]> Creatis software - creaImageIO.git/blob - win64/sqlite/sqlite3.c
4db4846b9731ada4225da7827d93db42e7b1233f
[creaImageIO.git] / win64 / sqlite / sqlite3.c
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.6.23.1.  By combining all the individual C code files into this 
4 ** single large file, the entire code can be compiled as a one translation
5 ** unit.  This allows many compilers to do optimizations that would not be
6 ** possible if the files were compiled separately.  Performance improvements
7 ** of 5% are more are commonly seen when SQLite is compiled as a single
8 ** translation unit.
9 **
10 ** This file is all you need to compile SQLite.  To use SQLite in other
11 ** programs, you need this file and the "sqlite3.h" header file that defines
12 ** the programming interface to the SQLite library.  (If you do not have 
13 ** the "sqlite3.h" header file at hand, you will find a copy embedded within
14 ** the text of this file.  Search for "Begin file sqlite3.h" to find the start
15 ** of the embedded sqlite3.h header file.) Additional code files may be needed
16 ** if you want a wrapper to interface SQLite with your choice of programming
17 ** language. The code for the "sqlite3" command-line shell is also in a
18 ** separate file. This file contains only code for the core SQLite library.
19 */
20 #define SQLITE_CORE 1
21 #define SQLITE_AMALGAMATION 1
22 #ifndef SQLITE_PRIVATE
23 # define SQLITE_PRIVATE static
24 #endif
25 #ifndef SQLITE_API
26 # define SQLITE_API
27 #endif
28 /************** Begin file sqliteInt.h ***************************************/
29 /*
30 ** 2001 September 15
31 **
32 ** The author disclaims copyright to this source code.  In place of
33 ** a legal notice, here is a blessing:
34 **
35 **    May you do good and not evil.
36 **    May you find forgiveness for yourself and forgive others.
37 **    May you share freely, never taking more than you give.
38 **
39 *************************************************************************
40 ** Internal interface definitions for SQLite.
41 **
42 */
43 #ifndef _SQLITEINT_H_
44 #define _SQLITEINT_H_
45
46 /*
47 ** These #defines should enable >2GB file support on POSIX if the
48 ** underlying operating system supports it.  If the OS lacks
49 ** large file support, or if the OS is windows, these should be no-ops.
50 **
51 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
52 ** system #includes.  Hence, this block of code must be the very first
53 ** code in all source files.
54 **
55 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
56 ** on the compiler command line.  This is necessary if you are compiling
57 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
58 ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
59 ** without this option, LFS is enable.  But LFS does not exist in the kernel
60 ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
61 ** portability you should omit LFS.
62 **
63 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
64 */
65 #ifndef SQLITE_DISABLE_LFS
66 # define _LARGE_FILE       1
67 # ifndef _FILE_OFFSET_BITS
68 #   define _FILE_OFFSET_BITS 64
69 # endif
70 # define _LARGEFILE_SOURCE 1
71 #endif
72
73 /*
74 ** Include the configuration header output by 'configure' if we're using the
75 ** autoconf-based build
76 */
77 #ifdef _HAVE_SQLITE_CONFIG_H
78 #include "config.h"
79 #endif
80
81 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
82 /************** Begin file sqliteLimit.h *************************************/
83 /*
84 ** 2007 May 7
85 **
86 ** The author disclaims copyright to this source code.  In place of
87 ** a legal notice, here is a blessing:
88 **
89 **    May you do good and not evil.
90 **    May you find forgiveness for yourself and forgive others.
91 **    May you share freely, never taking more than you give.
92 **
93 *************************************************************************
94 ** 
95 ** This file defines various limits of what SQLite can process.
96 */
97
98 /*
99 ** The maximum length of a TEXT or BLOB in bytes.   This also
100 ** limits the size of a row in a table or index.
101 **
102 ** The hard limit is the ability of a 32-bit signed integer
103 ** to count the size: 2^31-1 or 2147483647.
104 */
105 #ifndef SQLITE_MAX_LENGTH
106 # define SQLITE_MAX_LENGTH 1000000000
107 #endif
108
109 /*
110 ** This is the maximum number of
111 **
112 **    * Columns in a table
113 **    * Columns in an index
114 **    * Columns in a view
115 **    * Terms in the SET clause of an UPDATE statement
116 **    * Terms in the result set of a SELECT statement
117 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
118 **    * Terms in the VALUES clause of an INSERT statement
119 **
120 ** The hard upper limit here is 32676.  Most database people will
121 ** tell you that in a well-normalized database, you usually should
122 ** not have more than a dozen or so columns in any table.  And if
123 ** that is the case, there is no point in having more than a few
124 ** dozen values in any of the other situations described above.
125 */
126 #ifndef SQLITE_MAX_COLUMN
127 # define SQLITE_MAX_COLUMN 2000
128 #endif
129
130 /*
131 ** The maximum length of a single SQL statement in bytes.
132 **
133 ** It used to be the case that setting this value to zero would
134 ** turn the limit off.  That is no longer true.  It is not possible
135 ** to turn this limit off.
136 */
137 #ifndef SQLITE_MAX_SQL_LENGTH
138 # define SQLITE_MAX_SQL_LENGTH 1000000000
139 #endif
140
141 /*
142 ** The maximum depth of an expression tree. This is limited to 
143 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
144 ** want to place more severe limits on the complexity of an 
145 ** expression.
146 **
147 ** A value of 0 used to mean that the limit was not enforced.
148 ** But that is no longer true.  The limit is now strictly enforced
149 ** at all times.
150 */
151 #ifndef SQLITE_MAX_EXPR_DEPTH
152 # define SQLITE_MAX_EXPR_DEPTH 1000
153 #endif
154
155 /*
156 ** The maximum number of terms in a compound SELECT statement.
157 ** The code generator for compound SELECT statements does one
158 ** level of recursion for each term.  A stack overflow can result
159 ** if the number of terms is too large.  In practice, most SQL
160 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
161 ** any limit on the number of terms in a compount SELECT.
162 */
163 #ifndef SQLITE_MAX_COMPOUND_SELECT
164 # define SQLITE_MAX_COMPOUND_SELECT 500
165 #endif
166
167 /*
168 ** The maximum number of opcodes in a VDBE program.
169 ** Not currently enforced.
170 */
171 #ifndef SQLITE_MAX_VDBE_OP
172 # define SQLITE_MAX_VDBE_OP 25000
173 #endif
174
175 /*
176 ** The maximum number of arguments to an SQL function.
177 */
178 #ifndef SQLITE_MAX_FUNCTION_ARG
179 # define SQLITE_MAX_FUNCTION_ARG 127
180 #endif
181
182 /*
183 ** The maximum number of in-memory pages to use for the main database
184 ** table and for temporary tables.  The SQLITE_DEFAULT_CACHE_SIZE
185 */
186 #ifndef SQLITE_DEFAULT_CACHE_SIZE
187 # define SQLITE_DEFAULT_CACHE_SIZE  2000
188 #endif
189 #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
190 # define SQLITE_DEFAULT_TEMP_CACHE_SIZE  500
191 #endif
192
193 /*
194 ** The maximum number of attached databases.  This must be between 0
195 ** and 30.  The upper bound on 30 is because a 32-bit integer bitmap
196 ** is used internally to track attached databases.
197 */
198 #ifndef SQLITE_MAX_ATTACHED
199 # define SQLITE_MAX_ATTACHED 10
200 #endif
201
202
203 /*
204 ** The maximum value of a ?nnn wildcard that the parser will accept.
205 */
206 #ifndef SQLITE_MAX_VARIABLE_NUMBER
207 # define SQLITE_MAX_VARIABLE_NUMBER 999
208 #endif
209
210 /* Maximum page size.  The upper bound on this value is 32768.  This a limit
211 ** imposed by the necessity of storing the value in a 2-byte unsigned integer
212 ** and the fact that the page size must be a power of 2.
213 **
214 ** If this limit is changed, then the compiled library is technically
215 ** incompatible with an SQLite library compiled with a different limit. If
216 ** a process operating on a database with a page-size of 65536 bytes 
217 ** crashes, then an instance of SQLite compiled with the default page-size 
218 ** limit will not be able to rollback the aborted transaction. This could
219 ** lead to database corruption.
220 */
221 #ifndef SQLITE_MAX_PAGE_SIZE
222 # define SQLITE_MAX_PAGE_SIZE 32768
223 #endif
224
225
226 /*
227 ** The default size of a database page.
228 */
229 #ifndef SQLITE_DEFAULT_PAGE_SIZE
230 # define SQLITE_DEFAULT_PAGE_SIZE 1024
231 #endif
232 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
233 # undef SQLITE_DEFAULT_PAGE_SIZE
234 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
235 #endif
236
237 /*
238 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
239 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
240 ** device characteristics (sector-size and atomic write() support),
241 ** SQLite may choose a larger value. This constant is the maximum value
242 ** SQLite will choose on its own.
243 */
244 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
245 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
246 #endif
247 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
248 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
249 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
250 #endif
251
252
253 /*
254 ** Maximum number of pages in one database file.
255 **
256 ** This is really just the default value for the max_page_count pragma.
257 ** This value can be lowered (or raised) at run-time using that the
258 ** max_page_count macro.
259 */
260 #ifndef SQLITE_MAX_PAGE_COUNT
261 # define SQLITE_MAX_PAGE_COUNT 1073741823
262 #endif
263
264 /*
265 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
266 ** operator.
267 */
268 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
269 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
270 #endif
271
272 /*
273 ** Maximum depth of recursion for triggers.
274 **
275 ** A value of 1 means that a trigger program will not be able to itself
276 ** fire any triggers. A value of 0 means that no trigger programs at all 
277 ** may be executed.
278 */
279 #ifndef SQLITE_MAX_TRIGGER_DEPTH
280 # define SQLITE_MAX_TRIGGER_DEPTH 1000
281 #endif
282
283 /************** End of sqliteLimit.h *****************************************/
284 /************** Continuing where we left off in sqliteInt.h ******************/
285
286 /* Disable nuisance warnings on Borland compilers */
287 #if defined(__BORLANDC__)
288 #pragma warn -rch /* unreachable code */
289 #pragma warn -ccc /* Condition is always true or false */
290 #pragma warn -aus /* Assigned value is never used */
291 #pragma warn -csu /* Comparing signed and unsigned */
292 #pragma warn -spa /* Suspicious pointer arithmetic */
293 #endif
294
295 /* Needed for various definitions... */
296 #ifndef _GNU_SOURCE
297 # define _GNU_SOURCE
298 #endif
299
300 /*
301 ** Include standard header files as necessary
302 */
303 #ifdef HAVE_STDINT_H
304 #include <stdint.h>
305 #endif
306 #ifdef HAVE_INTTYPES_H
307 #include <inttypes.h>
308 #endif
309
310 /*
311 ** The number of samples of an index that SQLite takes in order to 
312 ** construct a histogram of the table content when running ANALYZE
313 ** and with SQLITE_ENABLE_STAT2
314 */
315 #define SQLITE_INDEX_SAMPLES 10
316
317 /*
318 ** The following macros are used to cast pointers to integers and
319 ** integers to pointers.  The way you do this varies from one compiler
320 ** to the next, so we have developed the following set of #if statements
321 ** to generate appropriate macros for a wide range of compilers.
322 **
323 ** The correct "ANSI" way to do this is to use the intptr_t type. 
324 ** Unfortunately, that typedef is not available on all compilers, or
325 ** if it is available, it requires an #include of specific headers
326 ** that very from one machine to the next.
327 **
328 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
329 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
330 ** So we have to define the macros in different ways depending on the
331 ** compiler.
332 */
333 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
334 # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
335 # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
336 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
337 # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
338 # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
339 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
340 # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
341 # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
342 #else                          /* Generates a warning - but it always works */
343 # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
344 # define SQLITE_PTR_TO_INT(X)  ((int)(X))
345 #endif
346
347 /*
348 ** The SQLITE_THREADSAFE macro must be defined as either 0 or 1.
349 ** Older versions of SQLite used an optional THREADSAFE macro.
350 ** We support that for legacy
351 */
352 #if !defined(SQLITE_THREADSAFE)
353 #if defined(THREADSAFE)
354 # define SQLITE_THREADSAFE THREADSAFE
355 #else
356 # define SQLITE_THREADSAFE 1
357 #endif
358 #endif
359
360 /*
361 ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
362 ** It determines whether or not the features related to 
363 ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
364 ** be overridden at runtime using the sqlite3_config() API.
365 */
366 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
367 # define SQLITE_DEFAULT_MEMSTATUS 1
368 #endif
369
370 /*
371 ** Exactly one of the following macros must be defined in order to
372 ** specify which memory allocation subsystem to use.
373 **
374 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
375 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
376 **
377 ** (Historical note:  There used to be several other options, but we've
378 ** pared it down to just these two.)
379 **
380 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
381 ** the default.
382 */
383 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)>1
384 # error "At most one of the following compile-time configuration options\
385  is allows: SQLITE_SYSTEM_MALLOC, SQLITE_MEMDEBUG"
386 #endif
387 #if defined(SQLITE_SYSTEM_MALLOC)+defined(SQLITE_MEMDEBUG)==0
388 # define SQLITE_SYSTEM_MALLOC 1
389 #endif
390
391 /*
392 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
393 ** sizes of memory allocations below this value where possible.
394 */
395 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
396 # define SQLITE_MALLOC_SOFT_LIMIT 1024
397 #endif
398
399 /*
400 ** We need to define _XOPEN_SOURCE as follows in order to enable
401 ** recursive mutexes on most Unix systems.  But Mac OS X is different.
402 ** The _XOPEN_SOURCE define causes problems for Mac OS X we are told,
403 ** so it is omitted there.  See ticket #2673.
404 **
405 ** Later we learn that _XOPEN_SOURCE is poorly or incorrectly
406 ** implemented on some systems.  So we avoid defining it at all
407 ** if it is already defined or if it is unneeded because we are
408 ** not doing a threadsafe build.  Ticket #2681.
409 **
410 ** See also ticket #2741.
411 */
412 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__) && SQLITE_THREADSAFE
413 #  define _XOPEN_SOURCE 500  /* Needed to enable pthread recursive mutexes */
414 #endif
415
416 /*
417 ** The TCL headers are only needed when compiling the TCL bindings.
418 */
419 #if defined(SQLITE_TCL) || defined(TCLSH)
420 # include <tcl.h>
421 #endif
422
423 /*
424 ** Many people are failing to set -DNDEBUG=1 when compiling SQLite.
425 ** Setting NDEBUG makes the code smaller and run faster.  So the following
426 ** lines are added to automatically set NDEBUG unless the -DSQLITE_DEBUG=1
427 ** option is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
428 ** feature.
429 */
430 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
431 # define NDEBUG 1
432 #endif
433
434 /*
435 ** The testcase() macro is used to aid in coverage testing.  When 
436 ** doing coverage testing, the condition inside the argument to
437 ** testcase() must be evaluated both true and false in order to
438 ** get full branch coverage.  The testcase() macro is inserted
439 ** to help ensure adequate test coverage in places where simple
440 ** condition/decision coverage is inadequate.  For example, testcase()
441 ** can be used to make sure boundary values are tested.  For
442 ** bitmask tests, testcase() can be used to make sure each bit
443 ** is significant and used at least once.  On switch statements
444 ** where multiple cases go to the same block of code, testcase()
445 ** can insure that all cases are evaluated.
446 **
447 */
448 #ifdef SQLITE_COVERAGE_TEST
449 SQLITE_PRIVATE   void sqlite3Coverage(int);
450 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
451 #else
452 # define testcase(X)
453 #endif
454
455 /*
456 ** The TESTONLY macro is used to enclose variable declarations or
457 ** other bits of code that are needed to support the arguments
458 ** within testcase() and assert() macros.
459 */
460 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
461 # define TESTONLY(X)  X
462 #else
463 # define TESTONLY(X)
464 #endif
465
466 /*
467 ** Sometimes we need a small amount of code such as a variable initialization
468 ** to setup for a later assert() statement.  We do not want this code to
469 ** appear when assert() is disabled.  The following macro is therefore
470 ** used to contain that setup code.  The "VVA" acronym stands for
471 ** "Verification, Validation, and Accreditation".  In other words, the
472 ** code within VVA_ONLY() will only run during verification processes.
473 */
474 #ifndef NDEBUG
475 # define VVA_ONLY(X)  X
476 #else
477 # define VVA_ONLY(X)
478 #endif
479
480 /*
481 ** The ALWAYS and NEVER macros surround boolean expressions which 
482 ** are intended to always be true or false, respectively.  Such
483 ** expressions could be omitted from the code completely.  But they
484 ** are included in a few cases in order to enhance the resilience
485 ** of SQLite to unexpected behavior - to make the code "self-healing"
486 ** or "ductile" rather than being "brittle" and crashing at the first
487 ** hint of unplanned behavior.
488 **
489 ** In other words, ALWAYS and NEVER are added for defensive code.
490 **
491 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
492 ** be true and false so that the unreachable code then specify will
493 ** not be counted as untested code.
494 */
495 #if defined(SQLITE_COVERAGE_TEST)
496 # define ALWAYS(X)      (1)
497 # define NEVER(X)       (0)
498 #elif !defined(NDEBUG)
499 # define ALWAYS(X)      ((X)?1:(assert(0),0))
500 # define NEVER(X)       ((X)?(assert(0),1):0)
501 #else
502 # define ALWAYS(X)      (X)
503 # define NEVER(X)       (X)
504 #endif
505
506 /*
507 ** The macro unlikely() is a hint that surrounds a boolean
508 ** expression that is usually false.  Macro likely() surrounds
509 ** a boolean expression that is usually true.  GCC is able to
510 ** use these hints to generate better code, sometimes.
511 */
512 #if defined(__GNUC__) && 0
513 # define likely(X)    __builtin_expect((X),1)
514 # define unlikely(X)  __builtin_expect((X),0)
515 #else
516 # define likely(X)    !!(X)
517 # define unlikely(X)  !!(X)
518 #endif
519
520 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
521 /************** Begin file sqlite3.h *****************************************/
522 /*
523 ** 2001 September 15
524 **
525 ** The author disclaims copyright to this source code.  In place of
526 ** a legal notice, here is a blessing:
527 **
528 **    May you do good and not evil.
529 **    May you find forgiveness for yourself and forgive others.
530 **    May you share freely, never taking more than you give.
531 **
532 *************************************************************************
533 ** This header file defines the interface that the SQLite library
534 ** presents to client programs.  If a C-function, structure, datatype,
535 ** or constant definition does not appear in this file, then it is
536 ** not a published API of SQLite, is subject to change without
537 ** notice, and should not be referenced by programs that use SQLite.
538 **
539 ** Some of the definitions that are in this file are marked as
540 ** "experimental".  Experimental interfaces are normally new
541 ** features recently added to SQLite.  We do not anticipate changes
542 ** to experimental interfaces but reserve the right to make minor changes
543 ** if experience from use "in the wild" suggest such changes are prudent.
544 **
545 ** The official C-language API documentation for SQLite is derived
546 ** from comments in this file.  This file is the authoritative source
547 ** on how SQLite interfaces are suppose to operate.
548 **
549 ** The name of this file under configuration management is "sqlite.h.in".
550 ** The makefile makes some minor changes to this file (such as inserting
551 ** the version number) and changes its name to "sqlite3.h" as
552 ** part of the build process.
553 */
554 #ifndef _SQLITE3_H_
555 #define _SQLITE3_H_
556 #include <stdarg.h>     /* Needed for the definition of va_list */
557
558 /*
559 ** Make sure we can call this stuff from C++.
560 */
561 #if 0
562 extern "C" {
563 #endif
564
565
566 /*
567 ** Add the ability to override 'extern'
568 */
569 #ifndef SQLITE_EXTERN
570 # define SQLITE_EXTERN extern
571 #endif
572
573 #ifndef SQLITE_API
574 # define SQLITE_API
575 #endif
576
577
578 /*
579 ** These no-op macros are used in front of interfaces to mark those
580 ** interfaces as either deprecated or experimental.  New applications
581 ** should not use deprecated interfaces - they are support for backwards
582 ** compatibility only.  Application writers should be aware that
583 ** experimental interfaces are subject to change in point releases.
584 **
585 ** These macros used to resolve to various kinds of compiler magic that
586 ** would generate warning messages when they were used.  But that
587 ** compiler magic ended up generating such a flurry of bug reports
588 ** that we have taken it all out and gone back to using simple
589 ** noop macros.
590 */
591 #define SQLITE_DEPRECATED
592 #define SQLITE_EXPERIMENTAL
593
594 /*
595 ** Ensure these symbols were not defined by some previous header file.
596 */
597 #ifdef SQLITE_VERSION
598 # undef SQLITE_VERSION
599 #endif
600 #ifdef SQLITE_VERSION_NUMBER
601 # undef SQLITE_VERSION_NUMBER
602 #endif
603
604 /*
605 ** CAPI3REF: Compile-Time Library Version Numbers
606 **
607 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
608 ** evaluates to a string literal that is the SQLite version in the
609 ** format "X.Y.Z" where X is the major version number (always 3 for
610 ** SQLite3) and Y is the minor version number and Z is the release number.)^
611 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
612 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
613 ** numbers used in [SQLITE_VERSION].)^
614 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
615 ** be larger than the release from which it is derived.  Either Y will
616 ** be held constant and Z will be incremented or else Y will be incremented
617 ** and Z will be reset to zero.
618 **
619 ** Since version 3.6.18, SQLite source code has been stored in the
620 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
621 ** system</a>.  ^The SQLITE_SOURCE_ID macro evalutes to
622 ** a string which identifies a particular check-in of SQLite
623 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
624 ** string contains the date and time of the check-in (UTC) and an SHA1
625 ** hash of the entire source tree.
626 **
627 ** See also: [sqlite3_libversion()],
628 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
629 ** [sqlite_version()] and [sqlite_source_id()].
630 */
631 #define SQLITE_VERSION        "3.6.23.1"
632 #define SQLITE_VERSION_NUMBER 3006023
633 #define SQLITE_SOURCE_ID      "2010-03-26 22:28:06 b078b588d617e07886ad156e9f54ade6d823568e"
634
635 /*
636 ** CAPI3REF: Run-Time Library Version Numbers
637 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
638 **
639 ** These interfaces provide the same information as the [SQLITE_VERSION],
640 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
641 ** but are associated with the library instead of the header file.  ^(Cautious
642 ** programmers might include assert() statements in their application to
643 ** verify that values returned by these interfaces match the macros in
644 ** the header, and thus insure that the application is
645 ** compiled with matching library and header files.
646 **
647 ** <blockquote><pre>
648 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
649 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
650 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
651 ** </pre></blockquote>)^
652 **
653 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
654 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
655 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
656 ** function is provided for use in DLLs since DLL users usually do not have
657 ** direct access to string constants within the DLL.  ^The
658 ** sqlite3_libversion_number() function returns an integer equal to
659 ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns 
660 ** a pointer to a string constant whose value is the same as the 
661 ** [SQLITE_SOURCE_ID] C preprocessor macro.
662 **
663 ** See also: [sqlite_version()] and [sqlite_source_id()].
664 */
665 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
666 SQLITE_API const char *sqlite3_libversion(void);
667 SQLITE_API const char *sqlite3_sourceid(void);
668 SQLITE_API int sqlite3_libversion_number(void);
669
670 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
671 /*
672 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
673 **
674 ** ^The sqlite3_compileoption_used() function returns 0 or 1 
675 ** indicating whether the specified option was defined at 
676 ** compile time.  ^The SQLITE_ prefix may be omitted from the 
677 ** option name passed to sqlite3_compileoption_used().  
678 **
679 ** ^The sqlite3_compileoption_get() function allows interating
680 ** over the list of options that were defined at compile time by
681 ** returning the N-th compile time option string.  ^If N is out of range,
682 ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ 
683 ** prefix is omitted from any strings returned by 
684 ** sqlite3_compileoption_get().
685 **
686 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
687 ** and sqlite3_compileoption_get() may be omitted by specifing the 
688 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
689 **
690 ** See also: SQL functions [sqlite_compileoption_used()] and
691 ** [sqlite_compileoption_get()] and the [compile_options pragma].
692 */
693 SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
694 SQLITE_API const char *sqlite3_compileoption_get(int N);
695 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
696
697 /*
698 ** CAPI3REF: Test To See If The Library Is Threadsafe
699 **
700 ** ^The sqlite3_threadsafe() function returns zero if and only if
701 ** SQLite was compiled mutexing code omitted due to the
702 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
703 **
704 ** SQLite can be compiled with or without mutexes.  When
705 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
706 ** are enabled and SQLite is threadsafe.  When the
707 ** [SQLITE_THREADSAFE] macro is 0, 
708 ** the mutexes are omitted.  Without the mutexes, it is not safe
709 ** to use SQLite concurrently from more than one thread.
710 **
711 ** Enabling mutexes incurs a measurable performance penalty.
712 ** So if speed is of utmost importance, it makes sense to disable
713 ** the mutexes.  But for maximum safety, mutexes should be enabled.
714 ** ^The default behavior is for mutexes to be enabled.
715 **
716 ** This interface can be used by an application to make sure that the
717 ** version of SQLite that it is linking against was compiled with
718 ** the desired setting of the [SQLITE_THREADSAFE] macro.
719 **
720 ** This interface only reports on the compile-time mutex setting
721 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
722 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
723 ** can be fully or partially disabled using a call to [sqlite3_config()]
724 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
725 ** or [SQLITE_CONFIG_MUTEX].  ^(The return value of the
726 ** sqlite3_threadsafe() function shows only the compile-time setting of
727 ** thread safety, not any run-time changes to that setting made by
728 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
729 ** is unchanged by calls to sqlite3_config().)^
730 **
731 ** See the [threading mode] documentation for additional information.
732 */
733 SQLITE_API int sqlite3_threadsafe(void);
734
735 /*
736 ** CAPI3REF: Database Connection Handle
737 ** KEYWORDS: {database connection} {database connections}
738 **
739 ** Each open SQLite database is represented by a pointer to an instance of
740 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
741 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
742 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
743 ** is its destructor.  There are many other interfaces (such as
744 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
745 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
746 ** sqlite3 object.
747 */
748 typedef struct sqlite3 sqlite3;
749
750 /*
751 ** CAPI3REF: 64-Bit Integer Types
752 ** KEYWORDS: sqlite_int64 sqlite_uint64
753 **
754 ** Because there is no cross-platform way to specify 64-bit integer types
755 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
756 **
757 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
758 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
759 ** compatibility only.
760 **
761 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
762 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
763 ** sqlite3_uint64 and sqlite_uint64 types can store integer values 
764 ** between 0 and +18446744073709551615 inclusive.
765 */
766 #ifdef SQLITE_INT64_TYPE
767   typedef SQLITE_INT64_TYPE sqlite_int64;
768   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
769 #elif defined(_MSC_VER) || defined(__BORLANDC__)
770   typedef __int64 sqlite_int64;
771   typedef unsigned __int64 sqlite_uint64;
772 #else
773   typedef long long int sqlite_int64;
774   typedef unsigned long long int sqlite_uint64;
775 #endif
776 typedef sqlite_int64 sqlite3_int64;
777 typedef sqlite_uint64 sqlite3_uint64;
778
779 /*
780 ** If compiling for a processor that lacks floating point support,
781 ** substitute integer for floating-point.
782 */
783 #ifdef SQLITE_OMIT_FLOATING_POINT
784 # define double sqlite3_int64
785 #endif
786
787 /*
788 ** CAPI3REF: Closing A Database Connection
789 **
790 ** ^The sqlite3_close() routine is the destructor for the [sqlite3] object.
791 ** ^Calls to sqlite3_close() return SQLITE_OK if the [sqlite3] object is
792 ** successfullly destroyed and all associated resources are deallocated.
793 **
794 ** Applications must [sqlite3_finalize | finalize] all [prepared statements]
795 ** and [sqlite3_blob_close | close] all [BLOB handles] associated with
796 ** the [sqlite3] object prior to attempting to close the object.  ^If
797 ** sqlite3_close() is called on a [database connection] that still has
798 ** outstanding [prepared statements] or [BLOB handles], then it returns
799 ** SQLITE_BUSY.
800 **
801 ** ^If [sqlite3_close()] is invoked while a transaction is open,
802 ** the transaction is automatically rolled back.
803 **
804 ** The C parameter to [sqlite3_close(C)] must be either a NULL
805 ** pointer or an [sqlite3] object pointer obtained
806 ** from [sqlite3_open()], [sqlite3_open16()], or
807 ** [sqlite3_open_v2()], and not previously closed.
808 ** ^Calling sqlite3_close() with a NULL pointer argument is a 
809 ** harmless no-op.
810 */
811 SQLITE_API int sqlite3_close(sqlite3 *);
812
813 /*
814 ** The type for a callback function.
815 ** This is legacy and deprecated.  It is included for historical
816 ** compatibility and is not documented.
817 */
818 typedef int (*sqlite3_callback)(void*,int,char**, char**);
819
820 /*
821 ** CAPI3REF: One-Step Query Execution Interface
822 **
823 ** The sqlite3_exec() interface is a convenience wrapper around
824 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
825 ** that allows an application to run multiple statements of SQL
826 ** without having to use a lot of C code. 
827 **
828 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
829 ** semicolon-separate SQL statements passed into its 2nd argument,
830 ** in the context of the [database connection] passed in as its 1st
831 ** argument.  ^If the callback function of the 3rd argument to
832 ** sqlite3_exec() is not NULL, then it is invoked for each result row
833 ** coming out of the evaluated SQL statements.  ^The 4th argument to
834 ** to sqlite3_exec() is relayed through to the 1st argument of each
835 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
836 ** is NULL, then no callback is ever invoked and result rows are
837 ** ignored.
838 **
839 ** ^If an error occurs while evaluating the SQL statements passed into
840 ** sqlite3_exec(), then execution of the current statement stops and
841 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
842 ** is not NULL then any error message is written into memory obtained
843 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
844 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
845 ** on error message strings returned through the 5th parameter of
846 ** of sqlite3_exec() after the error message string is no longer needed.
847 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
848 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
849 ** NULL before returning.
850 **
851 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
852 ** routine returns SQLITE_ABORT without invoking the callback again and
853 ** without running any subsequent SQL statements.
854 **
855 ** ^The 2nd argument to the sqlite3_exec() callback function is the
856 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
857 ** callback is an array of pointers to strings obtained as if from
858 ** [sqlite3_column_text()], one for each column.  ^If an element of a
859 ** result row is NULL then the corresponding string pointer for the
860 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
861 ** sqlite3_exec() callback is an array of pointers to strings where each
862 ** entry represents the name of corresponding result column as obtained
863 ** from [sqlite3_column_name()].
864 **
865 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
866 ** to an empty string, or a pointer that contains only whitespace and/or 
867 ** SQL comments, then no SQL statements are evaluated and the database
868 ** is not changed.
869 **
870 ** Restrictions:
871 **
872 ** <ul>
873 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
874 **      is a valid and open [database connection].
875 ** <li> The application must not close [database connection] specified by
876 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
877 ** <li> The application must not modify the SQL statement text passed into
878 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
879 ** </ul>
880 */
881 SQLITE_API int sqlite3_exec(
882   sqlite3*,                                  /* An open database */
883   const char *sql,                           /* SQL to be evaluated */
884   int (*callback)(void*,int,char**,char**),  /* Callback function */
885   void *,                                    /* 1st argument to callback */
886   char **errmsg                              /* Error msg written here */
887 );
888
889 /*
890 ** CAPI3REF: Result Codes
891 ** KEYWORDS: SQLITE_OK {error code} {error codes}
892 ** KEYWORDS: {result code} {result codes}
893 **
894 ** Many SQLite functions return an integer result code from the set shown
895 ** here in order to indicates success or failure.
896 **
897 ** New error codes may be added in future versions of SQLite.
898 **
899 ** See also: [SQLITE_IOERR_READ | extended result codes]
900 */
901 #define SQLITE_OK           0   /* Successful result */
902 /* beginning-of-error-codes */
903 #define SQLITE_ERROR        1   /* SQL error or missing database */
904 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
905 #define SQLITE_PERM         3   /* Access permission denied */
906 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
907 #define SQLITE_BUSY         5   /* The database file is locked */
908 #define SQLITE_LOCKED       6   /* A table in the database is locked */
909 #define SQLITE_NOMEM        7   /* A malloc() failed */
910 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
911 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
912 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
913 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
914 #define SQLITE_NOTFOUND    12   /* NOT USED. Table or record not found */
915 #define SQLITE_FULL        13   /* Insertion failed because database is full */
916 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
917 #define SQLITE_PROTOCOL    15   /* NOT USED. Database lock protocol error */
918 #define SQLITE_EMPTY       16   /* Database is empty */
919 #define SQLITE_SCHEMA      17   /* The database schema changed */
920 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
921 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
922 #define SQLITE_MISMATCH    20   /* Data type mismatch */
923 #define SQLITE_MISUSE      21   /* Library used incorrectly */
924 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
925 #define SQLITE_AUTH        23   /* Authorization denied */
926 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
927 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
928 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
929 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
930 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
931 /* end-of-error-codes */
932
933 /*
934 ** CAPI3REF: Extended Result Codes
935 ** KEYWORDS: {extended error code} {extended error codes}
936 ** KEYWORDS: {extended result code} {extended result codes}
937 **
938 ** In its default configuration, SQLite API routines return one of 26 integer
939 ** [SQLITE_OK | result codes].  However, experience has shown that many of
940 ** these result codes are too coarse-grained.  They do not provide as
941 ** much information about problems as programmers might like.  In an effort to
942 ** address this, newer versions of SQLite (version 3.3.8 and later) include
943 ** support for additional result codes that provide more detailed information
944 ** about errors. The extended result codes are enabled or disabled
945 ** on a per database connection basis using the
946 ** [sqlite3_extended_result_codes()] API.
947 **
948 ** Some of the available extended result codes are listed here.
949 ** One may expect the number of extended result codes will be expand
950 ** over time.  Software that uses extended result codes should expect
951 ** to see new result codes in future releases of SQLite.
952 **
953 ** The SQLITE_OK result code will never be extended.  It will always
954 ** be exactly zero.
955 */
956 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
957 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
958 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
959 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
960 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
961 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
962 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
963 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
964 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
965 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
966 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
967 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
968 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
969 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
970 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
971 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
972 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
973 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED | (1<<8) )
974
975 /*
976 ** CAPI3REF: Flags For File Open Operations
977 **
978 ** These bit values are intended for use in the
979 ** 3rd parameter to the [sqlite3_open_v2()] interface and
980 ** in the 4th parameter to the xOpen method of the
981 ** [sqlite3_vfs] object.
982 */
983 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
984 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
985 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
986 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
987 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
988 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
989 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
990 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
991 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
992 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
993 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
994 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
995 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
996 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
997 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
998 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
999 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
1000
1001 /*
1002 ** CAPI3REF: Device Characteristics
1003 **
1004 ** The xDeviceCapabilities method of the [sqlite3_io_methods]
1005 ** object returns an integer which is a vector of the these
1006 ** bit values expressing I/O characteristics of the mass storage
1007 ** device that holds the file that the [sqlite3_io_methods]
1008 ** refers to.
1009 **
1010 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1011 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1012 ** mean that writes of blocks that are nnn bytes in size and
1013 ** are aligned to an address which is an integer multiple of
1014 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1015 ** that when data is appended to a file, the data is appended
1016 ** first then the size of the file is extended, never the other
1017 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1018 ** information is written to disk in the same order as calls
1019 ** to xWrite().
1020 */
1021 #define SQLITE_IOCAP_ATOMIC          0x00000001
1022 #define SQLITE_IOCAP_ATOMIC512       0x00000002
1023 #define SQLITE_IOCAP_ATOMIC1K        0x00000004
1024 #define SQLITE_IOCAP_ATOMIC2K        0x00000008
1025 #define SQLITE_IOCAP_ATOMIC4K        0x00000010
1026 #define SQLITE_IOCAP_ATOMIC8K        0x00000020
1027 #define SQLITE_IOCAP_ATOMIC16K       0x00000040
1028 #define SQLITE_IOCAP_ATOMIC32K       0x00000080
1029 #define SQLITE_IOCAP_ATOMIC64K       0x00000100
1030 #define SQLITE_IOCAP_SAFE_APPEND     0x00000200
1031 #define SQLITE_IOCAP_SEQUENTIAL      0x00000400
1032
1033 /*
1034 ** CAPI3REF: File Locking Levels
1035 **
1036 ** SQLite uses one of these integer values as the second
1037 ** argument to calls it makes to the xLock() and xUnlock() methods
1038 ** of an [sqlite3_io_methods] object.
1039 */
1040 #define SQLITE_LOCK_NONE          0
1041 #define SQLITE_LOCK_SHARED        1
1042 #define SQLITE_LOCK_RESERVED      2
1043 #define SQLITE_LOCK_PENDING       3
1044 #define SQLITE_LOCK_EXCLUSIVE     4
1045
1046 /*
1047 ** CAPI3REF: Synchronization Type Flags
1048 **
1049 ** When SQLite invokes the xSync() method of an
1050 ** [sqlite3_io_methods] object it uses a combination of
1051 ** these integer values as the second argument.
1052 **
1053 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
1054 ** sync operation only needs to flush data to mass storage.  Inode
1055 ** information need not be flushed. If the lower four bits of the flag
1056 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
1057 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
1058 ** to use Mac OS X style fullsync instead of fsync().
1059 */
1060 #define SQLITE_SYNC_NORMAL        0x00002
1061 #define SQLITE_SYNC_FULL          0x00003
1062 #define SQLITE_SYNC_DATAONLY      0x00010
1063
1064 /*
1065 ** CAPI3REF: OS Interface Open File Handle
1066 **
1067 ** An [sqlite3_file] object represents an open file in the 
1068 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
1069 ** implementations will
1070 ** want to subclass this object by appending additional fields
1071 ** for their own use.  The pMethods entry is a pointer to an
1072 ** [sqlite3_io_methods] object that defines methods for performing
1073 ** I/O operations on the open file.
1074 */
1075 typedef struct sqlite3_file sqlite3_file;
1076 struct sqlite3_file {
1077   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
1078 };
1079
1080 /*
1081 ** CAPI3REF: OS Interface File Virtual Methods Object
1082 **
1083 ** Every file opened by the [sqlite3_vfs] xOpen method populates an
1084 ** [sqlite3_file] object (or, more commonly, a subclass of the
1085 ** [sqlite3_file] object) with a pointer to an instance of this object.
1086 ** This object defines the methods used to perform various operations
1087 ** against the open file represented by the [sqlite3_file] object.
1088 **
1089 ** If the xOpen method sets the sqlite3_file.pMethods element 
1090 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
1091 ** may be invoked even if the xOpen reported that it failed.  The
1092 ** only way to prevent a call to xClose following a failed xOpen
1093 ** is for the xOpen to set the sqlite3_file.pMethods element to NULL.
1094 **
1095 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
1096 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
1097 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
1098 ** flag may be ORed in to indicate that only the data of the file
1099 ** and not its inode needs to be synced.
1100 **
1101 ** The integer values to xLock() and xUnlock() are one of
1102 ** <ul>
1103 ** <li> [SQLITE_LOCK_NONE],
1104 ** <li> [SQLITE_LOCK_SHARED],
1105 ** <li> [SQLITE_LOCK_RESERVED],
1106 ** <li> [SQLITE_LOCK_PENDING], or
1107 ** <li> [SQLITE_LOCK_EXCLUSIVE].
1108 ** </ul>
1109 ** xLock() increases the lock. xUnlock() decreases the lock.
1110 ** The xCheckReservedLock() method checks whether any database connection,
1111 ** either in this process or in some other process, is holding a RESERVED,
1112 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
1113 ** if such a lock exists and false otherwise.
1114 **
1115 ** The xFileControl() method is a generic interface that allows custom
1116 ** VFS implementations to directly control an open file using the
1117 ** [sqlite3_file_control()] interface.  The second "op" argument is an
1118 ** integer opcode.  The third argument is a generic pointer intended to
1119 ** point to a structure that may contain arguments or space in which to
1120 ** write return values.  Potential uses for xFileControl() might be
1121 ** functions to enable blocking locks with timeouts, to change the
1122 ** locking strategy (for example to use dot-file locks), to inquire
1123 ** about the status of a lock, or to break stale locks.  The SQLite
1124 ** core reserves all opcodes less than 100 for its own use.
1125 ** A [SQLITE_FCNTL_LOCKSTATE | list of opcodes] less than 100 is available.
1126 ** Applications that define a custom xFileControl method should use opcodes
1127 ** greater than 100 to avoid conflicts.
1128 **
1129 ** The xSectorSize() method returns the sector size of the
1130 ** device that underlies the file.  The sector size is the
1131 ** minimum write that can be performed without disturbing
1132 ** other bytes in the file.  The xDeviceCharacteristics()
1133 ** method returns a bit vector describing behaviors of the
1134 ** underlying device:
1135 **
1136 ** <ul>
1137 ** <li> [SQLITE_IOCAP_ATOMIC]
1138 ** <li> [SQLITE_IOCAP_ATOMIC512]
1139 ** <li> [SQLITE_IOCAP_ATOMIC1K]
1140 ** <li> [SQLITE_IOCAP_ATOMIC2K]
1141 ** <li> [SQLITE_IOCAP_ATOMIC4K]
1142 ** <li> [SQLITE_IOCAP_ATOMIC8K]
1143 ** <li> [SQLITE_IOCAP_ATOMIC16K]
1144 ** <li> [SQLITE_IOCAP_ATOMIC32K]
1145 ** <li> [SQLITE_IOCAP_ATOMIC64K]
1146 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
1147 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
1148 ** </ul>
1149 **
1150 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
1151 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
1152 ** mean that writes of blocks that are nnn bytes in size and
1153 ** are aligned to an address which is an integer multiple of
1154 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
1155 ** that when data is appended to a file, the data is appended
1156 ** first then the size of the file is extended, never the other
1157 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
1158 ** information is written to disk in the same order as calls
1159 ** to xWrite().
1160 **
1161 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
1162 ** in the unread portions of the buffer with zeros.  A VFS that
1163 ** fails to zero-fill short reads might seem to work.  However,
1164 ** failure to zero-fill short reads will eventually lead to
1165 ** database corruption.
1166 */
1167 typedef struct sqlite3_io_methods sqlite3_io_methods;
1168 struct sqlite3_io_methods {
1169   int iVersion;
1170   int (*xClose)(sqlite3_file*);
1171   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
1172   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
1173   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
1174   int (*xSync)(sqlite3_file*, int flags);
1175   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
1176   int (*xLock)(sqlite3_file*, int);
1177   int (*xUnlock)(sqlite3_file*, int);
1178   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
1179   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
1180   int (*xSectorSize)(sqlite3_file*);
1181   int (*xDeviceCharacteristics)(sqlite3_file*);
1182   /* Additional methods may be added in future releases */
1183 };
1184
1185 /*
1186 ** CAPI3REF: Standard File Control Opcodes
1187 **
1188 ** These integer constants are opcodes for the xFileControl method
1189 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
1190 ** interface.
1191 **
1192 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
1193 ** opcode causes the xFileControl method to write the current state of
1194 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
1195 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
1196 ** into an integer that the pArg argument points to. This capability
1197 ** is used during testing and only needs to be supported when SQLITE_TEST
1198 ** is defined.
1199 */
1200 #define SQLITE_FCNTL_LOCKSTATE        1
1201 #define SQLITE_GET_LOCKPROXYFILE      2
1202 #define SQLITE_SET_LOCKPROXYFILE      3
1203 #define SQLITE_LAST_ERRNO             4
1204
1205 /*
1206 ** CAPI3REF: Mutex Handle
1207 **
1208 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1209 ** abstract type for a mutex object.  The SQLite core never looks
1210 ** at the internal representation of an [sqlite3_mutex].  It only
1211 ** deals with pointers to the [sqlite3_mutex] object.
1212 **
1213 ** Mutexes are created using [sqlite3_mutex_alloc()].
1214 */
1215 typedef struct sqlite3_mutex sqlite3_mutex;
1216
1217 /*
1218 ** CAPI3REF: OS Interface Object
1219 **
1220 ** An instance of the sqlite3_vfs object defines the interface between
1221 ** the SQLite core and the underlying operating system.  The "vfs"
1222 ** in the name of the object stands for "virtual file system".
1223 **
1224 ** The value of the iVersion field is initially 1 but may be larger in
1225 ** future versions of SQLite.  Additional fields may be appended to this
1226 ** object when the iVersion value is increased.  Note that the structure
1227 ** of the sqlite3_vfs object changes in the transaction between
1228 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1229 ** modified.
1230 **
1231 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1232 ** structure used by this VFS.  mxPathname is the maximum length of
1233 ** a pathname in this VFS.
1234 **
1235 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1236 ** the pNext pointer.  The [sqlite3_vfs_register()]
1237 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1238 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1239 ** searches the list.  Neither the application code nor the VFS
1240 ** implementation should use the pNext pointer.
1241 **
1242 ** The pNext field is the only field in the sqlite3_vfs
1243 ** structure that SQLite will ever modify.  SQLite will only access
1244 ** or modify this field while holding a particular static mutex.
1245 ** The application should never modify anything within the sqlite3_vfs
1246 ** object once the object has been registered.
1247 **
1248 ** The zName field holds the name of the VFS module.  The name must
1249 ** be unique across all VFS modules.
1250 **
1251 ** SQLite will guarantee that the zFilename parameter to xOpen
1252 ** is either a NULL pointer or string obtained
1253 ** from xFullPathname().  SQLite further guarantees that
1254 ** the string will be valid and unchanged until xClose() is
1255 ** called. Because of the previous sentence,
1256 ** the [sqlite3_file] can safely store a pointer to the
1257 ** filename if it needs to remember the filename for some reason.
1258 ** If the zFilename parameter is xOpen is a NULL pointer then xOpen
1259 ** must invent its own temporary name for the file.  Whenever the 
1260 ** xFilename parameter is NULL it will also be the case that the
1261 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1262 **
1263 ** The flags argument to xOpen() includes all bits set in
1264 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1265 ** or [sqlite3_open16()] is used, then flags includes at least
1266 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
1267 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1268 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1269 **
1270 ** SQLite will also add one of the following flags to the xOpen()
1271 ** call, depending on the object being opened:
1272 **
1273 ** <ul>
1274 ** <li>  [SQLITE_OPEN_MAIN_DB]
1275 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1276 ** <li>  [SQLITE_OPEN_TEMP_DB]
1277 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1278 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1279 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1280 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1281 ** </ul>
1282 **
1283 ** The file I/O implementation can use the object type flags to
1284 ** change the way it deals with files.  For example, an application
1285 ** that does not care about crash recovery or rollback might make
1286 ** the open of a journal file a no-op.  Writes to this journal would
1287 ** also be no-ops, and any attempt to read the journal would return
1288 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1289 ** file will be doing page-aligned sector reads and writes in a random
1290 ** order and set up its I/O subsystem accordingly.
1291 **
1292 ** SQLite might also add one of the following flags to the xOpen method:
1293 **
1294 ** <ul>
1295 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1296 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1297 ** </ul>
1298 **
1299 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1300 ** deleted when it is closed.  The [SQLITE_OPEN_DELETEONCLOSE]
1301 ** will be set for TEMP  databases, journals and for subjournals.
1302 **
1303 ** The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1304 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1305 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1306 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
1307 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1308 ** be created, and that it is an error if it already exists.
1309 ** It is <i>not</i> used to indicate the file should be opened 
1310 ** for exclusive access.
1311 **
1312 ** At least szOsFile bytes of memory are allocated by SQLite
1313 ** to hold the  [sqlite3_file] structure passed as the third
1314 ** argument to xOpen.  The xOpen method does not have to
1315 ** allocate the structure; it should just fill it in.  Note that
1316 ** the xOpen method must set the sqlite3_file.pMethods to either
1317 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1318 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1319 ** element will be valid after xOpen returns regardless of the success
1320 ** or failure of the xOpen call.
1321 **
1322 ** The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1323 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1324 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1325 ** to test whether a file is at least readable.   The file can be a
1326 ** directory.
1327 **
1328 ** SQLite will always allocate at least mxPathname+1 bytes for the
1329 ** output buffer xFullPathname.  The exact size of the output buffer
1330 ** is also passed as a parameter to both  methods. If the output buffer
1331 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1332 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1333 ** to prevent this by setting mxPathname to a sufficiently large value.
1334 **
1335 ** The xRandomness(), xSleep(), and xCurrentTime() interfaces
1336 ** are not strictly a part of the filesystem, but they are
1337 ** included in the VFS structure for completeness.
1338 ** The xRandomness() function attempts to return nBytes bytes
1339 ** of good-quality randomness into zOut.  The return value is
1340 ** the actual number of bytes of randomness obtained.
1341 ** The xSleep() method causes the calling thread to sleep for at
1342 ** least the number of microseconds given.  The xCurrentTime()
1343 ** method returns a Julian Day Number for the current date and time.
1344 **
1345 */
1346 typedef struct sqlite3_vfs sqlite3_vfs;
1347 struct sqlite3_vfs {
1348   int iVersion;            /* Structure version number */
1349   int szOsFile;            /* Size of subclassed sqlite3_file */
1350   int mxPathname;          /* Maximum file pathname length */
1351   sqlite3_vfs *pNext;      /* Next registered VFS */
1352   const char *zName;       /* Name of this virtual file system */
1353   void *pAppData;          /* Pointer to application-specific data */
1354   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1355                int flags, int *pOutFlags);
1356   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1357   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1358   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1359   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1360   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1361   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1362   void (*xDlClose)(sqlite3_vfs*, void*);
1363   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1364   int (*xSleep)(sqlite3_vfs*, int microseconds);
1365   int (*xCurrentTime)(sqlite3_vfs*, double*);
1366   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1367   /* New fields may be appended in figure versions.  The iVersion
1368   ** value will increment whenever this happens. */
1369 };
1370
1371 /*
1372 ** CAPI3REF: Flags for the xAccess VFS method
1373 **
1374 ** These integer constants can be used as the third parameter to
1375 ** the xAccess method of an [sqlite3_vfs] object.  They determine
1376 ** what kind of permissions the xAccess method is looking for.
1377 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1378 ** simply checks whether the file exists.
1379 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1380 ** checks whether the file is both readable and writable.
1381 ** With SQLITE_ACCESS_READ, the xAccess method
1382 ** checks whether the file is readable.
1383 */
1384 #define SQLITE_ACCESS_EXISTS    0
1385 #define SQLITE_ACCESS_READWRITE 1
1386 #define SQLITE_ACCESS_READ      2
1387
1388 /*
1389 ** CAPI3REF: Initialize The SQLite Library
1390 **
1391 ** ^The sqlite3_initialize() routine initializes the
1392 ** SQLite library.  ^The sqlite3_shutdown() routine
1393 ** deallocates any resources that were allocated by sqlite3_initialize().
1394 ** These routines are designed to aid in process initialization and
1395 ** shutdown on embedded systems.  Workstation applications using
1396 ** SQLite normally do not need to invoke either of these routines.
1397 **
1398 ** A call to sqlite3_initialize() is an "effective" call if it is
1399 ** the first time sqlite3_initialize() is invoked during the lifetime of
1400 ** the process, or if it is the first time sqlite3_initialize() is invoked
1401 ** following a call to sqlite3_shutdown().  ^(Only an effective call
1402 ** of sqlite3_initialize() does any initialization.  All other calls
1403 ** are harmless no-ops.)^
1404 **
1405 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1406 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1407 ** an effective call to sqlite3_shutdown() does any deinitialization.
1408 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1409 **
1410 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1411 ** is not.  The sqlite3_shutdown() interface must only be called from a
1412 ** single thread.  All open [database connections] must be closed and all
1413 ** other SQLite resources must be deallocated prior to invoking
1414 ** sqlite3_shutdown().
1415 **
1416 ** Among other things, ^sqlite3_initialize() will invoke
1417 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1418 ** will invoke sqlite3_os_end().
1419 **
1420 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1421 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1422 ** the library (perhaps it is unable to allocate a needed resource such
1423 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1424 **
1425 ** ^The sqlite3_initialize() routine is called internally by many other
1426 ** SQLite interfaces so that an application usually does not need to
1427 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1428 ** calls sqlite3_initialize() so the SQLite library will be automatically
1429 ** initialized when [sqlite3_open()] is called if it has not be initialized
1430 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1431 ** compile-time option, then the automatic calls to sqlite3_initialize()
1432 ** are omitted and the application must call sqlite3_initialize() directly
1433 ** prior to using any other SQLite interface.  For maximum portability,
1434 ** it is recommended that applications always invoke sqlite3_initialize()
1435 ** directly prior to using any other SQLite interface.  Future releases
1436 ** of SQLite may require this.  In other words, the behavior exhibited
1437 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1438 ** default behavior in some future release of SQLite.
1439 **
1440 ** The sqlite3_os_init() routine does operating-system specific
1441 ** initialization of the SQLite library.  The sqlite3_os_end()
1442 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1443 ** performed by these routines include allocation or deallocation
1444 ** of static resources, initialization of global variables,
1445 ** setting up a default [sqlite3_vfs] module, or setting up
1446 ** a default configuration using [sqlite3_config()].
1447 **
1448 ** The application should never invoke either sqlite3_os_init()
1449 ** or sqlite3_os_end() directly.  The application should only invoke
1450 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1451 ** interface is called automatically by sqlite3_initialize() and
1452 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1453 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1454 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1455 ** When [custom builds | built for other platforms]
1456 ** (using the [SQLITE_OS_OTHER=1] compile-time
1457 ** option) the application must supply a suitable implementation for
1458 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1459 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1460 ** must return [SQLITE_OK] on success and some other [error code] upon
1461 ** failure.
1462 */
1463 SQLITE_API int sqlite3_initialize(void);
1464 SQLITE_API int sqlite3_shutdown(void);
1465 SQLITE_API int sqlite3_os_init(void);
1466 SQLITE_API int sqlite3_os_end(void);
1467
1468 /*
1469 ** CAPI3REF: Configuring The SQLite Library
1470 **
1471 ** The sqlite3_config() interface is used to make global configuration
1472 ** changes to SQLite in order to tune SQLite to the specific needs of
1473 ** the application.  The default configuration is recommended for most
1474 ** applications and so this routine is usually not necessary.  It is
1475 ** provided to support rare applications with unusual needs.
1476 **
1477 ** The sqlite3_config() interface is not threadsafe.  The application
1478 ** must insure that no other SQLite interfaces are invoked by other
1479 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1480 ** may only be invoked prior to library initialization using
1481 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1482 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1483 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1484 ** Note, however, that ^sqlite3_config() can be called as part of the
1485 ** implementation of an application-defined [sqlite3_os_init()].
1486 **
1487 ** The first argument to sqlite3_config() is an integer
1488 ** [SQLITE_CONFIG_SINGLETHREAD | configuration option] that determines
1489 ** what property of SQLite is to be configured.  Subsequent arguments
1490 ** vary depending on the [SQLITE_CONFIG_SINGLETHREAD | configuration option]
1491 ** in the first argument.
1492 **
1493 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1494 ** ^If the option is unknown or SQLite is unable to set the option
1495 ** then this routine returns a non-zero [error code].
1496 */
1497 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_config(int, ...);
1498
1499 /*
1500 ** CAPI3REF: Configure database connections
1501 ** EXPERIMENTAL
1502 **
1503 ** The sqlite3_db_config() interface is used to make configuration
1504 ** changes to a [database connection].  The interface is similar to
1505 ** [sqlite3_config()] except that the changes apply to a single
1506 ** [database connection] (specified in the first argument).  The
1507 ** sqlite3_db_config() interface should only be used immediately after
1508 ** the database connection is created using [sqlite3_open()],
1509 ** [sqlite3_open16()], or [sqlite3_open_v2()].  
1510 **
1511 ** The second argument to sqlite3_db_config(D,V,...)  is the
1512 ** configuration verb - an integer code that indicates what
1513 ** aspect of the [database connection] is being configured.
1514 ** The only choice for this value is [SQLITE_DBCONFIG_LOOKASIDE].
1515 ** New verbs are likely to be added in future releases of SQLite.
1516 ** Additional arguments depend on the verb.
1517 **
1518 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1519 ** the call is considered successful.
1520 */
1521 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_config(sqlite3*, int op, ...);
1522
1523 /*
1524 ** CAPI3REF: Memory Allocation Routines
1525 ** EXPERIMENTAL
1526 **
1527 ** An instance of this object defines the interface between SQLite
1528 ** and low-level memory allocation routines.
1529 **
1530 ** This object is used in only one place in the SQLite interface.
1531 ** A pointer to an instance of this object is the argument to
1532 ** [sqlite3_config()] when the configuration option is
1533 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
1534 ** By creating an instance of this object
1535 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1536 ** during configuration, an application can specify an alternative
1537 ** memory allocation subsystem for SQLite to use for all of its
1538 ** dynamic memory needs.
1539 **
1540 ** Note that SQLite comes with several [built-in memory allocators]
1541 ** that are perfectly adequate for the overwhelming majority of applications
1542 ** and that this object is only useful to a tiny minority of applications
1543 ** with specialized memory allocation requirements.  This object is
1544 ** also used during testing of SQLite in order to specify an alternative
1545 ** memory allocator that simulates memory out-of-memory conditions in
1546 ** order to verify that SQLite recovers gracefully from such
1547 ** conditions.
1548 **
1549 ** The xMalloc and xFree methods must work like the
1550 ** malloc() and free() functions from the standard C library.
1551 ** The xRealloc method must work like realloc() from the standard C library
1552 ** with the exception that if the second argument to xRealloc is zero,
1553 ** xRealloc must be a no-op - it must not perform any allocation or
1554 ** deallocation.  ^SQLite guarantees that the second argument to
1555 ** xRealloc is always a value returned by a prior call to xRoundup.
1556 ** And so in cases where xRoundup always returns a positive number,
1557 ** xRealloc can perform exactly as the standard library realloc() and
1558 ** still be in compliance with this specification.
1559 **
1560 ** xSize should return the allocated size of a memory allocation
1561 ** previously obtained from xMalloc or xRealloc.  The allocated size
1562 ** is always at least as big as the requested size but may be larger.
1563 **
1564 ** The xRoundup method returns what would be the allocated size of
1565 ** a memory allocation given a particular requested size.  Most memory
1566 ** allocators round up memory allocations at least to the next multiple
1567 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1568 ** Every memory allocation request coming in through [sqlite3_malloc()]
1569 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
1570 ** that causes the corresponding memory allocation to fail.
1571 **
1572 ** The xInit method initializes the memory allocator.  (For example,
1573 ** it might allocate any require mutexes or initialize internal data
1574 ** structures.  The xShutdown method is invoked (indirectly) by
1575 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1576 ** by xInit.  The pAppData pointer is used as the only parameter to
1577 ** xInit and xShutdown.
1578 **
1579 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1580 ** the xInit method, so the xInit method need not be threadsafe.  The
1581 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1582 ** not need to be threadsafe either.  For all other methods, SQLite
1583 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1584 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1585 ** it is by default) and so the methods are automatically serialized.
1586 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1587 ** methods must be threadsafe or else make their own arrangements for
1588 ** serialization.
1589 **
1590 ** SQLite will never invoke xInit() more than once without an intervening
1591 ** call to xShutdown().
1592 */
1593 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1594 struct sqlite3_mem_methods {
1595   void *(*xMalloc)(int);         /* Memory allocation function */
1596   void (*xFree)(void*);          /* Free a prior allocation */
1597   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1598   int (*xSize)(void*);           /* Return the size of an allocation */
1599   int (*xRoundup)(int);          /* Round up request size to allocation size */
1600   int (*xInit)(void*);           /* Initialize the memory allocator */
1601   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1602   void *pAppData;                /* Argument to xInit() and xShutdown() */
1603 };
1604
1605 /*
1606 ** CAPI3REF: Configuration Options
1607 ** EXPERIMENTAL
1608 **
1609 ** These constants are the available integer configuration options that
1610 ** can be passed as the first argument to the [sqlite3_config()] interface.
1611 **
1612 ** New configuration options may be added in future releases of SQLite.
1613 ** Existing configuration options might be discontinued.  Applications
1614 ** should check the return code from [sqlite3_config()] to make sure that
1615 ** the call worked.  The [sqlite3_config()] interface will return a
1616 ** non-zero [error code] if a discontinued or unsupported configuration option
1617 ** is invoked.
1618 **
1619 ** <dl>
1620 ** <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1621 ** <dd>There are no arguments to this option.  ^This option sets the
1622 ** [threading mode] to Single-thread.  In other words, it disables
1623 ** all mutexing and puts SQLite into a mode where it can only be used
1624 ** by a single thread.   ^If SQLite is compiled with
1625 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1626 ** it is not possible to change the [threading mode] from its default
1627 ** value of Single-thread and so [sqlite3_config()] will return 
1628 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1629 ** configuration option.</dd>
1630 **
1631 ** <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1632 ** <dd>There are no arguments to this option.  ^This option sets the
1633 ** [threading mode] to Multi-thread.  In other words, it disables
1634 ** mutexing on [database connection] and [prepared statement] objects.
1635 ** The application is responsible for serializing access to
1636 ** [database connections] and [prepared statements].  But other mutexes
1637 ** are enabled so that SQLite will be safe to use in a multi-threaded
1638 ** environment as long as no two threads attempt to use the same
1639 ** [database connection] at the same time.  ^If SQLite is compiled with
1640 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1641 ** it is not possible to set the Multi-thread [threading mode] and
1642 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1643 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1644 **
1645 ** <dt>SQLITE_CONFIG_SERIALIZED</dt>
1646 ** <dd>There are no arguments to this option.  ^This option sets the
1647 ** [threading mode] to Serialized. In other words, this option enables
1648 ** all mutexes including the recursive
1649 ** mutexes on [database connection] and [prepared statement] objects.
1650 ** In this mode (which is the default when SQLite is compiled with
1651 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1652 ** to [database connections] and [prepared statements] so that the
1653 ** application is free to use the same [database connection] or the
1654 ** same [prepared statement] in different threads at the same time.
1655 ** ^If SQLite is compiled with
1656 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1657 ** it is not possible to set the Serialized [threading mode] and
1658 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1659 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1660 **
1661 ** <dt>SQLITE_CONFIG_MALLOC</dt>
1662 ** <dd> ^(This option takes a single argument which is a pointer to an
1663 ** instance of the [sqlite3_mem_methods] structure.  The argument specifies
1664 ** alternative low-level memory allocation routines to be used in place of
1665 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1666 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1667 ** before the [sqlite3_config()] call returns.</dd>
1668 **
1669 ** <dt>SQLITE_CONFIG_GETMALLOC</dt>
1670 ** <dd> ^(This option takes a single argument which is a pointer to an
1671 ** instance of the [sqlite3_mem_methods] structure.  The [sqlite3_mem_methods]
1672 ** structure is filled with the currently defined memory allocation routines.)^
1673 ** This option can be used to overload the default memory allocation
1674 ** routines with a wrapper that simulations memory allocation failure or
1675 ** tracks memory usage, for example. </dd>
1676 **
1677 ** <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1678 ** <dd> ^This option takes single argument of type int, interpreted as a 
1679 ** boolean, which enables or disables the collection of memory allocation 
1680 ** statistics. ^(When memory allocation statistics are disabled, the 
1681 ** following SQLite interfaces become non-operational:
1682 **   <ul>
1683 **   <li> [sqlite3_memory_used()]
1684 **   <li> [sqlite3_memory_highwater()]
1685 **   <li> [sqlite3_soft_heap_limit()]
1686 **   <li> [sqlite3_status()]
1687 **   </ul>)^
1688 ** ^Memory allocation statistics are enabled by default unless SQLite is
1689 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1690 ** allocation statistics are disabled by default.
1691 ** </dd>
1692 **
1693 ** <dt>SQLITE_CONFIG_SCRATCH</dt>
1694 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1695 ** scratch memory.  There are three arguments:  A pointer an 8-byte
1696 ** aligned memory buffer from which the scrach allocations will be
1697 ** drawn, the size of each scratch allocation (sz),
1698 ** and the maximum number of scratch allocations (N).  The sz
1699 ** argument must be a multiple of 16. The sz parameter should be a few bytes
1700 ** larger than the actual scratch space required due to internal overhead.
1701 ** The first argument must be a pointer to an 8-byte aligned buffer
1702 ** of at least sz*N bytes of memory.
1703 ** ^SQLite will use no more than one scratch buffer per thread.  So
1704 ** N should be set to the expected maximum number of threads.  ^SQLite will
1705 ** never require a scratch buffer that is more than 6 times the database
1706 ** page size. ^If SQLite needs needs additional scratch memory beyond 
1707 ** what is provided by this configuration option, then 
1708 ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
1709 **
1710 ** <dt>SQLITE_CONFIG_PAGECACHE</dt>
1711 ** <dd> ^This option specifies a static memory buffer that SQLite can use for
1712 ** the database page cache with the default page cache implemenation.  
1713 ** This configuration should not be used if an application-define page
1714 ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE option.
1715 ** There are three arguments to this option: A pointer to 8-byte aligned
1716 ** memory, the size of each page buffer (sz), and the number of pages (N).
1717 ** The sz argument should be the size of the largest database page
1718 ** (a power of two between 512 and 32768) plus a little extra for each
1719 ** page header.  ^The page header size is 20 to 40 bytes depending on
1720 ** the host architecture.  ^It is harmless, apart from the wasted memory,
1721 ** to make sz a little too large.  The first
1722 ** argument should point to an allocation of at least sz*N bytes of memory.
1723 ** ^SQLite will use the memory provided by the first argument to satisfy its
1724 ** memory needs for the first N pages that it adds to cache.  ^If additional
1725 ** page cache memory is needed beyond what is provided by this option, then
1726 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
1727 ** ^The implementation might use one or more of the N buffers to hold 
1728 ** memory accounting information. The pointer in the first argument must
1729 ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
1730 ** will be undefined.</dd>
1731 **
1732 ** <dt>SQLITE_CONFIG_HEAP</dt>
1733 ** <dd> ^This option specifies a static memory buffer that SQLite will use
1734 ** for all of its dynamic memory allocation needs beyond those provided
1735 ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
1736 ** There are three arguments: An 8-byte aligned pointer to the memory,
1737 ** the number of bytes in the memory buffer, and the minimum allocation size.
1738 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1739 ** to using its default memory allocator (the system malloc() implementation),
1740 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1741 ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
1742 ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
1743 ** allocator is engaged to handle all of SQLites memory allocation needs.
1744 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1745 ** boundary or subsequent behavior of SQLite will be undefined.</dd>
1746 **
1747 ** <dt>SQLITE_CONFIG_MUTEX</dt>
1748 ** <dd> ^(This option takes a single argument which is a pointer to an
1749 ** instance of the [sqlite3_mutex_methods] structure.  The argument specifies
1750 ** alternative low-level mutex routines to be used in place
1751 ** the mutex routines built into SQLite.)^  ^SQLite makes a copy of the
1752 ** content of the [sqlite3_mutex_methods] structure before the call to
1753 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1754 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1755 ** the entire mutexing subsystem is omitted from the build and hence calls to
1756 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1757 ** return [SQLITE_ERROR].</dd>
1758 **
1759 ** <dt>SQLITE_CONFIG_GETMUTEX</dt>
1760 ** <dd> ^(This option takes a single argument which is a pointer to an
1761 ** instance of the [sqlite3_mutex_methods] structure.  The
1762 ** [sqlite3_mutex_methods]
1763 ** structure is filled with the currently defined mutex routines.)^
1764 ** This option can be used to overload the default mutex allocation
1765 ** routines with a wrapper used to track mutex usage for performance
1766 ** profiling or testing, for example.   ^If SQLite is compiled with
1767 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1768 ** the entire mutexing subsystem is omitted from the build and hence calls to
1769 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1770 ** return [SQLITE_ERROR].</dd>
1771 **
1772 ** <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1773 ** <dd> ^(This option takes two arguments that determine the default
1774 ** memory allocation for the lookaside memory allocator on each
1775 ** [database connection].  The first argument is the
1776 ** size of each lookaside buffer slot and the second is the number of
1777 ** slots allocated to each database connection.)^  ^(This option sets the
1778 ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1779 ** verb to [sqlite3_db_config()] can be used to change the lookaside
1780 ** configuration on individual connections.)^ </dd>
1781 **
1782 ** <dt>SQLITE_CONFIG_PCACHE</dt>
1783 ** <dd> ^(This option takes a single argument which is a pointer to
1784 ** an [sqlite3_pcache_methods] object.  This object specifies the interface
1785 ** to a custom page cache implementation.)^  ^SQLite makes a copy of the
1786 ** object and uses it for page cache memory allocations.</dd>
1787 **
1788 ** <dt>SQLITE_CONFIG_GETPCACHE</dt>
1789 ** <dd> ^(This option takes a single argument which is a pointer to an
1790 ** [sqlite3_pcache_methods] object.  SQLite copies of the current
1791 ** page cache implementation into that object.)^ </dd>
1792 **
1793 ** </dl>
1794 */
1795 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1796 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1797 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1798 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1799 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1800 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1801 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
1802 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
1803 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
1804 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
1805 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
1806 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
1807 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
1808 #define SQLITE_CONFIG_PCACHE       14  /* sqlite3_pcache_methods* */
1809 #define SQLITE_CONFIG_GETPCACHE    15  /* sqlite3_pcache_methods* */
1810 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
1811
1812 /*
1813 ** CAPI3REF: Configuration Options
1814 ** EXPERIMENTAL
1815 **
1816 ** These constants are the available integer configuration options that
1817 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
1818 **
1819 ** New configuration options may be added in future releases of SQLite.
1820 ** Existing configuration options might be discontinued.  Applications
1821 ** should check the return code from [sqlite3_db_config()] to make sure that
1822 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
1823 ** non-zero [error code] if a discontinued or unsupported configuration option
1824 ** is invoked.
1825 **
1826 ** <dl>
1827 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
1828 ** <dd> ^This option takes three additional arguments that determine the 
1829 ** [lookaside memory allocator] configuration for the [database connection].
1830 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
1831 ** pointer to an memory buffer to use for lookaside memory.
1832 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
1833 ** may be NULL in which case SQLite will allocate the
1834 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
1835 ** size of each lookaside buffer slot.  ^The third argument is the number of
1836 ** slots.  The size of the buffer in the first argument must be greater than
1837 ** or equal to the product of the second and third arguments.  The buffer
1838 ** must be aligned to an 8-byte boundary.  ^If the second argument to
1839 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
1840 ** rounded down to the next smaller
1841 ** multiple of 8.  See also: [SQLITE_CONFIG_LOOKASIDE]</dd>
1842 **
1843 ** </dl>
1844 */
1845 #define SQLITE_DBCONFIG_LOOKASIDE    1001  /* void* int int */
1846
1847
1848 /*
1849 ** CAPI3REF: Enable Or Disable Extended Result Codes
1850 **
1851 ** ^The sqlite3_extended_result_codes() routine enables or disables the
1852 ** [extended result codes] feature of SQLite. ^The extended result
1853 ** codes are disabled by default for historical compatibility.
1854 */
1855 SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
1856
1857 /*
1858 ** CAPI3REF: Last Insert Rowid
1859 **
1860 ** ^Each entry in an SQLite table has a unique 64-bit signed
1861 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
1862 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
1863 ** names are not also used by explicitly declared columns. ^If
1864 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
1865 ** is another alias for the rowid.
1866 **
1867 ** ^This routine returns the [rowid] of the most recent
1868 ** successful [INSERT] into the database from the [database connection]
1869 ** in the first argument.  ^If no successful [INSERT]s
1870 ** have ever occurred on that database connection, zero is returned.
1871 **
1872 ** ^(If an [INSERT] occurs within a trigger, then the [rowid] of the inserted
1873 ** row is returned by this routine as long as the trigger is running.
1874 ** But once the trigger terminates, the value returned by this routine
1875 ** reverts to the last value inserted before the trigger fired.)^
1876 **
1877 ** ^An [INSERT] that fails due to a constraint violation is not a
1878 ** successful [INSERT] and does not change the value returned by this
1879 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
1880 ** and INSERT OR ABORT make no changes to the return value of this
1881 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
1882 ** encounters a constraint violation, it does not fail.  The
1883 ** INSERT continues to completion after deleting rows that caused
1884 ** the constraint problem so INSERT OR REPLACE will always change
1885 ** the return value of this interface.)^
1886 **
1887 ** ^For the purposes of this routine, an [INSERT] is considered to
1888 ** be successful even if it is subsequently rolled back.
1889 **
1890 ** This function is accessible to SQL statements via the
1891 ** [last_insert_rowid() SQL function].
1892 **
1893 ** If a separate thread performs a new [INSERT] on the same
1894 ** database connection while the [sqlite3_last_insert_rowid()]
1895 ** function is running and thus changes the last insert [rowid],
1896 ** then the value returned by [sqlite3_last_insert_rowid()] is
1897 ** unpredictable and might not equal either the old or the new
1898 ** last insert [rowid].
1899 */
1900 SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
1901
1902 /*
1903 ** CAPI3REF: Count The Number Of Rows Modified
1904 **
1905 ** ^This function returns the number of database rows that were changed
1906 ** or inserted or deleted by the most recently completed SQL statement
1907 ** on the [database connection] specified by the first parameter.
1908 ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
1909 ** or [DELETE] statement are counted.  Auxiliary changes caused by
1910 ** triggers or [foreign key actions] are not counted.)^ Use the
1911 ** [sqlite3_total_changes()] function to find the total number of changes
1912 ** including changes caused by triggers and foreign key actions.
1913 **
1914 ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
1915 ** are not counted.  Only real table changes are counted.
1916 **
1917 ** ^(A "row change" is a change to a single row of a single table
1918 ** caused by an INSERT, DELETE, or UPDATE statement.  Rows that
1919 ** are changed as side effects of [REPLACE] constraint resolution,
1920 ** rollback, ABORT processing, [DROP TABLE], or by any other
1921 ** mechanisms do not count as direct row changes.)^
1922 **
1923 ** A "trigger context" is a scope of execution that begins and
1924 ** ends with the script of a [CREATE TRIGGER | trigger]. 
1925 ** Most SQL statements are
1926 ** evaluated outside of any trigger.  This is the "top level"
1927 ** trigger context.  If a trigger fires from the top level, a
1928 ** new trigger context is entered for the duration of that one
1929 ** trigger.  Subtriggers create subcontexts for their duration.
1930 **
1931 ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
1932 ** not create a new trigger context.
1933 **
1934 ** ^This function returns the number of direct row changes in the
1935 ** most recent INSERT, UPDATE, or DELETE statement within the same
1936 ** trigger context.
1937 **
1938 ** ^Thus, when called from the top level, this function returns the
1939 ** number of changes in the most recent INSERT, UPDATE, or DELETE
1940 ** that also occurred at the top level.  ^(Within the body of a trigger,
1941 ** the sqlite3_changes() interface can be called to find the number of
1942 ** changes in the most recently completed INSERT, UPDATE, or DELETE
1943 ** statement within the body of the same trigger.
1944 ** However, the number returned does not include changes
1945 ** caused by subtriggers since those have their own context.)^
1946 **
1947 ** See also the [sqlite3_total_changes()] interface, the
1948 ** [count_changes pragma], and the [changes() SQL function].
1949 **
1950 ** If a separate thread makes changes on the same database connection
1951 ** while [sqlite3_changes()] is running then the value returned
1952 ** is unpredictable and not meaningful.
1953 */
1954 SQLITE_API int sqlite3_changes(sqlite3*);
1955
1956 /*
1957 ** CAPI3REF: Total Number Of Rows Modified
1958 **
1959 ** ^This function returns the number of row changes caused by [INSERT],
1960 ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
1961 ** ^(The count returned by sqlite3_total_changes() includes all changes
1962 ** from all [CREATE TRIGGER | trigger] contexts and changes made by
1963 ** [foreign key actions]. However,
1964 ** the count does not include changes used to implement [REPLACE] constraints,
1965 ** do rollbacks or ABORT processing, or [DROP TABLE] processing.  The
1966 ** count does not include rows of views that fire an [INSTEAD OF trigger],
1967 ** though if the INSTEAD OF trigger makes changes of its own, those changes 
1968 ** are counted.)^
1969 ** ^The sqlite3_total_changes() function counts the changes as soon as
1970 ** the statement that makes them is completed (when the statement handle
1971 ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
1972 **
1973 ** See also the [sqlite3_changes()] interface, the
1974 ** [count_changes pragma], and the [total_changes() SQL function].
1975 **
1976 ** If a separate thread makes changes on the same database connection
1977 ** while [sqlite3_total_changes()] is running then the value
1978 ** returned is unpredictable and not meaningful.
1979 */
1980 SQLITE_API int sqlite3_total_changes(sqlite3*);
1981
1982 /*
1983 ** CAPI3REF: Interrupt A Long-Running Query
1984 **
1985 ** ^This function causes any pending database operation to abort and
1986 ** return at its earliest opportunity. This routine is typically
1987 ** called in response to a user action such as pressing "Cancel"
1988 ** or Ctrl-C where the user wants a long query operation to halt
1989 ** immediately.
1990 **
1991 ** ^It is safe to call this routine from a thread different from the
1992 ** thread that is currently running the database operation.  But it
1993 ** is not safe to call this routine with a [database connection] that
1994 ** is closed or might close before sqlite3_interrupt() returns.
1995 **
1996 ** ^If an SQL operation is very nearly finished at the time when
1997 ** sqlite3_interrupt() is called, then it might not have an opportunity
1998 ** to be interrupted and might continue to completion.
1999 **
2000 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2001 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2002 ** that is inside an explicit transaction, then the entire transaction
2003 ** will be rolled back automatically.
2004 **
2005 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2006 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
2007 ** that are started after the sqlite3_interrupt() call and before the 
2008 ** running statements reaches zero are interrupted as if they had been
2009 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2010 ** that are started after the running statement count reaches zero are
2011 ** not effected by the sqlite3_interrupt().
2012 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2013 ** SQL statements is a no-op and has no effect on SQL statements
2014 ** that are started after the sqlite3_interrupt() call returns.
2015 **
2016 ** If the database connection closes while [sqlite3_interrupt()]
2017 ** is running then bad things will likely happen.
2018 */
2019 SQLITE_API void sqlite3_interrupt(sqlite3*);
2020
2021 /*
2022 ** CAPI3REF: Determine If An SQL Statement Is Complete
2023 **
2024 ** These routines are useful during command-line input to determine if the
2025 ** currently entered text seems to form a complete SQL statement or
2026 ** if additional input is needed before sending the text into
2027 ** SQLite for parsing.  ^These routines return 1 if the input string
2028 ** appears to be a complete SQL statement.  ^A statement is judged to be
2029 ** complete if it ends with a semicolon token and is not a prefix of a
2030 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2031 ** string literals or quoted identifier names or comments are not
2032 ** independent tokens (they are part of the token in which they are
2033 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
2034 ** and comments that follow the final semicolon are ignored.
2035 **
2036 ** ^These routines return 0 if the statement is incomplete.  ^If a
2037 ** memory allocation fails, then SQLITE_NOMEM is returned.
2038 **
2039 ** ^These routines do not parse the SQL statements thus
2040 ** will not detect syntactically incorrect SQL.
2041 **
2042 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
2043 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2044 ** automatically by sqlite3_complete16().  If that initialization fails,
2045 ** then the return value from sqlite3_complete16() will be non-zero
2046 ** regardless of whether or not the input SQL is complete.)^
2047 **
2048 ** The input to [sqlite3_complete()] must be a zero-terminated
2049 ** UTF-8 string.
2050 **
2051 ** The input to [sqlite3_complete16()] must be a zero-terminated
2052 ** UTF-16 string in native byte order.
2053 */
2054 SQLITE_API int sqlite3_complete(const char *sql);
2055 SQLITE_API int sqlite3_complete16(const void *sql);
2056
2057 /*
2058 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2059 **
2060 ** ^This routine sets a callback function that might be invoked whenever
2061 ** an attempt is made to open a database table that another thread
2062 ** or process has locked.
2063 **
2064 ** ^If the busy callback is NULL, then [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED]
2065 ** is returned immediately upon encountering the lock.  ^If the busy callback
2066 ** is not NULL, then the callback might be invoked with two arguments.
2067 **
2068 ** ^The first argument to the busy handler is a copy of the void* pointer which
2069 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
2070 ** the busy handler callback is the number of times that the busy handler has
2071 ** been invoked for this locking event.  ^If the
2072 ** busy callback returns 0, then no additional attempts are made to
2073 ** access the database and [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED] is returned.
2074 ** ^If the callback returns non-zero, then another attempt
2075 ** is made to open the database for reading and the cycle repeats.
2076 **
2077 ** The presence of a busy handler does not guarantee that it will be invoked
2078 ** when there is lock contention. ^If SQLite determines that invoking the busy
2079 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2080 ** or [SQLITE_IOERR_BLOCKED] instead of invoking the busy handler.
2081 ** Consider a scenario where one process is holding a read lock that
2082 ** it is trying to promote to a reserved lock and
2083 ** a second process is holding a reserved lock that it is trying
2084 ** to promote to an exclusive lock.  The first process cannot proceed
2085 ** because it is blocked by the second and the second process cannot
2086 ** proceed because it is blocked by the first.  If both processes
2087 ** invoke the busy handlers, neither will make any progress.  Therefore,
2088 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2089 ** will induce the first process to release its read lock and allow
2090 ** the second process to proceed.
2091 **
2092 ** ^The default busy callback is NULL.
2093 **
2094 ** ^The [SQLITE_BUSY] error is converted to [SQLITE_IOERR_BLOCKED]
2095 ** when SQLite is in the middle of a large transaction where all the
2096 ** changes will not fit into the in-memory cache.  SQLite will
2097 ** already hold a RESERVED lock on the database file, but it needs
2098 ** to promote this lock to EXCLUSIVE so that it can spill cache
2099 ** pages into the database file without harm to concurrent
2100 ** readers.  ^If it is unable to promote the lock, then the in-memory
2101 ** cache will be left in an inconsistent state and so the error
2102 ** code is promoted from the relatively benign [SQLITE_BUSY] to
2103 ** the more severe [SQLITE_IOERR_BLOCKED].  ^This error code promotion
2104 ** forces an automatic rollback of the changes.  See the
2105 ** <a href="/cvstrac/wiki?p=CorruptionFollowingBusyError">
2106 ** CorruptionFollowingBusyError</a> wiki page for a discussion of why
2107 ** this is important.
2108 **
2109 ** ^(There can only be a single busy handler defined for each
2110 ** [database connection].  Setting a new busy handler clears any
2111 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2112 ** will also set or clear the busy handler.
2113 **
2114 ** The busy callback should not take any actions which modify the
2115 ** database connection that invoked the busy handler.  Any such actions
2116 ** result in undefined behavior.
2117 ** 
2118 ** A busy handler must not close the database connection
2119 ** or [prepared statement] that invoked the busy handler.
2120 */
2121 SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2122
2123 /*
2124 ** CAPI3REF: Set A Busy Timeout
2125 **
2126 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2127 ** for a specified amount of time when a table is locked.  ^The handler
2128 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2129 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2130 ** the handler returns 0 which causes [sqlite3_step()] to return
2131 ** [SQLITE_BUSY] or [SQLITE_IOERR_BLOCKED].
2132 **
2133 ** ^Calling this routine with an argument less than or equal to zero
2134 ** turns off all busy handlers.
2135 **
2136 ** ^(There can only be a single busy handler for a particular
2137 ** [database connection] any any given moment.  If another busy handler
2138 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2139 ** this routine, that other busy handler is cleared.)^
2140 */
2141 SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
2142
2143 /*
2144 ** CAPI3REF: Convenience Routines For Running Queries
2145 **
2146 ** Definition: A <b>result table</b> is memory data structure created by the
2147 ** [sqlite3_get_table()] interface.  A result table records the
2148 ** complete query results from one or more queries.
2149 **
2150 ** The table conceptually has a number of rows and columns.  But
2151 ** these numbers are not part of the result table itself.  These
2152 ** numbers are obtained separately.  Let N be the number of rows
2153 ** and M be the number of columns.
2154 **
2155 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2156 ** There are (N+1)*M elements in the array.  The first M pointers point
2157 ** to zero-terminated strings that  contain the names of the columns.
2158 ** The remaining entries all point to query results.  NULL values result
2159 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2160 ** string representation as returned by [sqlite3_column_text()].
2161 **
2162 ** A result table might consist of one or more memory allocations.
2163 ** It is not safe to pass a result table directly to [sqlite3_free()].
2164 ** A result table should be deallocated using [sqlite3_free_table()].
2165 **
2166 ** As an example of the result table format, suppose a query result
2167 ** is as follows:
2168 **
2169 ** <blockquote><pre>
2170 **        Name        | Age
2171 **        -----------------------
2172 **        Alice       | 43
2173 **        Bob         | 28
2174 **        Cindy       | 21
2175 ** </pre></blockquote>
2176 **
2177 ** There are two column (M==2) and three rows (N==3).  Thus the
2178 ** result table has 8 entries.  Suppose the result table is stored
2179 ** in an array names azResult.  Then azResult holds this content:
2180 **
2181 ** <blockquote><pre>
2182 **        azResult&#91;0] = "Name";
2183 **        azResult&#91;1] = "Age";
2184 **        azResult&#91;2] = "Alice";
2185 **        azResult&#91;3] = "43";
2186 **        azResult&#91;4] = "Bob";
2187 **        azResult&#91;5] = "28";
2188 **        azResult&#91;6] = "Cindy";
2189 **        azResult&#91;7] = "21";
2190 ** </pre></blockquote>
2191 **
2192 ** ^The sqlite3_get_table() function evaluates one or more
2193 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2194 ** string of its 2nd parameter and returns a result table to the
2195 ** pointer given in its 3rd parameter.
2196 **
2197 ** After the application has finished with the result from sqlite3_get_table(),
2198 ** it should pass the result table pointer to sqlite3_free_table() in order to
2199 ** release the memory that was malloced.  Because of the way the
2200 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2201 ** function must not try to call [sqlite3_free()] directly.  Only
2202 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2203 **
2204 ** ^(The sqlite3_get_table() interface is implemented as a wrapper around
2205 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2206 ** to any internal data structures of SQLite.  It uses only the public
2207 ** interface defined here.  As a consequence, errors that occur in the
2208 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2209 ** reflected in subsequent calls to [sqlite3_errcode()] or
2210 ** [sqlite3_errmsg()].)^
2211 */
2212 SQLITE_API int sqlite3_get_table(
2213   sqlite3 *db,          /* An open database */
2214   const char *zSql,     /* SQL to be evaluated */
2215   char ***pazResult,    /* Results of the query */
2216   int *pnRow,           /* Number of result rows written here */
2217   int *pnColumn,        /* Number of result columns written here */
2218   char **pzErrmsg       /* Error msg written here */
2219 );
2220 SQLITE_API void sqlite3_free_table(char **result);
2221
2222 /*
2223 ** CAPI3REF: Formatted String Printing Functions
2224 **
2225 ** These routines are work-alikes of the "printf()" family of functions
2226 ** from the standard C library.
2227 **
2228 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2229 ** results into memory obtained from [sqlite3_malloc()].
2230 ** The strings returned by these two routines should be
2231 ** released by [sqlite3_free()].  ^Both routines return a
2232 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2233 ** memory to hold the resulting string.
2234 **
2235 ** ^(In sqlite3_snprintf() routine is similar to "snprintf()" from
2236 ** the standard C library.  The result is written into the
2237 ** buffer supplied as the second parameter whose size is given by
2238 ** the first parameter. Note that the order of the
2239 ** first two parameters is reversed from snprintf().)^  This is an
2240 ** historical accident that cannot be fixed without breaking
2241 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2242 ** returns a pointer to its buffer instead of the number of
2243 ** characters actually written into the buffer.)^  We admit that
2244 ** the number of characters written would be a more useful return
2245 ** value but we cannot change the implementation of sqlite3_snprintf()
2246 ** now without breaking compatibility.
2247 **
2248 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2249 ** guarantees that the buffer is always zero-terminated.  ^The first
2250 ** parameter "n" is the total size of the buffer, including space for
2251 ** the zero terminator.  So the longest string that can be completely
2252 ** written will be n-1 characters.
2253 **
2254 ** These routines all implement some additional formatting
2255 ** options that are useful for constructing SQL statements.
2256 ** All of the usual printf() formatting options apply.  In addition, there
2257 ** is are "%q", "%Q", and "%z" options.
2258 **
2259 ** ^(The %q option works like %s in that it substitutes a null-terminated
2260 ** string from the argument list.  But %q also doubles every '\'' character.
2261 ** %q is designed for use inside a string literal.)^  By doubling each '\''
2262 ** character it escapes that character and allows it to be inserted into
2263 ** the string.
2264 **
2265 ** For example, assume the string variable zText contains text as follows:
2266 **
2267 ** <blockquote><pre>
2268 **  char *zText = "It's a happy day!";
2269 ** </pre></blockquote>
2270 **
2271 ** One can use this text in an SQL statement as follows:
2272 **
2273 ** <blockquote><pre>
2274 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2275 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2276 **  sqlite3_free(zSQL);
2277 ** </pre></blockquote>
2278 **
2279 ** Because the %q format string is used, the '\'' character in zText
2280 ** is escaped and the SQL generated is as follows:
2281 **
2282 ** <blockquote><pre>
2283 **  INSERT INTO table1 VALUES('It''s a happy day!')
2284 ** </pre></blockquote>
2285 **
2286 ** This is correct.  Had we used %s instead of %q, the generated SQL
2287 ** would have looked like this:
2288 **
2289 ** <blockquote><pre>
2290 **  INSERT INTO table1 VALUES('It's a happy day!');
2291 ** </pre></blockquote>
2292 **
2293 ** This second example is an SQL syntax error.  As a general rule you should
2294 ** always use %q instead of %s when inserting text into a string literal.
2295 **
2296 ** ^(The %Q option works like %q except it also adds single quotes around
2297 ** the outside of the total string.  Additionally, if the parameter in the
2298 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2299 ** single quotes).)^  So, for example, one could say:
2300 **
2301 ** <blockquote><pre>
2302 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2303 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2304 **  sqlite3_free(zSQL);
2305 ** </pre></blockquote>
2306 **
2307 ** The code above will render a correct SQL statement in the zSQL
2308 ** variable even if the zText variable is a NULL pointer.
2309 **
2310 ** ^(The "%z" formatting option works like "%s" but with the
2311 ** addition that after the string has been read and copied into
2312 ** the result, [sqlite3_free()] is called on the input string.)^
2313 */
2314 SQLITE_API char *sqlite3_mprintf(const char*,...);
2315 SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
2316 SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
2317
2318 /*
2319 ** CAPI3REF: Memory Allocation Subsystem
2320 **
2321 ** The SQLite core uses these three routines for all of its own
2322 ** internal memory allocation needs. "Core" in the previous sentence
2323 ** does not include operating-system specific VFS implementation.  The
2324 ** Windows VFS uses native malloc() and free() for some operations.
2325 **
2326 ** ^The sqlite3_malloc() routine returns a pointer to a block
2327 ** of memory at least N bytes in length, where N is the parameter.
2328 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2329 ** memory, it returns a NULL pointer.  ^If the parameter N to
2330 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2331 ** a NULL pointer.
2332 **
2333 ** ^Calling sqlite3_free() with a pointer previously returned
2334 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2335 ** that it might be reused.  ^The sqlite3_free() routine is
2336 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2337 ** to sqlite3_free() is harmless.  After being freed, memory
2338 ** should neither be read nor written.  Even reading previously freed
2339 ** memory might result in a segmentation fault or other severe error.
2340 ** Memory corruption, a segmentation fault, or other severe error
2341 ** might result if sqlite3_free() is called with a non-NULL pointer that
2342 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2343 **
2344 ** ^(The sqlite3_realloc() interface attempts to resize a
2345 ** prior memory allocation to be at least N bytes, where N is the
2346 ** second parameter.  The memory allocation to be resized is the first
2347 ** parameter.)^ ^ If the first parameter to sqlite3_realloc()
2348 ** is a NULL pointer then its behavior is identical to calling
2349 ** sqlite3_malloc(N) where N is the second parameter to sqlite3_realloc().
2350 ** ^If the second parameter to sqlite3_realloc() is zero or
2351 ** negative then the behavior is exactly the same as calling
2352 ** sqlite3_free(P) where P is the first parameter to sqlite3_realloc().
2353 ** ^sqlite3_realloc() returns a pointer to a memory allocation
2354 ** of at least N bytes in size or NULL if sufficient memory is unavailable.
2355 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2356 ** of the prior allocation are copied into the beginning of buffer returned
2357 ** by sqlite3_realloc() and the prior allocation is freed.
2358 ** ^If sqlite3_realloc() returns NULL, then the prior allocation
2359 ** is not freed.
2360 **
2361 ** ^The memory returned by sqlite3_malloc() and sqlite3_realloc()
2362 ** is always aligned to at least an 8 byte boundary.
2363 **
2364 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2365 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2366 ** implementation of these routines to be omitted.  That capability
2367 ** is no longer provided.  Only built-in memory allocators can be used.
2368 **
2369 ** The Windows OS interface layer calls
2370 ** the system malloc() and free() directly when converting
2371 ** filenames between the UTF-8 encoding used by SQLite
2372 ** and whatever filename encoding is used by the particular Windows
2373 ** installation.  Memory allocation errors are detected, but
2374 ** they are reported back as [SQLITE_CANTOPEN] or
2375 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2376 **
2377 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2378 ** must be either NULL or else pointers obtained from a prior
2379 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2380 ** not yet been released.
2381 **
2382 ** The application must not read or write any part of
2383 ** a block of memory after it has been released using
2384 ** [sqlite3_free()] or [sqlite3_realloc()].
2385 */
2386 SQLITE_API void *sqlite3_malloc(int);
2387 SQLITE_API void *sqlite3_realloc(void*, int);
2388 SQLITE_API void sqlite3_free(void*);
2389
2390 /*
2391 ** CAPI3REF: Memory Allocator Statistics
2392 **
2393 ** SQLite provides these two interfaces for reporting on the status
2394 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2395 ** routines, which form the built-in memory allocation subsystem.
2396 **
2397 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2398 ** of memory currently outstanding (malloced but not freed).
2399 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2400 ** value of [sqlite3_memory_used()] since the high-water mark
2401 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2402 ** [sqlite3_memory_highwater()] include any overhead
2403 ** added by SQLite in its implementation of [sqlite3_malloc()],
2404 ** but not overhead added by the any underlying system library
2405 ** routines that [sqlite3_malloc()] may call.
2406 **
2407 ** ^The memory high-water mark is reset to the current value of
2408 ** [sqlite3_memory_used()] if and only if the parameter to
2409 ** [sqlite3_memory_highwater()] is true.  ^The value returned
2410 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2411 ** prior to the reset.
2412 */
2413 SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
2414 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
2415
2416 /*
2417 ** CAPI3REF: Pseudo-Random Number Generator
2418 **
2419 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2420 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2421 ** already uses the largest possible [ROWID].  The PRNG is also used for
2422 ** the build-in random() and randomblob() SQL functions.  This interface allows
2423 ** applications to access the same PRNG for other purposes.
2424 **
2425 ** ^A call to this routine stores N bytes of randomness into buffer P.
2426 **
2427 ** ^The first time this routine is invoked (either internally or by
2428 ** the application) the PRNG is seeded using randomness obtained
2429 ** from the xRandomness method of the default [sqlite3_vfs] object.
2430 ** ^On all subsequent invocations, the pseudo-randomness is generated
2431 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2432 ** method.
2433 */
2434 SQLITE_API void sqlite3_randomness(int N, void *P);
2435
2436 /*
2437 ** CAPI3REF: Compile-Time Authorization Callbacks
2438 **
2439 ** ^This routine registers a authorizer callback with a particular
2440 ** [database connection], supplied in the first argument.
2441 ** ^The authorizer callback is invoked as SQL statements are being compiled
2442 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2443 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2444 ** points during the compilation process, as logic is being created
2445 ** to perform various actions, the authorizer callback is invoked to
2446 ** see if those actions are allowed.  ^The authorizer callback should
2447 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2448 ** specific action but allow the SQL statement to continue to be
2449 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2450 ** rejected with an error.  ^If the authorizer callback returns
2451 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2452 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2453 ** the authorizer will fail with an error message.
2454 **
2455 ** When the callback returns [SQLITE_OK], that means the operation
2456 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2457 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2458 ** authorizer will fail with an error message explaining that
2459 ** access is denied. 
2460 **
2461 ** ^The first parameter to the authorizer callback is a copy of the third
2462 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2463 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2464 ** the particular action to be authorized. ^The third through sixth parameters
2465 ** to the callback are zero-terminated strings that contain additional
2466 ** details about the action to be authorized.
2467 **
2468 ** ^If the action code is [SQLITE_READ]
2469 ** and the callback returns [SQLITE_IGNORE] then the
2470 ** [prepared statement] statement is constructed to substitute
2471 ** a NULL value in place of the table column that would have
2472 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2473 ** return can be used to deny an untrusted user access to individual
2474 ** columns of a table.
2475 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2476 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2477 ** [truncate optimization] is disabled and all rows are deleted individually.
2478 **
2479 ** An authorizer is used when [sqlite3_prepare | preparing]
2480 ** SQL statements from an untrusted source, to ensure that the SQL statements
2481 ** do not try to access data they are not allowed to see, or that they do not
2482 ** try to execute malicious statements that damage the database.  For
2483 ** example, an application may allow a user to enter arbitrary
2484 ** SQL queries for evaluation by a database.  But the application does
2485 ** not want the user to be able to make arbitrary changes to the
2486 ** database.  An authorizer could then be put in place while the
2487 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2488 ** disallows everything except [SELECT] statements.
2489 **
2490 ** Applications that need to process SQL from untrusted sources
2491 ** might also consider lowering resource limits using [sqlite3_limit()]
2492 ** and limiting database size using the [max_page_count] [PRAGMA]
2493 ** in addition to using an authorizer.
2494 **
2495 ** ^(Only a single authorizer can be in place on a database connection
2496 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2497 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2498 ** The authorizer is disabled by default.
2499 **
2500 ** The authorizer callback must not do anything that will modify
2501 ** the database connection that invoked the authorizer callback.
2502 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2503 ** database connections for the meaning of "modify" in this paragraph.
2504 **
2505 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2506 ** statement might be re-prepared during [sqlite3_step()] due to a 
2507 ** schema change.  Hence, the application should ensure that the
2508 ** correct authorizer callback remains in place during the [sqlite3_step()].
2509 **
2510 ** ^Note that the authorizer callback is invoked only during
2511 ** [sqlite3_prepare()] or its variants.  Authorization is not
2512 ** performed during statement evaluation in [sqlite3_step()], unless
2513 ** as stated in the previous paragraph, sqlite3_step() invokes
2514 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2515 */
2516 SQLITE_API int sqlite3_set_authorizer(
2517   sqlite3*,
2518   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2519   void *pUserData
2520 );
2521
2522 /*
2523 ** CAPI3REF: Authorizer Return Codes
2524 **
2525 ** The [sqlite3_set_authorizer | authorizer callback function] must
2526 ** return either [SQLITE_OK] or one of these two constants in order
2527 ** to signal SQLite whether or not the action is permitted.  See the
2528 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2529 ** information.
2530 */
2531 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2532 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2533
2534 /*
2535 ** CAPI3REF: Authorizer Action Codes
2536 **
2537 ** The [sqlite3_set_authorizer()] interface registers a callback function
2538 ** that is invoked to authorize certain SQL statement actions.  The
2539 ** second parameter to the callback is an integer code that specifies
2540 ** what action is being authorized.  These are the integer action codes that
2541 ** the authorizer callback may be passed.
2542 **
2543 ** These action code values signify what kind of operation is to be
2544 ** authorized.  The 3rd and 4th parameters to the authorization
2545 ** callback function will be parameters or NULL depending on which of these
2546 ** codes is used as the second parameter.  ^(The 5th parameter to the
2547 ** authorizer callback is the name of the database ("main", "temp",
2548 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2549 ** is the name of the inner-most trigger or view that is responsible for
2550 ** the access attempt or NULL if this access attempt is directly from
2551 ** top-level SQL code.
2552 */
2553 /******************************************* 3rd ************ 4th ***********/
2554 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2555 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2556 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2557 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2558 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2559 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2560 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2561 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2562 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2563 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2564 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2565 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2566 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2567 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2568 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2569 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2570 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2571 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2572 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2573 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2574 #define SQLITE_SELECT               21   /* NULL            NULL            */
2575 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2576 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2577 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2578 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2579 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2580 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2581 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2582 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2583 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2584 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2585 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2586 #define SQLITE_COPY                  0   /* No longer used */
2587
2588 /*
2589 ** CAPI3REF: Tracing And Profiling Functions
2590 ** EXPERIMENTAL
2591 **
2592 ** These routines register callback functions that can be used for
2593 ** tracing and profiling the execution of SQL statements.
2594 **
2595 ** ^The callback function registered by sqlite3_trace() is invoked at
2596 ** various times when an SQL statement is being run by [sqlite3_step()].
2597 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2598 ** SQL statement text as the statement first begins executing.
2599 ** ^(Additional sqlite3_trace() callbacks might occur
2600 ** as each triggered subprogram is entered.  The callbacks for triggers
2601 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2602 **
2603 ** ^The callback function registered by sqlite3_profile() is invoked
2604 ** as each SQL statement finishes.  ^The profile callback contains
2605 ** the original statement text and an estimate of wall-clock time
2606 ** of how long that statement took to run.
2607 */
2608 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2609 SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
2610    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2611
2612 /*
2613 ** CAPI3REF: Query Progress Callbacks
2614 **
2615 ** ^This routine configures a callback function - the
2616 ** progress callback - that is invoked periodically during long
2617 ** running calls to [sqlite3_exec()], [sqlite3_step()] and
2618 ** [sqlite3_get_table()].  An example use for this
2619 ** interface is to keep a GUI updated during a large query.
2620 **
2621 ** ^If the progress callback returns non-zero, the operation is
2622 ** interrupted.  This feature can be used to implement a
2623 ** "Cancel" button on a GUI progress dialog box.
2624 **
2625 ** The progress handler must not do anything that will modify
2626 ** the database connection that invoked the progress handler.
2627 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2628 ** database connections for the meaning of "modify" in this paragraph.
2629 **
2630 */
2631 SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2632
2633 /*
2634 ** CAPI3REF: Opening A New Database Connection
2635 **
2636 ** ^These routines open an SQLite database file whose name is given by the
2637 ** filename argument. ^The filename argument is interpreted as UTF-8 for
2638 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2639 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
2640 ** returned in *ppDb, even if an error occurs.  The only exception is that
2641 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2642 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2643 ** object.)^ ^(If the database is opened (and/or created) successfully, then
2644 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2645 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2646 ** an English language description of the error following a failure of any
2647 ** of the sqlite3_open() routines.
2648 **
2649 ** ^The default encoding for the database will be UTF-8 if
2650 ** sqlite3_open() or sqlite3_open_v2() is called and
2651 ** UTF-16 in the native byte order if sqlite3_open16() is used.
2652 **
2653 ** Whether or not an error occurs when it is opened, resources
2654 ** associated with the [database connection] handle should be released by
2655 ** passing it to [sqlite3_close()] when it is no longer required.
2656 **
2657 ** The sqlite3_open_v2() interface works like sqlite3_open()
2658 ** except that it accepts two additional parameters for additional control
2659 ** over the new database connection.  ^(The flags parameter to
2660 ** sqlite3_open_v2() can take one of
2661 ** the following three values, optionally combined with the 
2662 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2663 ** and/or [SQLITE_OPEN_PRIVATECACHE] flags:)^
2664 **
2665 ** <dl>
2666 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2667 ** <dd>The database is opened in read-only mode.  If the database does not
2668 ** already exist, an error is returned.</dd>)^
2669 **
2670 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2671 ** <dd>The database is opened for reading and writing if possible, or reading
2672 ** only if the file is write protected by the operating system.  In either
2673 ** case the database must already exist, otherwise an error is returned.</dd>)^
2674 **
2675 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2676 ** <dd>The database is opened for reading and writing, and is creates it if
2677 ** it does not already exist. This is the behavior that is always used for
2678 ** sqlite3_open() and sqlite3_open16().</dd>)^
2679 ** </dl>
2680 **
2681 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2682 ** combinations shown above or one of the combinations shown above combined
2683 ** with the [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX],
2684 ** [SQLITE_OPEN_SHAREDCACHE] and/or [SQLITE_OPEN_SHAREDCACHE] flags,
2685 ** then the behavior is undefined.
2686 **
2687 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2688 ** opens in the multi-thread [threading mode] as long as the single-thread
2689 ** mode has not been set at compile-time or start-time.  ^If the
2690 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2691 ** in the serialized [threading mode] unless single-thread was
2692 ** previously selected at compile-time or start-time.
2693 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2694 ** eligible to use [shared cache mode], regardless of whether or not shared
2695 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
2696 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2697 ** participate in [shared cache mode] even if it is enabled.
2698 **
2699 ** ^If the filename is ":memory:", then a private, temporary in-memory database
2700 ** is created for the connection.  ^This in-memory database will vanish when
2701 ** the database connection is closed.  Future versions of SQLite might
2702 ** make use of additional special filenames that begin with the ":" character.
2703 ** It is recommended that when a database filename actually does begin with
2704 ** a ":" character you should prefix the filename with a pathname such as
2705 ** "./" to avoid ambiguity.
2706 **
2707 ** ^If the filename is an empty string, then a private, temporary
2708 ** on-disk database will be created.  ^This private database will be
2709 ** automatically deleted as soon as the database connection is closed.
2710 **
2711 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
2712 ** [sqlite3_vfs] object that defines the operating system interface that
2713 ** the new database connection should use.  ^If the fourth parameter is
2714 ** a NULL pointer then the default [sqlite3_vfs] object is used.
2715 **
2716 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
2717 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
2718 ** codepage is currently defined.  Filenames containing international
2719 ** characters must be converted to UTF-8 prior to passing them into
2720 ** sqlite3_open() or sqlite3_open_v2().
2721 */
2722 SQLITE_API int sqlite3_open(
2723   const char *filename,   /* Database filename (UTF-8) */
2724   sqlite3 **ppDb          /* OUT: SQLite db handle */
2725 );
2726 SQLITE_API int sqlite3_open16(
2727   const void *filename,   /* Database filename (UTF-16) */
2728   sqlite3 **ppDb          /* OUT: SQLite db handle */
2729 );
2730 SQLITE_API int sqlite3_open_v2(
2731   const char *filename,   /* Database filename (UTF-8) */
2732   sqlite3 **ppDb,         /* OUT: SQLite db handle */
2733   int flags,              /* Flags */
2734   const char *zVfs        /* Name of VFS module to use */
2735 );
2736
2737 /*
2738 ** CAPI3REF: Error Codes And Messages
2739 **
2740 ** ^The sqlite3_errcode() interface returns the numeric [result code] or
2741 ** [extended result code] for the most recent failed sqlite3_* API call
2742 ** associated with a [database connection]. If a prior API call failed
2743 ** but the most recent API call succeeded, the return value from
2744 ** sqlite3_errcode() is undefined.  ^The sqlite3_extended_errcode()
2745 ** interface is the same except that it always returns the 
2746 ** [extended result code] even when extended result codes are
2747 ** disabled.
2748 **
2749 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
2750 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
2751 ** ^(Memory to hold the error message string is managed internally.
2752 ** The application does not need to worry about freeing the result.
2753 ** However, the error string might be overwritten or deallocated by
2754 ** subsequent calls to other SQLite interface functions.)^
2755 **
2756 ** When the serialized [threading mode] is in use, it might be the
2757 ** case that a second error occurs on a separate thread in between
2758 ** the time of the first error and the call to these interfaces.
2759 ** When that happens, the second error will be reported since these
2760 ** interfaces always report the most recent result.  To avoid
2761 ** this, each thread can obtain exclusive use of the [database connection] D
2762 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
2763 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
2764 ** all calls to the interfaces listed here are completed.
2765 **
2766 ** If an interface fails with SQLITE_MISUSE, that means the interface
2767 ** was invoked incorrectly by the application.  In that case, the
2768 ** error code and message may or may not be set.
2769 */
2770 SQLITE_API int sqlite3_errcode(sqlite3 *db);
2771 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
2772 SQLITE_API const char *sqlite3_errmsg(sqlite3*);
2773 SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
2774
2775 /*
2776 ** CAPI3REF: SQL Statement Object
2777 ** KEYWORDS: {prepared statement} {prepared statements}
2778 **
2779 ** An instance of this object represents a single SQL statement.
2780 ** This object is variously known as a "prepared statement" or a
2781 ** "compiled SQL statement" or simply as a "statement".
2782 **
2783 ** The life of a statement object goes something like this:
2784 **
2785 ** <ol>
2786 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
2787 **      function.
2788 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
2789 **      interfaces.
2790 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
2791 ** <li> Reset the statement using [sqlite3_reset()] then go back
2792 **      to step 2.  Do this zero or more times.
2793 ** <li> Destroy the object using [sqlite3_finalize()].
2794 ** </ol>
2795 **
2796 ** Refer to documentation on individual methods above for additional
2797 ** information.
2798 */
2799 typedef struct sqlite3_stmt sqlite3_stmt;
2800
2801 /*
2802 ** CAPI3REF: Run-time Limits
2803 **
2804 ** ^(This interface allows the size of various constructs to be limited
2805 ** on a connection by connection basis.  The first parameter is the
2806 ** [database connection] whose limit is to be set or queried.  The
2807 ** second parameter is one of the [limit categories] that define a
2808 ** class of constructs to be size limited.  The third parameter is the
2809 ** new limit for that construct.  The function returns the old limit.)^
2810 **
2811 ** ^If the new limit is a negative number, the limit is unchanged.
2812 ** ^(For the limit category of SQLITE_LIMIT_XYZ there is a 
2813 ** [limits | hard upper bound]
2814 ** set by a compile-time C preprocessor macro named 
2815 ** [limits | SQLITE_MAX_XYZ].
2816 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
2817 ** ^Attempts to increase a limit above its hard upper bound are
2818 ** silently truncated to the hard upper bound.
2819 **
2820 ** Run-time limits are intended for use in applications that manage
2821 ** both their own internal database and also databases that are controlled
2822 ** by untrusted external sources.  An example application might be a
2823 ** web browser that has its own databases for storing history and
2824 ** separate databases controlled by JavaScript applications downloaded
2825 ** off the Internet.  The internal databases can be given the
2826 ** large, default limits.  Databases managed by external sources can
2827 ** be given much smaller limits designed to prevent a denial of service
2828 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
2829 ** interface to further control untrusted SQL.  The size of the database
2830 ** created by an untrusted script can be contained using the
2831 ** [max_page_count] [PRAGMA].
2832 **
2833 ** New run-time limit categories may be added in future releases.
2834 */
2835 SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
2836
2837 /*
2838 ** CAPI3REF: Run-Time Limit Categories
2839 ** KEYWORDS: {limit category} {*limit categories}
2840 **
2841 ** These constants define various performance limits
2842 ** that can be lowered at run-time using [sqlite3_limit()].
2843 ** The synopsis of the meanings of the various limits is shown below.
2844 ** Additional information is available at [limits | Limits in SQLite].
2845 **
2846 ** <dl>
2847 ** ^(<dt>SQLITE_LIMIT_LENGTH</dt>
2848 ** <dd>The maximum size of any string or BLOB or table row.<dd>)^
2849 **
2850 ** ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
2851 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
2852 **
2853 ** ^(<dt>SQLITE_LIMIT_COLUMN</dt>
2854 ** <dd>The maximum number of columns in a table definition or in the
2855 ** result set of a [SELECT] or the maximum number of columns in an index
2856 ** or in an ORDER BY or GROUP BY clause.</dd>)^
2857 **
2858 ** ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
2859 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
2860 **
2861 ** ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
2862 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
2863 **
2864 ** ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
2865 ** <dd>The maximum number of instructions in a virtual machine program
2866 ** used to implement an SQL statement.</dd>)^
2867 **
2868 ** ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
2869 ** <dd>The maximum number of arguments on a function.</dd>)^
2870 **
2871 ** ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
2872 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
2873 **
2874 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
2875 ** <dd>The maximum length of the pattern argument to the [LIKE] or
2876 ** [GLOB] operators.</dd>)^
2877 **
2878 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
2879 ** <dd>The maximum number of variables in an SQL statement that can
2880 ** be bound.</dd>)^
2881 **
2882 ** ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
2883 ** <dd>The maximum depth of recursion for triggers.</dd>)^
2884 ** </dl>
2885 */
2886 #define SQLITE_LIMIT_LENGTH                    0
2887 #define SQLITE_LIMIT_SQL_LENGTH                1
2888 #define SQLITE_LIMIT_COLUMN                    2
2889 #define SQLITE_LIMIT_EXPR_DEPTH                3
2890 #define SQLITE_LIMIT_COMPOUND_SELECT           4
2891 #define SQLITE_LIMIT_VDBE_OP                   5
2892 #define SQLITE_LIMIT_FUNCTION_ARG              6
2893 #define SQLITE_LIMIT_ATTACHED                  7
2894 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
2895 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
2896 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
2897
2898 /*
2899 ** CAPI3REF: Compiling An SQL Statement
2900 ** KEYWORDS: {SQL statement compiler}
2901 **
2902 ** To execute an SQL query, it must first be compiled into a byte-code
2903 ** program using one of these routines.
2904 **
2905 ** The first argument, "db", is a [database connection] obtained from a
2906 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
2907 ** [sqlite3_open16()].  The database connection must not have been closed.
2908 **
2909 ** The second argument, "zSql", is the statement to be compiled, encoded
2910 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
2911 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
2912 ** use UTF-16.
2913 **
2914 ** ^If the nByte argument is less than zero, then zSql is read up to the
2915 ** first zero terminator. ^If nByte is non-negative, then it is the maximum
2916 ** number of  bytes read from zSql.  ^When nByte is non-negative, the
2917 ** zSql string ends at either the first '\000' or '\u0000' character or
2918 ** the nByte-th byte, whichever comes first. If the caller knows
2919 ** that the supplied string is nul-terminated, then there is a small
2920 ** performance advantage to be gained by passing an nByte parameter that
2921 ** is equal to the number of bytes in the input string <i>including</i>
2922 ** the nul-terminator bytes.
2923 **
2924 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
2925 ** past the end of the first SQL statement in zSql.  These routines only
2926 ** compile the first statement in zSql, so *pzTail is left pointing to
2927 ** what remains uncompiled.
2928 **
2929 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
2930 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
2931 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
2932 ** string or a comment) then *ppStmt is set to NULL.
2933 ** The calling procedure is responsible for deleting the compiled
2934 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
2935 ** ppStmt may not be NULL.
2936 **
2937 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
2938 ** otherwise an [error code] is returned.
2939 **
2940 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
2941 ** recommended for all new programs. The two older interfaces are retained
2942 ** for backwards compatibility, but their use is discouraged.
2943 ** ^In the "v2" interfaces, the prepared statement
2944 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
2945 ** original SQL text. This causes the [sqlite3_step()] interface to
2946 ** behave differently in three ways:
2947 **
2948 ** <ol>
2949 ** <li>
2950 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
2951 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
2952 ** statement and try to run it again.  ^If the schema has changed in
2953 ** a way that makes the statement no longer valid, [sqlite3_step()] will still
2954 ** return [SQLITE_SCHEMA].  But unlike the legacy behavior, [SQLITE_SCHEMA] is
2955 ** now a fatal error.  Calling [sqlite3_prepare_v2()] again will not make the
2956 ** error go away.  Note: use [sqlite3_errmsg()] to find the text
2957 ** of the parsing error that results in an [SQLITE_SCHEMA] return.
2958 ** </li>
2959 **
2960 ** <li>
2961 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
2962 ** [error codes] or [extended error codes].  ^The legacy behavior was that
2963 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
2964 ** and the application would have to make a second call to [sqlite3_reset()]
2965 ** in order to find the underlying cause of the problem. With the "v2" prepare
2966 ** interfaces, the underlying reason for the error is returned immediately.
2967 ** </li>
2968 **
2969 ** <li>
2970 ** ^If the value of a [parameter | host parameter] in the WHERE clause might
2971 ** change the query plan for a statement, then the statement may be
2972 ** automatically recompiled (as if there had been a schema change) on the first 
2973 ** [sqlite3_step()] call following any change to the 
2974 ** [sqlite3_bind_text | bindings] of the [parameter]. 
2975 ** </li>
2976 ** </ol>
2977 */
2978 SQLITE_API int sqlite3_prepare(
2979   sqlite3 *db,            /* Database handle */
2980   const char *zSql,       /* SQL statement, UTF-8 encoded */
2981   int nByte,              /* Maximum length of zSql in bytes. */
2982   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2983   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
2984 );
2985 SQLITE_API int sqlite3_prepare_v2(
2986   sqlite3 *db,            /* Database handle */
2987   const char *zSql,       /* SQL statement, UTF-8 encoded */
2988   int nByte,              /* Maximum length of zSql in bytes. */
2989   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2990   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
2991 );
2992 SQLITE_API int sqlite3_prepare16(
2993   sqlite3 *db,            /* Database handle */
2994   const void *zSql,       /* SQL statement, UTF-16 encoded */
2995   int nByte,              /* Maximum length of zSql in bytes. */
2996   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
2997   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
2998 );
2999 SQLITE_API int sqlite3_prepare16_v2(
3000   sqlite3 *db,            /* Database handle */
3001   const void *zSql,       /* SQL statement, UTF-16 encoded */
3002   int nByte,              /* Maximum length of zSql in bytes. */
3003   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3004   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3005 );
3006
3007 /*
3008 ** CAPI3REF: Retrieving Statement SQL
3009 **
3010 ** ^This interface can be used to retrieve a saved copy of the original
3011 ** SQL text used to create a [prepared statement] if that statement was
3012 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3013 */
3014 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
3015
3016 /*
3017 ** CAPI3REF: Dynamically Typed Value Object
3018 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3019 **
3020 ** SQLite uses the sqlite3_value object to represent all values
3021 ** that can be stored in a database table. SQLite uses dynamic typing
3022 ** for the values it stores.  ^Values stored in sqlite3_value objects
3023 ** can be integers, floating point values, strings, BLOBs, or NULL.
3024 **
3025 ** An sqlite3_value object may be either "protected" or "unprotected".
3026 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3027 ** will accept either a protected or an unprotected sqlite3_value.
3028 ** Every interface that accepts sqlite3_value arguments specifies
3029 ** whether or not it requires a protected sqlite3_value.
3030 **
3031 ** The terms "protected" and "unprotected" refer to whether or not
3032 ** a mutex is held.  A internal mutex is held for a protected
3033 ** sqlite3_value object but no mutex is held for an unprotected
3034 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3035 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3036 ** or if SQLite is run in one of reduced mutex modes 
3037 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3038 ** then there is no distinction between protected and unprotected
3039 ** sqlite3_value objects and they can be used interchangeably.  However,
3040 ** for maximum code portability it is recommended that applications
3041 ** still make the distinction between between protected and unprotected
3042 ** sqlite3_value objects even when not strictly required.
3043 **
3044 ** ^The sqlite3_value objects that are passed as parameters into the
3045 ** implementation of [application-defined SQL functions] are protected.
3046 ** ^The sqlite3_value object returned by
3047 ** [sqlite3_column_value()] is unprotected.
3048 ** Unprotected sqlite3_value objects may only be used with
3049 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3050 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3051 ** interfaces require protected sqlite3_value objects.
3052 */
3053 typedef struct Mem sqlite3_value;
3054
3055 /*
3056 ** CAPI3REF: SQL Function Context Object
3057 **
3058 ** The context in which an SQL function executes is stored in an
3059 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
3060 ** is always first parameter to [application-defined SQL functions].
3061 ** The application-defined SQL function implementation will pass this
3062 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3063 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3064 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3065 ** and/or [sqlite3_set_auxdata()].
3066 */
3067 typedef struct sqlite3_context sqlite3_context;
3068
3069 /*
3070 ** CAPI3REF: Binding Values To Prepared Statements
3071 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3072 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3073 **
3074 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3075 ** literals may be replaced by a [parameter] that matches one of following
3076 ** templates:
3077 **
3078 ** <ul>
3079 ** <li>  ?
3080 ** <li>  ?NNN
3081 ** <li>  :VVV
3082 ** <li>  @VVV
3083 ** <li>  $VVV
3084 ** </ul>
3085 **
3086 ** In the templates above, NNN represents an integer literal,
3087 ** and VVV represents an alphanumeric identifer.)^  ^The values of these
3088 ** parameters (also called "host parameter names" or "SQL parameters")
3089 ** can be set using the sqlite3_bind_*() routines defined here.
3090 **
3091 ** ^The first argument to the sqlite3_bind_*() routines is always
3092 ** a pointer to the [sqlite3_stmt] object returned from
3093 ** [sqlite3_prepare_v2()] or its variants.
3094 **
3095 ** ^The second argument is the index of the SQL parameter to be set.
3096 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3097 ** SQL parameter is used more than once, second and subsequent
3098 ** occurrences have the same index as the first occurrence.
3099 ** ^The index for named parameters can be looked up using the
3100 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3101 ** for "?NNN" parameters is the value of NNN.
3102 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3103 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3104 **
3105 ** ^The third argument is the value to bind to the parameter.
3106 **
3107 ** ^(In those routines that have a fourth argument, its value is the
3108 ** number of bytes in the parameter.  To be clear: the value is the
3109 ** number of <u>bytes</u> in the value, not the number of characters.)^
3110 ** ^If the fourth parameter is negative, the length of the string is
3111 ** the number of bytes up to the first zero terminator.
3112 **
3113 ** ^The fifth argument to sqlite3_bind_blob(), sqlite3_bind_text(), and
3114 ** sqlite3_bind_text16() is a destructor used to dispose of the BLOB or
3115 ** string after SQLite has finished with it. ^If the fifth argument is
3116 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3117 ** information is in static, unmanaged space and does not need to be freed.
3118 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3119 ** SQLite makes its own private copy of the data immediately, before
3120 ** the sqlite3_bind_*() routine returns.
3121 **
3122 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3123 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3124 ** (just an integer to hold its size) while it is being processed.
3125 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3126 ** content is later written using
3127 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3128 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3129 **
3130 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3131 ** for the [prepared statement] or with a prepared statement for which
3132 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3133 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3134 ** routine is passed a [prepared statement] that has been finalized, the
3135 ** result is undefined and probably harmful.
3136 **
3137 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3138 ** ^Unbound parameters are interpreted as NULL.
3139 **
3140 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3141 ** [error code] if anything goes wrong.
3142 ** ^[SQLITE_RANGE] is returned if the parameter
3143 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3144 **
3145 ** See also: [sqlite3_bind_parameter_count()],
3146 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3147 */
3148 SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3149 SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
3150 SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
3151 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3152 SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
3153 SQLITE_API int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*));
3154 SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3155 SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3156 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3157
3158 /*
3159 ** CAPI3REF: Number Of SQL Parameters
3160 **
3161 ** ^This routine can be used to find the number of [SQL parameters]
3162 ** in a [prepared statement].  SQL parameters are tokens of the
3163 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3164 ** placeholders for values that are [sqlite3_bind_blob | bound]
3165 ** to the parameters at a later time.
3166 **
3167 ** ^(This routine actually returns the index of the largest (rightmost)
3168 ** parameter. For all forms except ?NNN, this will correspond to the
3169 ** number of unique parameters.  If parameters of the ?NNN form are used,
3170 ** there may be gaps in the list.)^
3171 **
3172 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3173 ** [sqlite3_bind_parameter_name()], and
3174 ** [sqlite3_bind_parameter_index()].
3175 */
3176 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
3177
3178 /*
3179 ** CAPI3REF: Name Of A Host Parameter
3180 **
3181 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3182 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3183 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3184 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3185 ** respectively.
3186 ** In other words, the initial ":" or "$" or "@" or "?"
3187 ** is included as part of the name.)^
3188 ** ^Parameters of the form "?" without a following integer have no name
3189 ** and are referred to as "nameless" or "anonymous parameters".
3190 **
3191 ** ^The first host parameter has an index of 1, not 0.
3192 **
3193 ** ^If the value N is out of range or if the N-th parameter is
3194 ** nameless, then NULL is returned.  ^The returned string is
3195 ** always in UTF-8 encoding even if the named parameter was
3196 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3197 ** [sqlite3_prepare16_v2()].
3198 **
3199 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3200 ** [sqlite3_bind_parameter_count()], and
3201 ** [sqlite3_bind_parameter_index()].
3202 */
3203 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3204
3205 /*
3206 ** CAPI3REF: Index Of A Parameter With A Given Name
3207 **
3208 ** ^Return the index of an SQL parameter given its name.  ^The
3209 ** index value returned is suitable for use as the second
3210 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3211 ** is returned if no matching parameter is found.  ^The parameter
3212 ** name must be given in UTF-8 even if the original statement
3213 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3214 **
3215 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3216 ** [sqlite3_bind_parameter_count()], and
3217 ** [sqlite3_bind_parameter_index()].
3218 */
3219 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3220
3221 /*
3222 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3223 **
3224 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3225 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3226 ** ^Use this routine to reset all host parameters to NULL.
3227 */
3228 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
3229
3230 /*
3231 ** CAPI3REF: Number Of Columns In A Result Set
3232 **
3233 ** ^Return the number of columns in the result set returned by the
3234 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3235 ** statement that does not return data (for example an [UPDATE]).
3236 */
3237 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
3238
3239 /*
3240 ** CAPI3REF: Column Names In A Result Set
3241 **
3242 ** ^These routines return the name assigned to a particular column
3243 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3244 ** interface returns a pointer to a zero-terminated UTF-8 string
3245 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3246 ** UTF-16 string.  ^The first parameter is the [prepared statement]
3247 ** that implements the [SELECT] statement. ^The second parameter is the
3248 ** column number.  ^The leftmost column is number 0.
3249 **
3250 ** ^The returned string pointer is valid until either the [prepared statement]
3251 ** is destroyed by [sqlite3_finalize()] or until the next call to
3252 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3253 **
3254 ** ^If sqlite3_malloc() fails during the processing of either routine
3255 ** (for example during a conversion from UTF-8 to UTF-16) then a
3256 ** NULL pointer is returned.
3257 **
3258 ** ^The name of a result column is the value of the "AS" clause for
3259 ** that column, if there is an AS clause.  If there is no AS clause
3260 ** then the name of the column is unspecified and may change from
3261 ** one release of SQLite to the next.
3262 */
3263 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
3264 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
3265
3266 /*
3267 ** CAPI3REF: Source Of Data In A Query Result
3268 **
3269 ** ^These routines provide a means to determine the database, table, and
3270 ** table column that is the origin of a particular result column in
3271 ** [SELECT] statement.
3272 ** ^The name of the database or table or column can be returned as
3273 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3274 ** the database name, the _table_ routines return the table name, and
3275 ** the origin_ routines return the column name.
3276 ** ^The returned string is valid until the [prepared statement] is destroyed
3277 ** using [sqlite3_finalize()] or until the same information is requested
3278 ** again in a different encoding.
3279 **
3280 ** ^The names returned are the original un-aliased names of the
3281 ** database, table, and column.
3282 **
3283 ** ^The first argument to these interfaces is a [prepared statement].
3284 ** ^These functions return information about the Nth result column returned by
3285 ** the statement, where N is the second function argument.
3286 ** ^The left-most column is column 0 for these routines.
3287 **
3288 ** ^If the Nth column returned by the statement is an expression or
3289 ** subquery and is not a column value, then all of these functions return
3290 ** NULL.  ^These routine might also return NULL if a memory allocation error
3291 ** occurs.  ^Otherwise, they return the name of the attached database, table,
3292 ** or column that query result column was extracted from.
3293 **
3294 ** ^As with all other SQLite APIs, those whose names end with "16" return
3295 ** UTF-16 encoded strings and the other functions return UTF-8.
3296 **
3297 ** ^These APIs are only available if the library was compiled with the
3298 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3299 **
3300 ** If two or more threads call one or more of these routines against the same
3301 ** prepared statement and column at the same time then the results are
3302 ** undefined.
3303 **
3304 ** If two or more threads call one or more
3305 ** [sqlite3_column_database_name | column metadata interfaces]
3306 ** for the same [prepared statement] and result column
3307 ** at the same time then the results are undefined.
3308 */
3309 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
3310 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
3311 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
3312 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
3313 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
3314 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
3315
3316 /*
3317 ** CAPI3REF: Declared Datatype Of A Query Result
3318 **
3319 ** ^(The first parameter is a [prepared statement].
3320 ** If this statement is a [SELECT] statement and the Nth column of the
3321 ** returned result set of that [SELECT] is a table column (not an
3322 ** expression or subquery) then the declared type of the table
3323 ** column is returned.)^  ^If the Nth column of the result set is an
3324 ** expression or subquery, then a NULL pointer is returned.
3325 ** ^The returned string is always UTF-8 encoded.
3326 **
3327 ** ^(For example, given the database schema:
3328 **
3329 ** CREATE TABLE t1(c1 VARIANT);
3330 **
3331 ** and the following statement to be compiled:
3332 **
3333 ** SELECT c1 + 1, c1 FROM t1;
3334 **
3335 ** this routine would return the string "VARIANT" for the second result
3336 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
3337 **
3338 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
3339 ** is declared to contain a particular type does not mean that the
3340 ** data stored in that column is of the declared type.  SQLite is
3341 ** strongly typed, but the typing is dynamic not static.  ^Type
3342 ** is associated with individual values, not with the containers
3343 ** used to hold those values.
3344 */
3345 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
3346 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
3347
3348 /*
3349 ** CAPI3REF: Evaluate An SQL Statement
3350 **
3351 ** After a [prepared statement] has been prepared using either
3352 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3353 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3354 ** must be called one or more times to evaluate the statement.
3355 **
3356 ** The details of the behavior of the sqlite3_step() interface depend
3357 ** on whether the statement was prepared using the newer "v2" interface
3358 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3359 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3360 ** new "v2" interface is recommended for new applications but the legacy
3361 ** interface will continue to be supported.
3362 **
3363 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3364 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3365 ** ^With the "v2" interface, any of the other [result codes] or
3366 ** [extended result codes] might be returned as well.
3367 **
3368 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3369 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3370 ** or occurs outside of an explicit transaction, then you can retry the
3371 ** statement.  If the statement is not a [COMMIT] and occurs within a
3372 ** explicit transaction then you should rollback the transaction before
3373 ** continuing.
3374 **
3375 ** ^[SQLITE_DONE] means that the statement has finished executing
3376 ** successfully.  sqlite3_step() should not be called again on this virtual
3377 ** machine without first calling [sqlite3_reset()] to reset the virtual
3378 ** machine back to its initial state.
3379 **
3380 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3381 ** is returned each time a new row of data is ready for processing by the
3382 ** caller. The values may be accessed using the [column access functions].
3383 ** sqlite3_step() is called again to retrieve the next row of data.
3384 **
3385 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3386 ** violation) has occurred.  sqlite3_step() should not be called again on
3387 ** the VM. More information may be found by calling [sqlite3_errmsg()].
3388 ** ^With the legacy interface, a more specific error code (for example,
3389 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3390 ** can be obtained by calling [sqlite3_reset()] on the
3391 ** [prepared statement].  ^In the "v2" interface,
3392 ** the more specific error code is returned directly by sqlite3_step().
3393 **
3394 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3395 ** Perhaps it was called on a [prepared statement] that has
3396 ** already been [sqlite3_finalize | finalized] or on one that had
3397 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3398 ** be the case that the same database connection is being used by two or
3399 ** more threads at the same moment in time.
3400 **
3401 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3402 ** API always returns a generic error code, [SQLITE_ERROR], following any
3403 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
3404 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
3405 ** specific [error codes] that better describes the error.
3406 ** We admit that this is a goofy design.  The problem has been fixed
3407 ** with the "v2" interface.  If you prepare all of your SQL statements
3408 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
3409 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
3410 ** then the more specific [error codes] are returned directly
3411 ** by sqlite3_step().  The use of the "v2" interface is recommended.
3412 */
3413 SQLITE_API int sqlite3_step(sqlite3_stmt*);
3414
3415 /*
3416 ** CAPI3REF: Number of columns in a result set
3417 **
3418 ** ^The sqlite3_data_count(P) the number of columns in the
3419 ** of the result set of [prepared statement] P.
3420 */
3421 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
3422
3423 /*
3424 ** CAPI3REF: Fundamental Datatypes
3425 ** KEYWORDS: SQLITE_TEXT
3426 **
3427 ** ^(Every value in SQLite has one of five fundamental datatypes:
3428 **
3429 ** <ul>
3430 ** <li> 64-bit signed integer
3431 ** <li> 64-bit IEEE floating point number
3432 ** <li> string
3433 ** <li> BLOB
3434 ** <li> NULL
3435 ** </ul>)^
3436 **
3437 ** These constants are codes for each of those types.
3438 **
3439 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
3440 ** for a completely different meaning.  Software that links against both
3441 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
3442 ** SQLITE_TEXT.
3443 */
3444 #define SQLITE_INTEGER  1
3445 #define SQLITE_FLOAT    2
3446 #define SQLITE_BLOB     4
3447 #define SQLITE_NULL     5
3448 #ifdef SQLITE_TEXT
3449 # undef SQLITE_TEXT
3450 #else
3451 # define SQLITE_TEXT     3
3452 #endif
3453 #define SQLITE3_TEXT     3
3454
3455 /*
3456 ** CAPI3REF: Result Values From A Query
3457 ** KEYWORDS: {column access functions}
3458 **
3459 ** These routines form the "result set" interface.
3460 **
3461 ** ^These routines return information about a single column of the current
3462 ** result row of a query.  ^In every case the first argument is a pointer
3463 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
3464 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
3465 ** and the second argument is the index of the column for which information
3466 ** should be returned. ^The leftmost column of the result set has the index 0.
3467 ** ^The number of columns in the result can be determined using
3468 ** [sqlite3_column_count()].
3469 **
3470 ** If the SQL statement does not currently point to a valid row, or if the
3471 ** column index is out of range, the result is undefined.
3472 ** These routines may only be called when the most recent call to
3473 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
3474 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
3475 ** If any of these routines are called after [sqlite3_reset()] or
3476 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
3477 ** something other than [SQLITE_ROW], the results are undefined.
3478 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
3479 ** are called from a different thread while any of these routines
3480 ** are pending, then the results are undefined.
3481 **
3482 ** ^The sqlite3_column_type() routine returns the
3483 ** [SQLITE_INTEGER | datatype code] for the initial data type
3484 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
3485 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
3486 ** returned by sqlite3_column_type() is only meaningful if no type
3487 ** conversions have occurred as described below.  After a type conversion,
3488 ** the value returned by sqlite3_column_type() is undefined.  Future
3489 ** versions of SQLite may change the behavior of sqlite3_column_type()
3490 ** following a type conversion.
3491 **
3492 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
3493 ** routine returns the number of bytes in that BLOB or string.
3494 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
3495 ** the string to UTF-8 and then returns the number of bytes.
3496 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
3497 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
3498 ** the number of bytes in that string.
3499 ** ^The value returned does not include the zero terminator at the end
3500 ** of the string.  ^For clarity: the value returned is the number of
3501 ** bytes in the string, not the number of characters.
3502 **
3503 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
3504 ** even empty strings, are always zero terminated.  ^The return
3505 ** value from sqlite3_column_blob() for a zero-length BLOB is an arbitrary
3506 ** pointer, possibly even a NULL pointer.
3507 **
3508 ** ^The sqlite3_column_bytes16() routine is similar to sqlite3_column_bytes()
3509 ** but leaves the result in UTF-16 in native byte order instead of UTF-8.
3510 ** ^The zero terminator is not included in this count.
3511 **
3512 ** ^The object returned by [sqlite3_column_value()] is an
3513 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
3514 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
3515 ** If the [unprotected sqlite3_value] object returned by
3516 ** [sqlite3_column_value()] is used in any other way, including calls
3517 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
3518 ** or [sqlite3_value_bytes()], then the behavior is undefined.
3519 **
3520 ** These routines attempt to convert the value where appropriate.  ^For
3521 ** example, if the internal representation is FLOAT and a text result
3522 ** is requested, [sqlite3_snprintf()] is used internally to perform the
3523 ** conversion automatically.  ^(The following table details the conversions
3524 ** that are applied:
3525 **
3526 ** <blockquote>
3527 ** <table border="1">
3528 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
3529 **
3530 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
3531 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
3532 ** <tr><td>  NULL    <td>   TEXT    <td> Result is NULL pointer
3533 ** <tr><td>  NULL    <td>   BLOB    <td> Result is NULL pointer
3534 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
3535 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
3536 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
3537 ** <tr><td>  FLOAT   <td> INTEGER   <td> Convert from float to integer
3538 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
3539 ** <tr><td>  FLOAT   <td>   BLOB    <td> Same as FLOAT->TEXT
3540 ** <tr><td>  TEXT    <td> INTEGER   <td> Use atoi()
3541 ** <tr><td>  TEXT    <td>  FLOAT    <td> Use atof()
3542 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
3543 ** <tr><td>  BLOB    <td> INTEGER   <td> Convert to TEXT then use atoi()
3544 ** <tr><td>  BLOB    <td>  FLOAT    <td> Convert to TEXT then use atof()
3545 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
3546 ** </table>
3547 ** </blockquote>)^
3548 **
3549 ** The table above makes reference to standard C library functions atoi()
3550 ** and atof().  SQLite does not really use these functions.  It has its
3551 ** own equivalent internal routines.  The atoi() and atof() names are
3552 ** used in the table for brevity and because they are familiar to most
3553 ** C programmers.
3554 **
3555 ** ^Note that when type conversions occur, pointers returned by prior
3556 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
3557 ** sqlite3_column_text16() may be invalidated.
3558 ** ^(Type conversions and pointer invalidations might occur
3559 ** in the following cases:
3560 **
3561 ** <ul>
3562 ** <li> The initial content is a BLOB and sqlite3_column_text() or
3563 **      sqlite3_column_text16() is called.  A zero-terminator might
3564 **      need to be added to the string.</li>
3565 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
3566 **      sqlite3_column_text16() is called.  The content must be converted
3567 **      to UTF-16.</li>
3568 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
3569 **      sqlite3_column_text() is called.  The content must be converted
3570 **      to UTF-8.</li>
3571 ** </ul>)^
3572 **
3573 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
3574 ** not invalidate a prior pointer, though of course the content of the buffer
3575 ** that the prior pointer points to will have been modified.  Other kinds
3576 ** of conversion are done in place when it is possible, but sometimes they
3577 ** are not possible and in those cases prior pointers are invalidated.
3578 **
3579 ** ^(The safest and easiest to remember policy is to invoke these routines
3580 ** in one of the following ways:
3581 **
3582 ** <ul>
3583 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
3584 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
3585 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
3586 ** </ul>)^
3587 **
3588 ** In other words, you should call sqlite3_column_text(),
3589 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
3590 ** into the desired format, then invoke sqlite3_column_bytes() or
3591 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
3592 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
3593 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
3594 ** with calls to sqlite3_column_bytes().
3595 **
3596 ** ^The pointers returned are valid until a type conversion occurs as
3597 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
3598 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
3599 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
3600 ** [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
3601 ** [sqlite3_free()].
3602 **
3603 ** ^(If a memory allocation error occurs during the evaluation of any
3604 ** of these routines, a default value is returned.  The default value
3605 ** is either the integer 0, the floating point number 0.0, or a NULL
3606 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
3607 ** [SQLITE_NOMEM].)^
3608 */
3609 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
3610 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
3611 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
3612 SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
3613 SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
3614 SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
3615 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
3616 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
3617 SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
3618 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
3619
3620 /*
3621 ** CAPI3REF: Destroy A Prepared Statement Object
3622 **
3623 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
3624 ** ^If the statement was executed successfully or not executed at all, then
3625 ** SQLITE_OK is returned. ^If execution of the statement failed then an
3626 ** [error code] or [extended error code] is returned.
3627 **
3628 ** ^This routine can be called at any point during the execution of the
3629 ** [prepared statement].  ^If the virtual machine has not
3630 ** completed execution when this routine is called, that is like
3631 ** encountering an error or an [sqlite3_interrupt | interrupt].
3632 ** ^Incomplete updates may be rolled back and transactions canceled,
3633 ** depending on the circumstances, and the
3634 ** [error code] returned will be [SQLITE_ABORT].
3635 */
3636 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
3637
3638 /*
3639 ** CAPI3REF: Reset A Prepared Statement Object
3640 **
3641 ** The sqlite3_reset() function is called to reset a [prepared statement]
3642 ** object back to its initial state, ready to be re-executed.
3643 ** ^Any SQL statement variables that had values bound to them using
3644 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
3645 ** Use [sqlite3_clear_bindings()] to reset the bindings.
3646 **
3647 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
3648 ** back to the beginning of its program.
3649 **
3650 ** ^If the most recent call to [sqlite3_step(S)] for the
3651 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
3652 ** or if [sqlite3_step(S)] has never before been called on S,
3653 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
3654 **
3655 ** ^If the most recent call to [sqlite3_step(S)] for the
3656 ** [prepared statement] S indicated an error, then
3657 ** [sqlite3_reset(S)] returns an appropriate [error code].
3658 **
3659 ** ^The [sqlite3_reset(S)] interface does not change the values
3660 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
3661 */
3662 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
3663
3664 /*
3665 ** CAPI3REF: Create Or Redefine SQL Functions
3666 ** KEYWORDS: {function creation routines}
3667 ** KEYWORDS: {application-defined SQL function}
3668 ** KEYWORDS: {application-defined SQL functions}
3669 **
3670 ** ^These two functions (collectively known as "function creation routines")
3671 ** are used to add SQL functions or aggregates or to redefine the behavior
3672 ** of existing SQL functions or aggregates.  The only difference between the
3673 ** two is that the second parameter, the name of the (scalar) function or
3674 ** aggregate, is encoded in UTF-8 for sqlite3_create_function() and UTF-16
3675 ** for sqlite3_create_function16().
3676 **
3677 ** ^The first parameter is the [database connection] to which the SQL
3678 ** function is to be added.  ^If an application uses more than one database
3679 ** connection then application-defined SQL functions must be added
3680 ** to each database connection separately.
3681 **
3682 ** The second parameter is the name of the SQL function to be created or
3683 ** redefined.  ^The length of the name is limited to 255 bytes, exclusive of
3684 ** the zero-terminator.  Note that the name length limit is in bytes, not
3685 ** characters.  ^Any attempt to create a function with a longer name
3686 ** will result in [SQLITE_ERROR] being returned.
3687 **
3688 ** ^The third parameter (nArg)
3689 ** is the number of arguments that the SQL function or
3690 ** aggregate takes. ^If this parameter is -1, then the SQL function or
3691 ** aggregate may take any number of arguments between 0 and the limit
3692 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
3693 ** parameter is less than -1 or greater than 127 then the behavior is
3694 ** undefined.
3695 **
3696 ** The fourth parameter, eTextRep, specifies what
3697 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
3698 ** its parameters.  Any SQL function implementation should be able to work
3699 ** work with UTF-8, UTF-16le, or UTF-16be.  But some implementations may be
3700 ** more efficient with one encoding than another.  ^An application may
3701 ** invoke sqlite3_create_function() or sqlite3_create_function16() multiple
3702 ** times with the same function but with different values of eTextRep.
3703 ** ^When multiple implementations of the same function are available, SQLite
3704 ** will pick the one that involves the least amount of data conversion.
3705 ** If there is only a single implementation which does not care what text
3706 ** encoding is used, then the fourth argument should be [SQLITE_ANY].
3707 **
3708 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
3709 ** function can gain access to this pointer using [sqlite3_user_data()].)^
3710 **
3711 ** The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are
3712 ** pointers to C-language functions that implement the SQL function or
3713 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
3714 ** callback only; NULL pointers should be passed as the xStep and xFinal
3715 ** parameters. ^An aggregate SQL function requires an implementation of xStep
3716 ** and xFinal and NULL should be passed for xFunc. ^To delete an existing
3717 ** SQL function or aggregate, pass NULL for all three function callbacks.
3718 **
3719 ** ^It is permitted to register multiple implementations of the same
3720 ** functions with the same name but with either differing numbers of
3721 ** arguments or differing preferred text encodings.  ^SQLite will use
3722 ** the implementation that most closely matches the way in which the
3723 ** SQL function is used.  ^A function implementation with a non-negative
3724 ** nArg parameter is a better match than a function implementation with
3725 ** a negative nArg.  ^A function where the preferred text encoding
3726 ** matches the database encoding is a better
3727 ** match than a function where the encoding is different.  
3728 ** ^A function where the encoding difference is between UTF16le and UTF16be
3729 ** is a closer match than a function where the encoding difference is
3730 ** between UTF8 and UTF16.
3731 **
3732 ** ^Built-in functions may be overloaded by new application-defined functions.
3733 ** ^The first application-defined function with a given name overrides all
3734 ** built-in functions in the same [database connection] with the same name.
3735 ** ^Subsequent application-defined functions of the same name only override 
3736 ** prior application-defined functions that are an exact match for the
3737 ** number of parameters and preferred encoding.
3738 **
3739 ** ^An application-defined function is permitted to call other
3740 ** SQLite interfaces.  However, such calls must not
3741 ** close the database connection nor finalize or reset the prepared
3742 ** statement in which the function is running.
3743 */
3744 SQLITE_API int sqlite3_create_function(
3745   sqlite3 *db,
3746   const char *zFunctionName,
3747   int nArg,
3748   int eTextRep,
3749   void *pApp,
3750   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3751   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3752   void (*xFinal)(sqlite3_context*)
3753 );
3754 SQLITE_API int sqlite3_create_function16(
3755   sqlite3 *db,
3756   const void *zFunctionName,
3757   int nArg,
3758   int eTextRep,
3759   void *pApp,
3760   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
3761   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
3762   void (*xFinal)(sqlite3_context*)
3763 );
3764
3765 /*
3766 ** CAPI3REF: Text Encodings
3767 **
3768 ** These constant define integer codes that represent the various
3769 ** text encodings supported by SQLite.
3770 */
3771 #define SQLITE_UTF8           1
3772 #define SQLITE_UTF16LE        2
3773 #define SQLITE_UTF16BE        3
3774 #define SQLITE_UTF16          4    /* Use native byte order */
3775 #define SQLITE_ANY            5    /* sqlite3_create_function only */
3776 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
3777
3778 /*
3779 ** CAPI3REF: Deprecated Functions
3780 ** DEPRECATED
3781 **
3782 ** These functions are [deprecated].  In order to maintain
3783 ** backwards compatibility with older code, these functions continue 
3784 ** to be supported.  However, new applications should avoid
3785 ** the use of these functions.  To help encourage people to avoid
3786 ** using these functions, we are not going to tell you what they do.
3787 */
3788 #ifndef SQLITE_OMIT_DEPRECATED
3789 SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
3790 SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
3791 SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
3792 SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
3793 SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
3794 SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),void*,sqlite3_int64);
3795 #endif
3796
3797 /*
3798 ** CAPI3REF: Obtaining SQL Function Parameter Values
3799 **
3800 ** The C-language implementation of SQL functions and aggregates uses
3801 ** this set of interface routines to access the parameter values on
3802 ** the function or aggregate.
3803 **
3804 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
3805 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
3806 ** define callbacks that implement the SQL functions and aggregates.
3807 ** The 4th parameter to these callbacks is an array of pointers to
3808 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
3809 ** each parameter to the SQL function.  These routines are used to
3810 ** extract values from the [sqlite3_value] objects.
3811 **
3812 ** These routines work only with [protected sqlite3_value] objects.
3813 ** Any attempt to use these routines on an [unprotected sqlite3_value]
3814 ** object results in undefined behavior.
3815 **
3816 ** ^These routines work just like the corresponding [column access functions]
3817 ** except that  these routines take a single [protected sqlite3_value] object
3818 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
3819 **
3820 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
3821 ** in the native byte-order of the host machine.  ^The
3822 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
3823 ** extract UTF-16 strings as big-endian and little-endian respectively.
3824 **
3825 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
3826 ** numeric affinity to the value.  This means that an attempt is
3827 ** made to convert the value to an integer or floating point.  If
3828 ** such a conversion is possible without loss of information (in other
3829 ** words, if the value is a string that looks like a number)
3830 ** then the conversion is performed.  Otherwise no conversion occurs.
3831 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
3832 **
3833 ** Please pay particular attention to the fact that the pointer returned
3834 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
3835 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
3836 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
3837 ** or [sqlite3_value_text16()].
3838 **
3839 ** These routines must be called from the same thread as
3840 ** the SQL function that supplied the [sqlite3_value*] parameters.
3841 */
3842 SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
3843 SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
3844 SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
3845 SQLITE_API double sqlite3_value_double(sqlite3_value*);
3846 SQLITE_API int sqlite3_value_int(sqlite3_value*);
3847 SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
3848 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
3849 SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
3850 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
3851 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
3852 SQLITE_API int sqlite3_value_type(sqlite3_value*);
3853 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
3854
3855 /*
3856 ** CAPI3REF: Obtain Aggregate Function Context
3857 **
3858 ** Implementions of aggregate SQL functions use this
3859 ** routine to allocate memory for storing their state.
3860 **
3861 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
3862 ** for a particular aggregate function, SQLite
3863 ** allocates N of memory, zeroes out that memory, and returns a pointer
3864 ** to the new memory. ^On second and subsequent calls to
3865 ** sqlite3_aggregate_context() for the same aggregate function instance,
3866 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
3867 ** called once for each invocation of the xStep callback and then one
3868 ** last time when the xFinal callback is invoked.  ^(When no rows match
3869 ** an aggregate query, the xStep() callback of the aggregate function
3870 ** implementation is never called and xFinal() is called exactly once.
3871 ** In those cases, sqlite3_aggregate_context() might be called for the
3872 ** first time from within xFinal().)^
3873 **
3874 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer if N is
3875 ** less than or equal to zero or if a memory allocate error occurs.
3876 **
3877 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
3878 ** determined by the N parameter on first successful call.  Changing the
3879 ** value of N in subsequent call to sqlite3_aggregate_context() within
3880 ** the same aggregate function instance will not resize the memory
3881 ** allocation.)^
3882 **
3883 ** ^SQLite automatically frees the memory allocated by 
3884 ** sqlite3_aggregate_context() when the aggregate query concludes.
3885 **
3886 ** The first parameter must be a copy of the
3887 ** [sqlite3_context | SQL function context] that is the first parameter
3888 ** to the xStep or xFinal callback routine that implements the aggregate
3889 ** function.
3890 **
3891 ** This routine must be called from the same thread in which
3892 ** the aggregate SQL function is running.
3893 */
3894 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
3895
3896 /*
3897 ** CAPI3REF: User Data For Functions
3898 **
3899 ** ^The sqlite3_user_data() interface returns a copy of
3900 ** the pointer that was the pUserData parameter (the 5th parameter)
3901 ** of the [sqlite3_create_function()]
3902 ** and [sqlite3_create_function16()] routines that originally
3903 ** registered the application defined function.
3904 **
3905 ** This routine must be called from the same thread in which
3906 ** the application-defined function is running.
3907 */
3908 SQLITE_API void *sqlite3_user_data(sqlite3_context*);
3909
3910 /*
3911 ** CAPI3REF: Database Connection For Functions
3912 **
3913 ** ^The sqlite3_context_db_handle() interface returns a copy of
3914 ** the pointer to the [database connection] (the 1st parameter)
3915 ** of the [sqlite3_create_function()]
3916 ** and [sqlite3_create_function16()] routines that originally
3917 ** registered the application defined function.
3918 */
3919 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
3920
3921 /*
3922 ** CAPI3REF: Function Auxiliary Data
3923 **
3924 ** The following two functions may be used by scalar SQL functions to
3925 ** associate metadata with argument values. If the same value is passed to
3926 ** multiple invocations of the same SQL function during query execution, under
3927 ** some circumstances the associated metadata may be preserved. This may
3928 ** be used, for example, to add a regular-expression matching scalar
3929 ** function. The compiled version of the regular expression is stored as
3930 ** metadata associated with the SQL value passed as the regular expression
3931 ** pattern.  The compiled regular expression can be reused on multiple
3932 ** invocations of the same function so that the original pattern string
3933 ** does not need to be recompiled on each invocation.
3934 **
3935 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
3936 ** associated by the sqlite3_set_auxdata() function with the Nth argument
3937 ** value to the application-defined function. ^If no metadata has been ever
3938 ** been set for the Nth argument of the function, or if the corresponding
3939 ** function parameter has changed since the meta-data was set,
3940 ** then sqlite3_get_auxdata() returns a NULL pointer.
3941 **
3942 ** ^The sqlite3_set_auxdata() interface saves the metadata
3943 ** pointed to by its 3rd parameter as the metadata for the N-th
3944 ** argument of the application-defined function.  Subsequent
3945 ** calls to sqlite3_get_auxdata() might return this data, if it has
3946 ** not been destroyed.
3947 ** ^If it is not NULL, SQLite will invoke the destructor
3948 ** function given by the 4th parameter to sqlite3_set_auxdata() on
3949 ** the metadata when the corresponding function parameter changes
3950 ** or when the SQL statement completes, whichever comes first.
3951 **
3952 ** SQLite is free to call the destructor and drop metadata on any
3953 ** parameter of any function at any time.  ^The only guarantee is that
3954 ** the destructor will be called before the metadata is dropped.
3955 **
3956 ** ^(In practice, metadata is preserved between function calls for
3957 ** expressions that are constant at compile time. This includes literal
3958 ** values and [parameters].)^
3959 **
3960 ** These routines must be called from the same thread in which
3961 ** the SQL function is running.
3962 */
3963 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
3964 SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
3965
3966
3967 /*
3968 ** CAPI3REF: Constants Defining Special Destructor Behavior
3969 **
3970 ** These are special values for the destructor that is passed in as the
3971 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
3972 ** argument is SQLITE_STATIC, it means that the content pointer is constant
3973 ** and will never change.  It does not need to be destroyed.  ^The
3974 ** SQLITE_TRANSIENT value means that the content will likely change in
3975 ** the near future and that SQLite should make its own private copy of
3976 ** the content before returning.
3977 **
3978 ** The typedef is necessary to work around problems in certain
3979 ** C++ compilers.  See ticket #2191.
3980 */
3981 typedef void (*sqlite3_destructor_type)(void*);
3982 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
3983 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
3984
3985 /*
3986 ** CAPI3REF: Setting The Result Of An SQL Function
3987 **
3988 ** These routines are used by the xFunc or xFinal callbacks that
3989 ** implement SQL functions and aggregates.  See
3990 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
3991 ** for additional information.
3992 **
3993 ** These functions work very much like the [parameter binding] family of
3994 ** functions used to bind values to host parameters in prepared statements.
3995 ** Refer to the [SQL parameter] documentation for additional information.
3996 **
3997 ** ^The sqlite3_result_blob() interface sets the result from
3998 ** an application-defined function to be the BLOB whose content is pointed
3999 ** to by the second parameter and which is N bytes long where N is the
4000 ** third parameter.
4001 **
4002 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4003 ** the application-defined function to be a BLOB containing all zero
4004 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4005 **
4006 ** ^The sqlite3_result_double() interface sets the result from
4007 ** an application-defined function to be a floating point value specified
4008 ** by its 2nd argument.
4009 **
4010 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4011 ** cause the implemented SQL function to throw an exception.
4012 ** ^SQLite uses the string pointed to by the
4013 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4014 ** as the text of an error message.  ^SQLite interprets the error
4015 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4016 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4017 ** byte order.  ^If the third parameter to sqlite3_result_error()
4018 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4019 ** message all text up through the first zero character.
4020 ** ^If the third parameter to sqlite3_result_error() or
4021 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4022 ** bytes (not characters) from the 2nd parameter as the error message.
4023 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4024 ** routines make a private copy of the error message text before
4025 ** they return.  Hence, the calling function can deallocate or
4026 ** modify the text after they return without harm.
4027 ** ^The sqlite3_result_error_code() function changes the error code
4028 ** returned by SQLite as a result of an error in a function.  ^By default,
4029 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4030 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4031 **
4032 ** ^The sqlite3_result_toobig() interface causes SQLite to throw an error
4033 ** indicating that a string or BLOB is too long to represent.
4034 **
4035 ** ^The sqlite3_result_nomem() interface causes SQLite to throw an error
4036 ** indicating that a memory allocation failed.
4037 **
4038 ** ^The sqlite3_result_int() interface sets the return value
4039 ** of the application-defined function to be the 32-bit signed integer
4040 ** value given in the 2nd argument.
4041 ** ^The sqlite3_result_int64() interface sets the return value
4042 ** of the application-defined function to be the 64-bit signed integer
4043 ** value given in the 2nd argument.
4044 **
4045 ** ^The sqlite3_result_null() interface sets the return value
4046 ** of the application-defined function to be NULL.
4047 **
4048 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4049 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4050 ** set the return value of the application-defined function to be
4051 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4052 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4053 ** ^SQLite takes the text result from the application from
4054 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4055 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4056 ** is negative, then SQLite takes result text from the 2nd parameter
4057 ** through the first zero character.
4058 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4059 ** is non-negative, then as many bytes (not characters) of the text
4060 ** pointed to by the 2nd parameter are taken as the application-defined
4061 ** function result.
4062 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4063 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4064 ** function as the destructor on the text or BLOB result when it has
4065 ** finished using that result.
4066 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4067 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4068 ** assumes that the text or BLOB result is in constant space and does not
4069 ** copy the content of the parameter nor call a destructor on the content
4070 ** when it has finished using that result.
4071 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4072 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4073 ** then SQLite makes a copy of the result into space obtained from
4074 ** from [sqlite3_malloc()] before it returns.
4075 **
4076 ** ^The sqlite3_result_value() interface sets the result of
4077 ** the application-defined function to be a copy the
4078 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4079 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4080 ** so that the [sqlite3_value] specified in the parameter may change or
4081 ** be deallocated after sqlite3_result_value() returns without harm.
4082 ** ^A [protected sqlite3_value] object may always be used where an
4083 ** [unprotected sqlite3_value] object is required, so either
4084 ** kind of [sqlite3_value] object can be used with this interface.
4085 **
4086 ** If these routines are called from within the different thread
4087 ** than the one containing the application-defined function that received
4088 ** the [sqlite3_context] pointer, the results are undefined.
4089 */
4090 SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4091 SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
4092 SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
4093 SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
4094 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
4095 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
4096 SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
4097 SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
4098 SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4099 SQLITE_API void sqlite3_result_null(sqlite3_context*);
4100 SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4101 SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4102 SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4103 SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4104 SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4105 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
4106
4107 /*
4108 ** CAPI3REF: Define New Collating Sequences
4109 **
4110 ** These functions are used to add new collation sequences to the
4111 ** [database connection] specified as the first argument.
4112 **
4113 ** ^The name of the new collation sequence is specified as a UTF-8 string
4114 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4115 ** and a UTF-16 string for sqlite3_create_collation16(). ^In all cases
4116 ** the name is passed as the second function argument.
4117 **
4118 ** ^The third argument may be one of the constants [SQLITE_UTF8],
4119 ** [SQLITE_UTF16LE], or [SQLITE_UTF16BE], indicating that the user-supplied
4120 ** routine expects to be passed pointers to strings encoded using UTF-8,
4121 ** UTF-16 little-endian, or UTF-16 big-endian, respectively. ^The
4122 ** third argument might also be [SQLITE_UTF16] to indicate that the routine
4123 ** expects pointers to be UTF-16 strings in the native byte order, or the
4124 ** argument can be [SQLITE_UTF16_ALIGNED] if the
4125 ** the routine expects pointers to 16-bit word aligned strings
4126 ** of UTF-16 in the native byte order.
4127 **
4128 ** A pointer to the user supplied routine must be passed as the fifth
4129 ** argument.  ^If it is NULL, this is the same as deleting the collation
4130 ** sequence (so that SQLite cannot call it anymore).
4131 ** ^Each time the application supplied function is invoked, it is passed
4132 ** as its first parameter a copy of the void* passed as the fourth argument
4133 ** to sqlite3_create_collation() or sqlite3_create_collation16().
4134 **
4135 ** ^The remaining arguments to the application-supplied routine are two strings,
4136 ** each represented by a (length, data) pair and encoded in the encoding
4137 ** that was passed as the third argument when the collation sequence was
4138 ** registered.  The application defined collation routine should
4139 ** return negative, zero or positive if the first string is less than,
4140 ** equal to, or greater than the second string. i.e. (STRING1 - STRING2).
4141 **
4142 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4143 ** except that it takes an extra argument which is a destructor for
4144 ** the collation.  ^The destructor is called when the collation is
4145 ** destroyed and is passed a copy of the fourth parameter void* pointer
4146 ** of the sqlite3_create_collation_v2().
4147 ** ^Collations are destroyed when they are overridden by later calls to the
4148 ** collation creation functions or when the [database connection] is closed
4149 ** using [sqlite3_close()].
4150 **
4151 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4152 */
4153 SQLITE_API int sqlite3_create_collation(
4154   sqlite3*, 
4155   const char *zName, 
4156   int eTextRep, 
4157   void*,
4158   int(*xCompare)(void*,int,const void*,int,const void*)
4159 );
4160 SQLITE_API int sqlite3_create_collation_v2(
4161   sqlite3*, 
4162   const char *zName, 
4163   int eTextRep, 
4164   void*,
4165   int(*xCompare)(void*,int,const void*,int,const void*),
4166   void(*xDestroy)(void*)
4167 );
4168 SQLITE_API int sqlite3_create_collation16(
4169   sqlite3*, 
4170   const void *zName,
4171   int eTextRep, 
4172   void*,
4173   int(*xCompare)(void*,int,const void*,int,const void*)
4174 );
4175
4176 /*
4177 ** CAPI3REF: Collation Needed Callbacks
4178 **
4179 ** ^To avoid having to register all collation sequences before a database
4180 ** can be used, a single callback function may be registered with the
4181 ** [database connection] to be invoked whenever an undefined collation
4182 ** sequence is required.
4183 **
4184 ** ^If the function is registered using the sqlite3_collation_needed() API,
4185 ** then it is passed the names of undefined collation sequences as strings
4186 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4187 ** the names are passed as UTF-16 in machine native byte order.
4188 ** ^A call to either function replaces the existing collation-needed callback.
4189 **
4190 ** ^(When the callback is invoked, the first argument passed is a copy
4191 ** of the second argument to sqlite3_collation_needed() or
4192 ** sqlite3_collation_needed16().  The second argument is the database
4193 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4194 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4195 ** sequence function required.  The fourth parameter is the name of the
4196 ** required collation sequence.)^
4197 **
4198 ** The callback function should register the desired collation using
4199 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4200 ** [sqlite3_create_collation_v2()].
4201 */
4202 SQLITE_API int sqlite3_collation_needed(
4203   sqlite3*, 
4204   void*, 
4205   void(*)(void*,sqlite3*,int eTextRep,const char*)
4206 );
4207 SQLITE_API int sqlite3_collation_needed16(
4208   sqlite3*, 
4209   void*,
4210   void(*)(void*,sqlite3*,int eTextRep,const void*)
4211 );
4212
4213 #if SQLITE_HAS_CODEC
4214 /*
4215 ** Specify the key for an encrypted database.  This routine should be
4216 ** called right after sqlite3_open().
4217 **
4218 ** The code to implement this API is not available in the public release
4219 ** of SQLite.
4220 */
4221 SQLITE_API int sqlite3_key(
4222   sqlite3 *db,                   /* Database to be rekeyed */
4223   const void *pKey, int nKey     /* The key */
4224 );
4225
4226 /*
4227 ** Change the key on an open database.  If the current database is not
4228 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4229 ** database is decrypted.
4230 **
4231 ** The code to implement this API is not available in the public release
4232 ** of SQLite.
4233 */
4234 SQLITE_API int sqlite3_rekey(
4235   sqlite3 *db,                   /* Database to be rekeyed */
4236   const void *pKey, int nKey     /* The new key */
4237 );
4238
4239 /*
4240 ** Specify the activation key for a SEE database.  Unless 
4241 ** activated, none of the SEE routines will work.
4242 */
4243 SQLITE_API void sqlite3_activate_see(
4244   const char *zPassPhrase        /* Activation phrase */
4245 );
4246 #endif
4247
4248 #ifdef SQLITE_ENABLE_CEROD
4249 /*
4250 ** Specify the activation key for a CEROD database.  Unless 
4251 ** activated, none of the CEROD routines will work.
4252 */
4253 SQLITE_API void sqlite3_activate_cerod(
4254   const char *zPassPhrase        /* Activation phrase */
4255 );
4256 #endif
4257
4258 /*
4259 ** CAPI3REF: Suspend Execution For A Short Time
4260 **
4261 ** ^The sqlite3_sleep() function causes the current thread to suspend execution
4262 ** for at least a number of milliseconds specified in its parameter.
4263 **
4264 ** ^If the operating system does not support sleep requests with
4265 ** millisecond time resolution, then the time will be rounded up to
4266 ** the nearest second. ^The number of milliseconds of sleep actually
4267 ** requested from the operating system is returned.
4268 **
4269 ** ^SQLite implements this interface by calling the xSleep()
4270 ** method of the default [sqlite3_vfs] object.
4271 */
4272 SQLITE_API int sqlite3_sleep(int);
4273
4274 /*
4275 ** CAPI3REF: Name Of The Folder Holding Temporary Files
4276 **
4277 ** ^(If this global variable is made to point to a string which is
4278 ** the name of a folder (a.k.a. directory), then all temporary files
4279 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
4280 ** will be placed in that directory.)^  ^If this variable
4281 ** is a NULL pointer, then SQLite performs a search for an appropriate
4282 ** temporary file directory.
4283 **
4284 ** It is not safe to read or modify this variable in more than one
4285 ** thread at a time.  It is not safe to read or modify this variable
4286 ** if a [database connection] is being used at the same time in a separate
4287 ** thread.
4288 ** It is intended that this variable be set once
4289 ** as part of process initialization and before any SQLite interface
4290 ** routines have been called and that this variable remain unchanged
4291 ** thereafter.
4292 **
4293 ** ^The [temp_store_directory pragma] may modify this variable and cause
4294 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
4295 ** the [temp_store_directory pragma] always assumes that any string
4296 ** that this variable points to is held in memory obtained from 
4297 ** [sqlite3_malloc] and the pragma may attempt to free that memory
4298 ** using [sqlite3_free].
4299 ** Hence, if this variable is modified directly, either it should be
4300 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
4301 ** or else the use of the [temp_store_directory pragma] should be avoided.
4302 */
4303 SQLITE_API char *sqlite3_temp_directory;
4304
4305 /*
4306 ** CAPI3REF: Test For Auto-Commit Mode
4307 ** KEYWORDS: {autocommit mode}
4308 **
4309 ** ^The sqlite3_get_autocommit() interface returns non-zero or
4310 ** zero if the given database connection is or is not in autocommit mode,
4311 ** respectively.  ^Autocommit mode is on by default.
4312 ** ^Autocommit mode is disabled by a [BEGIN] statement.
4313 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
4314 **
4315 ** If certain kinds of errors occur on a statement within a multi-statement
4316 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
4317 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
4318 ** transaction might be rolled back automatically.  The only way to
4319 ** find out whether SQLite automatically rolled back the transaction after
4320 ** an error is to use this function.
4321 **
4322 ** If another thread changes the autocommit status of the database
4323 ** connection while this routine is running, then the return value
4324 ** is undefined.
4325 */
4326 SQLITE_API int sqlite3_get_autocommit(sqlite3*);
4327
4328 /*
4329 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
4330 **
4331 ** ^The sqlite3_db_handle interface returns the [database connection] handle
4332 ** to which a [prepared statement] belongs.  ^The [database connection]
4333 ** returned by sqlite3_db_handle is the same [database connection]
4334 ** that was the first argument
4335 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
4336 ** create the statement in the first place.
4337 */
4338 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
4339
4340 /*
4341 ** CAPI3REF: Find the next prepared statement
4342 **
4343 ** ^This interface returns a pointer to the next [prepared statement] after
4344 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
4345 ** then this interface returns a pointer to the first prepared statement
4346 ** associated with the database connection pDb.  ^If no prepared statement
4347 ** satisfies the conditions of this routine, it returns NULL.
4348 **
4349 ** The [database connection] pointer D in a call to
4350 ** [sqlite3_next_stmt(D,S)] must refer to an open database
4351 ** connection and in particular must not be a NULL pointer.
4352 */
4353 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
4354
4355 /*
4356 ** CAPI3REF: Commit And Rollback Notification Callbacks
4357 **
4358 ** ^The sqlite3_commit_hook() interface registers a callback
4359 ** function to be invoked whenever a transaction is [COMMIT | committed].
4360 ** ^Any callback set by a previous call to sqlite3_commit_hook()
4361 ** for the same database connection is overridden.
4362 ** ^The sqlite3_rollback_hook() interface registers a callback
4363 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
4364 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
4365 ** for the same database connection is overridden.
4366 ** ^The pArg argument is passed through to the callback.
4367 ** ^If the callback on a commit hook function returns non-zero,
4368 ** then the commit is converted into a rollback.
4369 **
4370 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
4371 ** return the P argument from the previous call of the same function
4372 ** on the same [database connection] D, or NULL for
4373 ** the first call for each function on D.
4374 **
4375 ** The callback implementation must not do anything that will modify
4376 ** the database connection that invoked the callback.  Any actions
4377 ** to modify the database connection must be deferred until after the
4378 ** completion of the [sqlite3_step()] call that triggered the commit
4379 ** or rollback hook in the first place.
4380 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4381 ** database connections for the meaning of "modify" in this paragraph.
4382 **
4383 ** ^Registering a NULL function disables the callback.
4384 **
4385 ** ^When the commit hook callback routine returns zero, the [COMMIT]
4386 ** operation is allowed to continue normally.  ^If the commit hook
4387 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
4388 ** ^The rollback hook is invoked on a rollback that results from a commit
4389 ** hook returning non-zero, just as it would be with any other rollback.
4390 **
4391 ** ^For the purposes of this API, a transaction is said to have been
4392 ** rolled back if an explicit "ROLLBACK" statement is executed, or
4393 ** an error or constraint causes an implicit rollback to occur.
4394 ** ^The rollback callback is not invoked if a transaction is
4395 ** automatically rolled back because the database connection is closed.
4396 ** ^The rollback callback is not invoked if a transaction is
4397 ** rolled back because a commit callback returned non-zero.
4398 **
4399 ** See also the [sqlite3_update_hook()] interface.
4400 */
4401 SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
4402 SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
4403
4404 /*
4405 ** CAPI3REF: Data Change Notification Callbacks
4406 **
4407 ** ^The sqlite3_update_hook() interface registers a callback function
4408 ** with the [database connection] identified by the first argument
4409 ** to be invoked whenever a row is updated, inserted or deleted.
4410 ** ^Any callback set by a previous call to this function
4411 ** for the same database connection is overridden.
4412 **
4413 ** ^The second argument is a pointer to the function to invoke when a
4414 ** row is updated, inserted or deleted.
4415 ** ^The first argument to the callback is a copy of the third argument
4416 ** to sqlite3_update_hook().
4417 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
4418 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
4419 ** to be invoked.
4420 ** ^The third and fourth arguments to the callback contain pointers to the
4421 ** database and table name containing the affected row.
4422 ** ^The final callback parameter is the [rowid] of the row.
4423 ** ^In the case of an update, this is the [rowid] after the update takes place.
4424 **
4425 ** ^(The update hook is not invoked when internal system tables are
4426 ** modified (i.e. sqlite_master and sqlite_sequence).)^
4427 **
4428 ** ^In the current implementation, the update hook
4429 ** is not invoked when duplication rows are deleted because of an
4430 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
4431 ** invoked when rows are deleted using the [truncate optimization].
4432 ** The exceptions defined in this paragraph might change in a future
4433 ** release of SQLite.
4434 **
4435 ** The update hook implementation must not do anything that will modify
4436 ** the database connection that invoked the update hook.  Any actions
4437 ** to modify the database connection must be deferred until after the
4438 ** completion of the [sqlite3_step()] call that triggered the update hook.
4439 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
4440 ** database connections for the meaning of "modify" in this paragraph.
4441 **
4442 ** ^The sqlite3_update_hook(D,C,P) function
4443 ** returns the P argument from the previous call
4444 ** on the same [database connection] D, or NULL for
4445 ** the first call on D.
4446 **
4447 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
4448 ** interfaces.
4449 */
4450 SQLITE_API void *sqlite3_update_hook(
4451   sqlite3*, 
4452   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
4453   void*
4454 );
4455
4456 /*
4457 ** CAPI3REF: Enable Or Disable Shared Pager Cache
4458 ** KEYWORDS: {shared cache}
4459 **
4460 ** ^(This routine enables or disables the sharing of the database cache
4461 ** and schema data structures between [database connection | connections]
4462 ** to the same database. Sharing is enabled if the argument is true
4463 ** and disabled if the argument is false.)^
4464 **
4465 ** ^Cache sharing is enabled and disabled for an entire process.
4466 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
4467 ** sharing was enabled or disabled for each thread separately.
4468 **
4469 ** ^(The cache sharing mode set by this interface effects all subsequent
4470 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
4471 ** Existing database connections continue use the sharing mode
4472 ** that was in effect at the time they were opened.)^
4473 **
4474 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
4475 ** successfully.  An [error code] is returned otherwise.)^
4476 **
4477 ** ^Shared cache is disabled by default. But this might change in
4478 ** future releases of SQLite.  Applications that care about shared
4479 ** cache setting should set it explicitly.
4480 **
4481 ** See Also:  [SQLite Shared-Cache Mode]
4482 */
4483 SQLITE_API int sqlite3_enable_shared_cache(int);
4484
4485 /*
4486 ** CAPI3REF: Attempt To Free Heap Memory
4487 **
4488 ** ^The sqlite3_release_memory() interface attempts to free N bytes
4489 ** of heap memory by deallocating non-essential memory allocations
4490 ** held by the database library.   Memory used to cache database
4491 ** pages to improve performance is an example of non-essential memory.
4492 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
4493 ** which might be more or less than the amount requested.
4494 */
4495 SQLITE_API int sqlite3_release_memory(int);
4496
4497 /*
4498 ** CAPI3REF: Impose A Limit On Heap Size
4499 **
4500 ** ^The sqlite3_soft_heap_limit() interface places a "soft" limit
4501 ** on the amount of heap memory that may be allocated by SQLite.
4502 ** ^If an internal allocation is requested that would exceed the
4503 ** soft heap limit, [sqlite3_release_memory()] is invoked one or
4504 ** more times to free up some space before the allocation is performed.
4505 **
4506 ** ^The limit is called "soft" because if [sqlite3_release_memory()]
4507 ** cannot free sufficient memory to prevent the limit from being exceeded,
4508 ** the memory is allocated anyway and the current operation proceeds.
4509 **
4510 ** ^A negative or zero value for N means that there is no soft heap limit and
4511 ** [sqlite3_release_memory()] will only be called when memory is exhausted.
4512 ** ^The default value for the soft heap limit is zero.
4513 **
4514 ** ^(SQLite makes a best effort to honor the soft heap limit.
4515 ** But if the soft heap limit cannot be honored, execution will
4516 ** continue without error or notification.)^  This is why the limit is
4517 ** called a "soft" limit.  It is advisory only.
4518 **
4519 ** Prior to SQLite version 3.5.0, this routine only constrained the memory
4520 ** allocated by a single thread - the same thread in which this routine
4521 ** runs.  Beginning with SQLite version 3.5.0, the soft heap limit is
4522 ** applied to all threads. The value specified for the soft heap limit
4523 ** is an upper bound on the total memory allocation for all threads. In
4524 ** version 3.5.0 there is no mechanism for limiting the heap usage for
4525 ** individual threads.
4526 */
4527 SQLITE_API void sqlite3_soft_heap_limit(int);
4528
4529 /*
4530 ** CAPI3REF: Extract Metadata About A Column Of A Table
4531 **
4532 ** ^This routine returns metadata about a specific column of a specific
4533 ** database table accessible using the [database connection] handle
4534 ** passed as the first function argument.
4535 **
4536 ** ^The column is identified by the second, third and fourth parameters to
4537 ** this function. ^The second parameter is either the name of the database
4538 ** (i.e. "main", "temp", or an attached database) containing the specified
4539 ** table or NULL. ^If it is NULL, then all attached databases are searched
4540 ** for the table using the same algorithm used by the database engine to
4541 ** resolve unqualified table references.
4542 **
4543 ** ^The third and fourth parameters to this function are the table and column
4544 ** name of the desired column, respectively. Neither of these parameters
4545 ** may be NULL.
4546 **
4547 ** ^Metadata is returned by writing to the memory locations passed as the 5th
4548 ** and subsequent parameters to this function. ^Any of these arguments may be
4549 ** NULL, in which case the corresponding element of metadata is omitted.
4550 **
4551 ** ^(<blockquote>
4552 ** <table border="1">
4553 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
4554 **
4555 ** <tr><td> 5th <td> const char* <td> Data type
4556 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
4557 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
4558 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
4559 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
4560 ** </table>
4561 ** </blockquote>)^
4562 **
4563 ** ^The memory pointed to by the character pointers returned for the
4564 ** declaration type and collation sequence is valid only until the next
4565 ** call to any SQLite API function.
4566 **
4567 ** ^If the specified table is actually a view, an [error code] is returned.
4568 **
4569 ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
4570 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
4571 ** parameters are set for the explicitly declared column. ^(If there is no
4572 ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
4573 ** parameters are set as follows:
4574 **
4575 ** <pre>
4576 **     data type: "INTEGER"
4577 **     collation sequence: "BINARY"
4578 **     not null: 0
4579 **     primary key: 1
4580 **     auto increment: 0
4581 ** </pre>)^
4582 **
4583 ** ^(This function may load one or more schemas from database files. If an
4584 ** error occurs during this process, or if the requested table or column
4585 ** cannot be found, an [error code] is returned and an error message left
4586 ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
4587 **
4588 ** ^This API is only available if the library was compiled with the
4589 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
4590 */
4591 SQLITE_API int sqlite3_table_column_metadata(
4592   sqlite3 *db,                /* Connection handle */
4593   const char *zDbName,        /* Database name or NULL */
4594   const char *zTableName,     /* Table name */
4595   const char *zColumnName,    /* Column name */
4596   char const **pzDataType,    /* OUTPUT: Declared data type */
4597   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
4598   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
4599   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
4600   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
4601 );
4602
4603 /*
4604 ** CAPI3REF: Load An Extension
4605 **
4606 ** ^This interface loads an SQLite extension library from the named file.
4607 **
4608 ** ^The sqlite3_load_extension() interface attempts to load an
4609 ** SQLite extension library contained in the file zFile.
4610 **
4611 ** ^The entry point is zProc.
4612 ** ^zProc may be 0, in which case the name of the entry point
4613 ** defaults to "sqlite3_extension_init".
4614 ** ^The sqlite3_load_extension() interface returns
4615 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
4616 ** ^If an error occurs and pzErrMsg is not 0, then the
4617 ** [sqlite3_load_extension()] interface shall attempt to
4618 ** fill *pzErrMsg with error message text stored in memory
4619 ** obtained from [sqlite3_malloc()]. The calling function
4620 ** should free this memory by calling [sqlite3_free()].
4621 **
4622 ** ^Extension loading must be enabled using
4623 ** [sqlite3_enable_load_extension()] prior to calling this API,
4624 ** otherwise an error will be returned.
4625 **
4626 ** See also the [load_extension() SQL function].
4627 */
4628 SQLITE_API int sqlite3_load_extension(
4629   sqlite3 *db,          /* Load the extension into this database connection */
4630   const char *zFile,    /* Name of the shared library containing extension */
4631   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
4632   char **pzErrMsg       /* Put error message here if not 0 */
4633 );
4634
4635 /*
4636 ** CAPI3REF: Enable Or Disable Extension Loading
4637 **
4638 ** ^So as not to open security holes in older applications that are
4639 ** unprepared to deal with extension loading, and as a means of disabling
4640 ** extension loading while evaluating user-entered SQL, the following API
4641 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
4642 **
4643 ** ^Extension loading is off by default. See ticket #1863.
4644 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
4645 ** to turn extension loading on and call it with onoff==0 to turn
4646 ** it back off again.
4647 */
4648 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
4649
4650 /*
4651 ** CAPI3REF: Automatically Load An Extensions
4652 **
4653 ** ^This API can be invoked at program startup in order to register
4654 ** one or more statically linked extensions that will be available
4655 ** to all new [database connections].
4656 **
4657 ** ^(This routine stores a pointer to the extension entry point
4658 ** in an array that is obtained from [sqlite3_malloc()].  That memory
4659 ** is deallocated by [sqlite3_reset_auto_extension()].)^
4660 **
4661 ** ^This function registers an extension entry point that is
4662 ** automatically invoked whenever a new [database connection]
4663 ** is opened using [sqlite3_open()], [sqlite3_open16()],
4664 ** or [sqlite3_open_v2()].
4665 ** ^Duplicate extensions are detected so calling this routine
4666 ** multiple times with the same extension is harmless.
4667 ** ^Automatic extensions apply across all threads.
4668 */
4669 SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
4670
4671 /*
4672 ** CAPI3REF: Reset Automatic Extension Loading
4673 **
4674 ** ^(This function disables all previously registered automatic
4675 ** extensions. It undoes the effect of all prior
4676 ** [sqlite3_auto_extension()] calls.)^
4677 **
4678 ** ^This function disables automatic extensions in all threads.
4679 */
4680 SQLITE_API void sqlite3_reset_auto_extension(void);
4681
4682 /*
4683 ****** EXPERIMENTAL - subject to change without notice **************
4684 **
4685 ** The interface to the virtual-table mechanism is currently considered
4686 ** to be experimental.  The interface might change in incompatible ways.
4687 ** If this is a problem for you, do not use the interface at this time.
4688 **
4689 ** When the virtual-table mechanism stabilizes, we will declare the
4690 ** interface fixed, support it indefinitely, and remove this comment.
4691 */
4692
4693 /*
4694 ** Structures used by the virtual table interface
4695 */
4696 typedef struct sqlite3_vtab sqlite3_vtab;
4697 typedef struct sqlite3_index_info sqlite3_index_info;
4698 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
4699 typedef struct sqlite3_module sqlite3_module;
4700
4701 /*
4702 ** CAPI3REF: Virtual Table Object
4703 ** KEYWORDS: sqlite3_module {virtual table module}
4704 ** EXPERIMENTAL
4705 **
4706 ** This structure, sometimes called a a "virtual table module", 
4707 ** defines the implementation of a [virtual tables].  
4708 ** This structure consists mostly of methods for the module.
4709 **
4710 ** ^A virtual table module is created by filling in a persistent
4711 ** instance of this structure and passing a pointer to that instance
4712 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
4713 ** ^The registration remains valid until it is replaced by a different
4714 ** module or until the [database connection] closes.  The content
4715 ** of this structure must not change while it is registered with
4716 ** any database connection.
4717 */
4718 struct sqlite3_module {
4719   int iVersion;
4720   int (*xCreate)(sqlite3*, void *pAux,
4721                int argc, const char *const*argv,
4722                sqlite3_vtab **ppVTab, char**);
4723   int (*xConnect)(sqlite3*, void *pAux,
4724                int argc, const char *const*argv,
4725                sqlite3_vtab **ppVTab, char**);
4726   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
4727   int (*xDisconnect)(sqlite3_vtab *pVTab);
4728   int (*xDestroy)(sqlite3_vtab *pVTab);
4729   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
4730   int (*xClose)(sqlite3_vtab_cursor*);
4731   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
4732                 int argc, sqlite3_value **argv);
4733   int (*xNext)(sqlite3_vtab_cursor*);
4734   int (*xEof)(sqlite3_vtab_cursor*);
4735   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
4736   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
4737   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
4738   int (*xBegin)(sqlite3_vtab *pVTab);
4739   int (*xSync)(sqlite3_vtab *pVTab);
4740   int (*xCommit)(sqlite3_vtab *pVTab);
4741   int (*xRollback)(sqlite3_vtab *pVTab);
4742   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
4743                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
4744                        void **ppArg);
4745   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
4746 };
4747
4748 /*
4749 ** CAPI3REF: Virtual Table Indexing Information
4750 ** KEYWORDS: sqlite3_index_info
4751 ** EXPERIMENTAL
4752 **
4753 ** The sqlite3_index_info structure and its substructures is used to
4754 ** pass information into and receive the reply from the [xBestIndex]
4755 ** method of a [virtual table module].  The fields under **Inputs** are the
4756 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
4757 ** results into the **Outputs** fields.
4758 **
4759 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
4760 **
4761 ** <pre>column OP expr</pre>
4762 **
4763 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
4764 ** stored in aConstraint[].op.)^  ^(The index of the column is stored in
4765 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
4766 ** expr on the right-hand side can be evaluated (and thus the constraint
4767 ** is usable) and false if it cannot.)^
4768 **
4769 ** ^The optimizer automatically inverts terms of the form "expr OP column"
4770 ** and makes other simplifications to the WHERE clause in an attempt to
4771 ** get as many WHERE clause terms into the form shown above as possible.
4772 ** ^The aConstraint[] array only reports WHERE clause terms that are
4773 ** relevant to the particular virtual table being queried.
4774 **
4775 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
4776 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
4777 **
4778 ** The [xBestIndex] method must fill aConstraintUsage[] with information
4779 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
4780 ** the right-hand side of the corresponding aConstraint[] is evaluated
4781 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
4782 ** is true, then the constraint is assumed to be fully handled by the
4783 ** virtual table and is not checked again by SQLite.)^
4784 **
4785 ** ^The idxNum and idxPtr values are recorded and passed into the
4786 ** [xFilter] method.
4787 ** ^[sqlite3_free()] is used to free idxPtr if and only if
4788 ** needToFreeIdxPtr is true.
4789 **
4790 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
4791 ** the correct order to satisfy the ORDER BY clause so that no separate
4792 ** sorting step is required.
4793 **
4794 ** ^The estimatedCost value is an estimate of the cost of doing the
4795 ** particular lookup.  A full scan of a table with N entries should have
4796 ** a cost of N.  A binary search of a table of N entries should have a
4797 ** cost of approximately log(N).
4798 */
4799 struct sqlite3_index_info {
4800   /* Inputs */
4801   int nConstraint;           /* Number of entries in aConstraint */
4802   struct sqlite3_index_constraint {
4803      int iColumn;              /* Column on left-hand side of constraint */
4804      unsigned char op;         /* Constraint operator */
4805      unsigned char usable;     /* True if this constraint is usable */
4806      int iTermOffset;          /* Used internally - xBestIndex should ignore */
4807   } *aConstraint;            /* Table of WHERE clause constraints */
4808   int nOrderBy;              /* Number of terms in the ORDER BY clause */
4809   struct sqlite3_index_orderby {
4810      int iColumn;              /* Column number */
4811      unsigned char desc;       /* True for DESC.  False for ASC. */
4812   } *aOrderBy;               /* The ORDER BY clause */
4813   /* Outputs */
4814   struct sqlite3_index_constraint_usage {
4815     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
4816     unsigned char omit;      /* Do not code a test for this constraint */
4817   } *aConstraintUsage;
4818   int idxNum;                /* Number used to identify the index */
4819   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
4820   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
4821   int orderByConsumed;       /* True if output is already ordered */
4822   double estimatedCost;      /* Estimated cost of using this index */
4823 };
4824 #define SQLITE_INDEX_CONSTRAINT_EQ    2
4825 #define SQLITE_INDEX_CONSTRAINT_GT    4
4826 #define SQLITE_INDEX_CONSTRAINT_LE    8
4827 #define SQLITE_INDEX_CONSTRAINT_LT    16
4828 #define SQLITE_INDEX_CONSTRAINT_GE    32
4829 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
4830
4831 /*
4832 ** CAPI3REF: Register A Virtual Table Implementation
4833 ** EXPERIMENTAL
4834 **
4835 ** ^These routines are used to register a new [virtual table module] name.
4836 ** ^Module names must be registered before
4837 ** creating a new [virtual table] using the module and before using a
4838 ** preexisting [virtual table] for the module.
4839 **
4840 ** ^The module name is registered on the [database connection] specified
4841 ** by the first parameter.  ^The name of the module is given by the 
4842 ** second parameter.  ^The third parameter is a pointer to
4843 ** the implementation of the [virtual table module].   ^The fourth
4844 ** parameter is an arbitrary client data pointer that is passed through
4845 ** into the [xCreate] and [xConnect] methods of the virtual table module
4846 ** when a new virtual table is be being created or reinitialized.
4847 **
4848 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
4849 ** is a pointer to a destructor for the pClientData.  ^SQLite will
4850 ** invoke the destructor function (if it is not NULL) when SQLite
4851 ** no longer needs the pClientData pointer.  ^The sqlite3_create_module()
4852 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
4853 ** destructor.
4854 */
4855 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module(
4856   sqlite3 *db,               /* SQLite connection to register module with */
4857   const char *zName,         /* Name of the module */
4858   const sqlite3_module *p,   /* Methods for the module */
4859   void *pClientData          /* Client data for xCreate/xConnect */
4860 );
4861 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_create_module_v2(
4862   sqlite3 *db,               /* SQLite connection to register module with */
4863   const char *zName,         /* Name of the module */
4864   const sqlite3_module *p,   /* Methods for the module */
4865   void *pClientData,         /* Client data for xCreate/xConnect */
4866   void(*xDestroy)(void*)     /* Module destructor function */
4867 );
4868
4869 /*
4870 ** CAPI3REF: Virtual Table Instance Object
4871 ** KEYWORDS: sqlite3_vtab
4872 ** EXPERIMENTAL
4873 **
4874 ** Every [virtual table module] implementation uses a subclass
4875 ** of this object to describe a particular instance
4876 ** of the [virtual table].  Each subclass will
4877 ** be tailored to the specific needs of the module implementation.
4878 ** The purpose of this superclass is to define certain fields that are
4879 ** common to all module implementations.
4880 **
4881 ** ^Virtual tables methods can set an error message by assigning a
4882 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
4883 ** take care that any prior string is freed by a call to [sqlite3_free()]
4884 ** prior to assigning a new string to zErrMsg.  ^After the error message
4885 ** is delivered up to the client application, the string will be automatically
4886 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
4887 */
4888 struct sqlite3_vtab {
4889   const sqlite3_module *pModule;  /* The module for this virtual table */
4890   int nRef;                       /* NO LONGER USED */
4891   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
4892   /* Virtual table implementations will typically add additional fields */
4893 };
4894
4895 /*
4896 ** CAPI3REF: Virtual Table Cursor Object
4897 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
4898 ** EXPERIMENTAL
4899 **
4900 ** Every [virtual table module] implementation uses a subclass of the
4901 ** following structure to describe cursors that point into the
4902 ** [virtual table] and are used
4903 ** to loop through the virtual table.  Cursors are created using the
4904 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
4905 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
4906 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
4907 ** of the module.  Each module implementation will define
4908 ** the content of a cursor structure to suit its own needs.
4909 **
4910 ** This superclass exists in order to define fields of the cursor that
4911 ** are common to all implementations.
4912 */
4913 struct sqlite3_vtab_cursor {
4914   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
4915   /* Virtual table implementations will typically add additional fields */
4916 };
4917
4918 /*
4919 ** CAPI3REF: Declare The Schema Of A Virtual Table
4920 ** EXPERIMENTAL
4921 **
4922 ** ^The [xCreate] and [xConnect] methods of a
4923 ** [virtual table module] call this interface
4924 ** to declare the format (the names and datatypes of the columns) of
4925 ** the virtual tables they implement.
4926 */
4927 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
4928
4929 /*
4930 ** CAPI3REF: Overload A Function For A Virtual Table
4931 ** EXPERIMENTAL
4932 **
4933 ** ^(Virtual tables can provide alternative implementations of functions
4934 ** using the [xFindFunction] method of the [virtual table module].  
4935 ** But global versions of those functions
4936 ** must exist in order to be overloaded.)^
4937 **
4938 ** ^(This API makes sure a global version of a function with a particular
4939 ** name and number of parameters exists.  If no such function exists
4940 ** before this API is called, a new function is created.)^  ^The implementation
4941 ** of the new function always causes an exception to be thrown.  So
4942 ** the new function is not good for anything by itself.  Its only
4943 ** purpose is to be a placeholder function that can be overloaded
4944 ** by a [virtual table].
4945 */
4946 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
4947
4948 /*
4949 ** The interface to the virtual-table mechanism defined above (back up
4950 ** to a comment remarkably similar to this one) is currently considered
4951 ** to be experimental.  The interface might change in incompatible ways.
4952 ** If this is a problem for you, do not use the interface at this time.
4953 **
4954 ** When the virtual-table mechanism stabilizes, we will declare the
4955 ** interface fixed, support it indefinitely, and remove this comment.
4956 **
4957 ****** EXPERIMENTAL - subject to change without notice **************
4958 */
4959
4960 /*
4961 ** CAPI3REF: A Handle To An Open BLOB
4962 ** KEYWORDS: {BLOB handle} {BLOB handles}
4963 **
4964 ** An instance of this object represents an open BLOB on which
4965 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
4966 ** ^Objects of this type are created by [sqlite3_blob_open()]
4967 ** and destroyed by [sqlite3_blob_close()].
4968 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
4969 ** can be used to read or write small subsections of the BLOB.
4970 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
4971 */
4972 typedef struct sqlite3_blob sqlite3_blob;
4973
4974 /*
4975 ** CAPI3REF: Open A BLOB For Incremental I/O
4976 **
4977 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
4978 ** in row iRow, column zColumn, table zTable in database zDb;
4979 ** in other words, the same BLOB that would be selected by:
4980 **
4981 ** <pre>
4982 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
4983 ** </pre>)^
4984 **
4985 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
4986 ** and write access. ^If it is zero, the BLOB is opened for read access.
4987 ** ^It is not possible to open a column that is part of an index or primary 
4988 ** key for writing. ^If [foreign key constraints] are enabled, it is 
4989 ** not possible to open a column that is part of a [child key] for writing.
4990 **
4991 ** ^Note that the database name is not the filename that contains
4992 ** the database but rather the symbolic name of the database that
4993 ** appears after the AS keyword when the database is connected using [ATTACH].
4994 ** ^For the main database file, the database name is "main".
4995 ** ^For TEMP tables, the database name is "temp".
4996 **
4997 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
4998 ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
4999 ** to be a null pointer.)^
5000 ** ^This function sets the [database connection] error code and message
5001 ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
5002 ** functions. ^Note that the *ppBlob variable is always initialized in a
5003 ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
5004 ** regardless of the success or failure of this routine.
5005 **
5006 ** ^(If the row that a BLOB handle points to is modified by an
5007 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5008 ** then the BLOB handle is marked as "expired".
5009 ** This is true if any column of the row is changed, even a column
5010 ** other than the one the BLOB handle is open on.)^
5011 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5012 ** a expired BLOB handle fail with an return code of [SQLITE_ABORT].
5013 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5014 ** rolled back by the expiration of the BLOB.  Such changes will eventually
5015 ** commit if the transaction continues to completion.)^
5016 **
5017 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5018 ** the opened blob.  ^The size of a blob may not be changed by this
5019 ** interface.  Use the [UPDATE] SQL command to change the size of a
5020 ** blob.
5021 **
5022 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5023 ** and the built-in [zeroblob] SQL function can be used, if desired,
5024 ** to create an empty, zero-filled blob in which to read or write using
5025 ** this interface.
5026 **
5027 ** To avoid a resource leak, every open [BLOB handle] should eventually
5028 ** be released by a call to [sqlite3_blob_close()].
5029 */
5030 SQLITE_API int sqlite3_blob_open(
5031   sqlite3*,
5032   const char *zDb,
5033   const char *zTable,
5034   const char *zColumn,
5035   sqlite3_int64 iRow,
5036   int flags,
5037   sqlite3_blob **ppBlob
5038 );
5039
5040 /*
5041 ** CAPI3REF: Close A BLOB Handle
5042 **
5043 ** ^Closes an open [BLOB handle].
5044 **
5045 ** ^Closing a BLOB shall cause the current transaction to commit
5046 ** if there are no other BLOBs, no pending prepared statements, and the
5047 ** database connection is in [autocommit mode].
5048 ** ^If any writes were made to the BLOB, they might be held in cache
5049 ** until the close operation if they will fit.
5050 **
5051 ** ^(Closing the BLOB often forces the changes
5052 ** out to disk and so if any I/O errors occur, they will likely occur
5053 ** at the time when the BLOB is closed.  Any errors that occur during
5054 ** closing are reported as a non-zero return value.)^
5055 **
5056 ** ^(The BLOB is closed unconditionally.  Even if this routine returns
5057 ** an error code, the BLOB is still closed.)^
5058 **
5059 ** ^Calling this routine with a null pointer (such as would be returned
5060 ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
5061 */
5062 SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
5063
5064 /*
5065 ** CAPI3REF: Return The Size Of An Open BLOB
5066 **
5067 ** ^Returns the size in bytes of the BLOB accessible via the 
5068 ** successfully opened [BLOB handle] in its only argument.  ^The
5069 ** incremental blob I/O routines can only read or overwriting existing
5070 ** blob content; they cannot change the size of a blob.
5071 **
5072 ** This routine only works on a [BLOB handle] which has been created
5073 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5074 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5075 ** to this routine results in undefined and probably undesirable behavior.
5076 */
5077 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
5078
5079 /*
5080 ** CAPI3REF: Read Data From A BLOB Incrementally
5081 **
5082 ** ^(This function is used to read data from an open [BLOB handle] into a
5083 ** caller-supplied buffer. N bytes of data are copied into buffer Z
5084 ** from the open BLOB, starting at offset iOffset.)^
5085 **
5086 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5087 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
5088 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
5089 ** ^The size of the blob (and hence the maximum value of N+iOffset)
5090 ** can be determined using the [sqlite3_blob_bytes()] interface.
5091 **
5092 ** ^An attempt to read from an expired [BLOB handle] fails with an
5093 ** error code of [SQLITE_ABORT].
5094 **
5095 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
5096 ** Otherwise, an [error code] or an [extended error code] is returned.)^
5097 **
5098 ** This routine only works on a [BLOB handle] which has been created
5099 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5100 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5101 ** to this routine results in undefined and probably undesirable behavior.
5102 **
5103 ** See also: [sqlite3_blob_write()].
5104 */
5105 SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
5106
5107 /*
5108 ** CAPI3REF: Write Data Into A BLOB Incrementally
5109 **
5110 ** ^This function is used to write data into an open [BLOB handle] from a
5111 ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
5112 ** into the open BLOB, starting at offset iOffset.
5113 **
5114 ** ^If the [BLOB handle] passed as the first argument was not opened for
5115 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
5116 ** this function returns [SQLITE_READONLY].
5117 **
5118 ** ^This function may only modify the contents of the BLOB; it is
5119 ** not possible to increase the size of a BLOB using this API.
5120 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
5121 ** [SQLITE_ERROR] is returned and no data is written.  ^If N is
5122 ** less than zero [SQLITE_ERROR] is returned and no data is written.
5123 ** The size of the BLOB (and hence the maximum value of N+iOffset)
5124 ** can be determined using the [sqlite3_blob_bytes()] interface.
5125 **
5126 ** ^An attempt to write to an expired [BLOB handle] fails with an
5127 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
5128 ** before the [BLOB handle] expired are not rolled back by the
5129 ** expiration of the handle, though of course those changes might
5130 ** have been overwritten by the statement that expired the BLOB handle
5131 ** or by other independent statements.
5132 **
5133 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
5134 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
5135 **
5136 ** This routine only works on a [BLOB handle] which has been created
5137 ** by a prior successful call to [sqlite3_blob_open()] and which has not
5138 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
5139 ** to this routine results in undefined and probably undesirable behavior.
5140 **
5141 ** See also: [sqlite3_blob_read()].
5142 */
5143 SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
5144
5145 /*
5146 ** CAPI3REF: Virtual File System Objects
5147 **
5148 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
5149 ** that SQLite uses to interact
5150 ** with the underlying operating system.  Most SQLite builds come with a
5151 ** single default VFS that is appropriate for the host computer.
5152 ** New VFSes can be registered and existing VFSes can be unregistered.
5153 ** The following interfaces are provided.
5154 **
5155 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
5156 ** ^Names are case sensitive.
5157 ** ^Names are zero-terminated UTF-8 strings.
5158 ** ^If there is no match, a NULL pointer is returned.
5159 ** ^If zVfsName is NULL then the default VFS is returned.
5160 **
5161 ** ^New VFSes are registered with sqlite3_vfs_register().
5162 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
5163 ** ^The same VFS can be registered multiple times without injury.
5164 ** ^To make an existing VFS into the default VFS, register it again
5165 ** with the makeDflt flag set.  If two different VFSes with the
5166 ** same name are registered, the behavior is undefined.  If a
5167 ** VFS is registered with a name that is NULL or an empty string,
5168 ** then the behavior is undefined.
5169 **
5170 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
5171 ** ^(If the default VFS is unregistered, another VFS is chosen as
5172 ** the default.  The choice for the new VFS is arbitrary.)^
5173 */
5174 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
5175 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
5176 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
5177
5178 /*
5179 ** CAPI3REF: Mutexes
5180 **
5181 ** The SQLite core uses these routines for thread
5182 ** synchronization. Though they are intended for internal
5183 ** use by SQLite, code that links against SQLite is
5184 ** permitted to use any of these routines.
5185 **
5186 ** The SQLite source code contains multiple implementations
5187 ** of these mutex routines.  An appropriate implementation
5188 ** is selected automatically at compile-time.  ^(The following
5189 ** implementations are available in the SQLite core:
5190 **
5191 ** <ul>
5192 ** <li>   SQLITE_MUTEX_OS2
5193 ** <li>   SQLITE_MUTEX_PTHREAD
5194 ** <li>   SQLITE_MUTEX_W32
5195 ** <li>   SQLITE_MUTEX_NOOP
5196 ** </ul>)^
5197 **
5198 ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
5199 ** that does no real locking and is appropriate for use in
5200 ** a single-threaded application.  ^The SQLITE_MUTEX_OS2,
5201 ** SQLITE_MUTEX_PTHREAD, and SQLITE_MUTEX_W32 implementations
5202 ** are appropriate for use on OS/2, Unix, and Windows.
5203 **
5204 ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
5205 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
5206 ** implementation is included with the library. In this case the
5207 ** application must supply a custom mutex implementation using the
5208 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
5209 ** before calling sqlite3_initialize() or any other public sqlite3_
5210 ** function that calls sqlite3_initialize().)^
5211 **
5212 ** ^The sqlite3_mutex_alloc() routine allocates a new
5213 ** mutex and returns a pointer to it. ^If it returns NULL
5214 ** that means that a mutex could not be allocated.  ^SQLite
5215 ** will unwind its stack and return an error.  ^(The argument
5216 ** to sqlite3_mutex_alloc() is one of these integer constants:
5217 **
5218 ** <ul>
5219 ** <li>  SQLITE_MUTEX_FAST
5220 ** <li>  SQLITE_MUTEX_RECURSIVE
5221 ** <li>  SQLITE_MUTEX_STATIC_MASTER
5222 ** <li>  SQLITE_MUTEX_STATIC_MEM
5223 ** <li>  SQLITE_MUTEX_STATIC_MEM2
5224 ** <li>  SQLITE_MUTEX_STATIC_PRNG
5225 ** <li>  SQLITE_MUTEX_STATIC_LRU
5226 ** <li>  SQLITE_MUTEX_STATIC_LRU2
5227 ** </ul>)^
5228 **
5229 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
5230 ** cause sqlite3_mutex_alloc() to create
5231 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
5232 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
5233 ** The mutex implementation does not need to make a distinction
5234 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
5235 ** not want to.  ^SQLite will only request a recursive mutex in
5236 ** cases where it really needs one.  ^If a faster non-recursive mutex
5237 ** implementation is available on the host platform, the mutex subsystem
5238 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
5239 **
5240 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
5241 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
5242 ** a pointer to a static preexisting mutex.  ^Six static mutexes are
5243 ** used by the current version of SQLite.  Future versions of SQLite
5244 ** may add additional static mutexes.  Static mutexes are for internal
5245 ** use by SQLite only.  Applications that use SQLite mutexes should
5246 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
5247 ** SQLITE_MUTEX_RECURSIVE.
5248 **
5249 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
5250 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
5251 ** returns a different mutex on every call.  ^But for the static
5252 ** mutex types, the same mutex is returned on every call that has
5253 ** the same type number.
5254 **
5255 ** ^The sqlite3_mutex_free() routine deallocates a previously
5256 ** allocated dynamic mutex.  ^SQLite is careful to deallocate every
5257 ** dynamic mutex that it allocates.  The dynamic mutexes must not be in
5258 ** use when they are deallocated.  Attempting to deallocate a static
5259 ** mutex results in undefined behavior.  ^SQLite never deallocates
5260 ** a static mutex.
5261 **
5262 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
5263 ** to enter a mutex.  ^If another thread is already within the mutex,
5264 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
5265 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
5266 ** upon successful entry.  ^(Mutexes created using
5267 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
5268 ** In such cases the,
5269 ** mutex must be exited an equal number of times before another thread
5270 ** can enter.)^  ^(If the same thread tries to enter any other
5271 ** kind of mutex more than once, the behavior is undefined.
5272 ** SQLite will never exhibit
5273 ** such behavior in its own use of mutexes.)^
5274 **
5275 ** ^(Some systems (for example, Windows 95) do not support the operation
5276 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
5277 ** will always return SQLITE_BUSY.  The SQLite core only ever uses
5278 ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
5279 **
5280 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
5281 ** previously entered by the same thread.   ^(The behavior
5282 ** is undefined if the mutex is not currently entered by the
5283 ** calling thread or is not currently allocated.  SQLite will
5284 ** never do either.)^
5285 **
5286 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
5287 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
5288 ** behave as no-ops.
5289 **
5290 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
5291 */
5292 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
5293 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
5294 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
5295 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
5296 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
5297
5298 /*
5299 ** CAPI3REF: Mutex Methods Object
5300 ** EXPERIMENTAL
5301 **
5302 ** An instance of this structure defines the low-level routines
5303 ** used to allocate and use mutexes.
5304 **
5305 ** Usually, the default mutex implementations provided by SQLite are
5306 ** sufficient, however the user has the option of substituting a custom
5307 ** implementation for specialized deployments or systems for which SQLite
5308 ** does not provide a suitable implementation. In this case, the user
5309 ** creates and populates an instance of this structure to pass
5310 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
5311 ** Additionally, an instance of this structure can be used as an
5312 ** output variable when querying the system for the current mutex
5313 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
5314 **
5315 ** ^The xMutexInit method defined by this structure is invoked as
5316 ** part of system initialization by the sqlite3_initialize() function.
5317 ** ^The xMutexInit routine is calle by SQLite exactly once for each
5318 ** effective call to [sqlite3_initialize()].
5319 **
5320 ** ^The xMutexEnd method defined by this structure is invoked as
5321 ** part of system shutdown by the sqlite3_shutdown() function. The
5322 ** implementation of this method is expected to release all outstanding
5323 ** resources obtained by the mutex methods implementation, especially
5324 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
5325 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
5326 **
5327 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
5328 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
5329 ** xMutexNotheld) implement the following interfaces (respectively):
5330 **
5331 ** <ul>
5332 **   <li>  [sqlite3_mutex_alloc()] </li>
5333 **   <li>  [sqlite3_mutex_free()] </li>
5334 **   <li>  [sqlite3_mutex_enter()] </li>
5335 **   <li>  [sqlite3_mutex_try()] </li>
5336 **   <li>  [sqlite3_mutex_leave()] </li>
5337 **   <li>  [sqlite3_mutex_held()] </li>
5338 **   <li>  [sqlite3_mutex_notheld()] </li>
5339 ** </ul>)^
5340 **
5341 ** The only difference is that the public sqlite3_XXX functions enumerated
5342 ** above silently ignore any invocations that pass a NULL pointer instead
5343 ** of a valid mutex handle. The implementations of the methods defined
5344 ** by this structure are not required to handle this case, the results
5345 ** of passing a NULL pointer instead of a valid mutex handle are undefined
5346 ** (i.e. it is acceptable to provide an implementation that segfaults if
5347 ** it is passed a NULL pointer).
5348 **
5349 ** The xMutexInit() method must be threadsafe.  ^It must be harmless to
5350 ** invoke xMutexInit() mutiple times within the same process and without
5351 ** intervening calls to xMutexEnd().  Second and subsequent calls to
5352 ** xMutexInit() must be no-ops.
5353 **
5354 ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
5355 ** and its associates).  ^Similarly, xMutexAlloc() must not use SQLite memory
5356 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
5357 ** memory allocation for a fast or recursive mutex.
5358 **
5359 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
5360 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
5361 ** If xMutexInit fails in any way, it is expected to clean up after itself
5362 ** prior to returning.
5363 */
5364 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
5365 struct sqlite3_mutex_methods {
5366   int (*xMutexInit)(void);
5367   int (*xMutexEnd)(void);
5368   sqlite3_mutex *(*xMutexAlloc)(int);
5369   void (*xMutexFree)(sqlite3_mutex *);
5370   void (*xMutexEnter)(sqlite3_mutex *);
5371   int (*xMutexTry)(sqlite3_mutex *);
5372   void (*xMutexLeave)(sqlite3_mutex *);
5373   int (*xMutexHeld)(sqlite3_mutex *);
5374   int (*xMutexNotheld)(sqlite3_mutex *);
5375 };
5376
5377 /*
5378 ** CAPI3REF: Mutex Verification Routines
5379 **
5380 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
5381 ** are intended for use inside assert() statements.  ^The SQLite core
5382 ** never uses these routines except inside an assert() and applications
5383 ** are advised to follow the lead of the core.  ^The SQLite core only
5384 ** provides implementations for these routines when it is compiled
5385 ** with the SQLITE_DEBUG flag.  ^External mutex implementations
5386 ** are only required to provide these routines if SQLITE_DEBUG is
5387 ** defined and if NDEBUG is not defined.
5388 **
5389 ** ^These routines should return true if the mutex in their argument
5390 ** is held or not held, respectively, by the calling thread.
5391 **
5392 ** ^The implementation is not required to provided versions of these
5393 ** routines that actually work. If the implementation does not provide working
5394 ** versions of these routines, it should at least provide stubs that always
5395 ** return true so that one does not get spurious assertion failures.
5396 **
5397 ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
5398 ** the routine should return 1.   This seems counter-intuitive since
5399 ** clearly the mutex cannot be held if it does not exist.  But the
5400 ** the reason the mutex does not exist is because the build is not
5401 ** using mutexes.  And we do not want the assert() containing the
5402 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
5403 ** the appropriate thing to do.  ^The sqlite3_mutex_notheld()
5404 ** interface should also return 1 when given a NULL pointer.
5405 */
5406 #ifndef NDEBUG
5407 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
5408 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
5409 #endif
5410
5411 /*
5412 ** CAPI3REF: Mutex Types
5413 **
5414 ** The [sqlite3_mutex_alloc()] interface takes a single argument
5415 ** which is one of these integer constants.
5416 **
5417 ** The set of static mutexes may change from one SQLite release to the
5418 ** next.  Applications that override the built-in mutex logic must be
5419 ** prepared to accommodate additional static mutexes.
5420 */
5421 #define SQLITE_MUTEX_FAST             0
5422 #define SQLITE_MUTEX_RECURSIVE        1
5423 #define SQLITE_MUTEX_STATIC_MASTER    2
5424 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
5425 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
5426 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
5427 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
5428 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
5429 #define SQLITE_MUTEX_STATIC_LRU2      7  /* lru page list */
5430
5431 /*
5432 ** CAPI3REF: Retrieve the mutex for a database connection
5433 **
5434 ** ^This interface returns a pointer the [sqlite3_mutex] object that 
5435 ** serializes access to the [database connection] given in the argument
5436 ** when the [threading mode] is Serialized.
5437 ** ^If the [threading mode] is Single-thread or Multi-thread then this
5438 ** routine returns a NULL pointer.
5439 */
5440 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
5441
5442 /*
5443 ** CAPI3REF: Low-Level Control Of Database Files
5444 **
5445 ** ^The [sqlite3_file_control()] interface makes a direct call to the
5446 ** xFileControl method for the [sqlite3_io_methods] object associated
5447 ** with a particular database identified by the second argument. ^The
5448 ** name of the database "main" for the main database or "temp" for the
5449 ** TEMP database, or the name that appears after the AS keyword for
5450 ** databases that are added using the [ATTACH] SQL command.
5451 ** ^A NULL pointer can be used in place of "main" to refer to the
5452 ** main database file.
5453 ** ^The third and fourth parameters to this routine
5454 ** are passed directly through to the second and third parameters of
5455 ** the xFileControl method.  ^The return value of the xFileControl
5456 ** method becomes the return value of this routine.
5457 **
5458 ** ^If the second parameter (zDbName) does not match the name of any
5459 ** open database file, then SQLITE_ERROR is returned.  ^This error
5460 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
5461 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
5462 ** also return SQLITE_ERROR.  There is no way to distinguish between
5463 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
5464 ** xFileControl method.
5465 **
5466 ** See also: [SQLITE_FCNTL_LOCKSTATE]
5467 */
5468 SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
5469
5470 /*
5471 ** CAPI3REF: Testing Interface
5472 **
5473 ** ^The sqlite3_test_control() interface is used to read out internal
5474 ** state of SQLite and to inject faults into SQLite for testing
5475 ** purposes.  ^The first parameter is an operation code that determines
5476 ** the number, meaning, and operation of all subsequent parameters.
5477 **
5478 ** This interface is not for use by applications.  It exists solely
5479 ** for verifying the correct operation of the SQLite library.  Depending
5480 ** on how the SQLite library is compiled, this interface might not exist.
5481 **
5482 ** The details of the operation codes, their meanings, the parameters
5483 ** they take, and what they do are all subject to change without notice.
5484 ** Unlike most of the SQLite API, this function is not guaranteed to
5485 ** operate consistently from one release to the next.
5486 */
5487 SQLITE_API int sqlite3_test_control(int op, ...);
5488
5489 /*
5490 ** CAPI3REF: Testing Interface Operation Codes
5491 **
5492 ** These constants are the valid operation code parameters used
5493 ** as the first argument to [sqlite3_test_control()].
5494 **
5495 ** These parameters and their meanings are subject to change
5496 ** without notice.  These values are for testing purposes only.
5497 ** Applications should not use any of these parameters or the
5498 ** [sqlite3_test_control()] interface.
5499 */
5500 #define SQLITE_TESTCTRL_FIRST                    5
5501 #define SQLITE_TESTCTRL_PRNG_SAVE                5
5502 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
5503 #define SQLITE_TESTCTRL_PRNG_RESET               7
5504 #define SQLITE_TESTCTRL_BITVEC_TEST              8
5505 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
5506 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
5507 #define SQLITE_TESTCTRL_PENDING_BYTE            11
5508 #define SQLITE_TESTCTRL_ASSERT                  12
5509 #define SQLITE_TESTCTRL_ALWAYS                  13
5510 #define SQLITE_TESTCTRL_RESERVE                 14
5511 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
5512 #define SQLITE_TESTCTRL_ISKEYWORD               16
5513 #define SQLITE_TESTCTRL_LAST                    16
5514
5515 /*
5516 ** CAPI3REF: SQLite Runtime Status
5517 ** EXPERIMENTAL
5518 **
5519 ** ^This interface is used to retrieve runtime status information
5520 ** about the preformance of SQLite, and optionally to reset various
5521 ** highwater marks.  ^The first argument is an integer code for
5522 ** the specific parameter to measure.  ^(Recognized integer codes
5523 ** are of the form [SQLITE_STATUS_MEMORY_USED | SQLITE_STATUS_...].)^
5524 ** ^The current value of the parameter is returned into *pCurrent.
5525 ** ^The highest recorded value is returned in *pHighwater.  ^If the
5526 ** resetFlag is true, then the highest record value is reset after
5527 ** *pHighwater is written.  ^(Some parameters do not record the highest
5528 ** value.  For those parameters
5529 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
5530 ** ^(Other parameters record only the highwater mark and not the current
5531 ** value.  For these latter parameters nothing is written into *pCurrent.)^
5532 **
5533 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
5534 ** non-zero [error code] on failure.
5535 **
5536 ** This routine is threadsafe but is not atomic.  This routine can be
5537 ** called while other threads are running the same or different SQLite
5538 ** interfaces.  However the values returned in *pCurrent and
5539 ** *pHighwater reflect the status of SQLite at different points in time
5540 ** and it is possible that another thread might change the parameter
5541 ** in between the times when *pCurrent and *pHighwater are written.
5542 **
5543 ** See also: [sqlite3_db_status()]
5544 */
5545 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
5546
5547
5548 /*
5549 ** CAPI3REF: Status Parameters
5550 ** EXPERIMENTAL
5551 **
5552 ** These integer constants designate various run-time status parameters
5553 ** that can be returned by [sqlite3_status()].
5554 **
5555 ** <dl>
5556 ** ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
5557 ** <dd>This parameter is the current amount of memory checked out
5558 ** using [sqlite3_malloc()], either directly or indirectly.  The
5559 ** figure includes calls made to [sqlite3_malloc()] by the application
5560 ** and internal memory usage by the SQLite library.  Scratch memory
5561 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
5562 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
5563 ** this parameter.  The amount returned is the sum of the allocation
5564 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
5565 **
5566 ** ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
5567 ** <dd>This parameter records the largest memory allocation request
5568 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
5569 ** internal equivalents).  Only the value returned in the
5570 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
5571 ** The value written into the *pCurrent parameter is undefined.</dd>)^
5572 **
5573 ** ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
5574 ** <dd>This parameter returns the number of pages used out of the
5575 ** [pagecache memory allocator] that was configured using 
5576 ** [SQLITE_CONFIG_PAGECACHE].  The
5577 ** value returned is in pages, not in bytes.</dd>)^
5578 **
5579 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
5580 ** <dd>This parameter returns the number of bytes of page cache
5581 ** allocation which could not be statisfied by the [SQLITE_CONFIG_PAGECACHE]
5582 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
5583 ** returned value includes allocations that overflowed because they
5584 ** where too large (they were larger than the "sz" parameter to
5585 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
5586 ** no space was left in the page cache.</dd>)^
5587 **
5588 ** ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
5589 ** <dd>This parameter records the largest memory allocation request
5590 ** handed to [pagecache memory allocator].  Only the value returned in the
5591 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
5592 ** The value written into the *pCurrent parameter is undefined.</dd>)^
5593 **
5594 ** ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
5595 ** <dd>This parameter returns the number of allocations used out of the
5596 ** [scratch memory allocator] configured using
5597 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
5598 ** in bytes.  Since a single thread may only have one scratch allocation
5599 ** outstanding at time, this parameter also reports the number of threads
5600 ** using scratch memory at the same time.</dd>)^
5601 **
5602 ** ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
5603 ** <dd>This parameter returns the number of bytes of scratch memory
5604 ** allocation which could not be statisfied by the [SQLITE_CONFIG_SCRATCH]
5605 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
5606 ** returned include overflows because the requested allocation was too
5607 ** larger (that is, because the requested allocation was larger than the
5608 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
5609 ** slots were available.
5610 ** </dd>)^
5611 **
5612 ** ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
5613 ** <dd>This parameter records the largest memory allocation request
5614 ** handed to [scratch memory allocator].  Only the value returned in the
5615 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
5616 ** The value written into the *pCurrent parameter is undefined.</dd>)^
5617 **
5618 ** ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
5619 ** <dd>This parameter records the deepest parser stack.  It is only
5620 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
5621 ** </dl>
5622 **
5623 ** New status parameters may be added from time to time.
5624 */
5625 #define SQLITE_STATUS_MEMORY_USED          0
5626 #define SQLITE_STATUS_PAGECACHE_USED       1
5627 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
5628 #define SQLITE_STATUS_SCRATCH_USED         3
5629 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
5630 #define SQLITE_STATUS_MALLOC_SIZE          5
5631 #define SQLITE_STATUS_PARSER_STACK         6
5632 #define SQLITE_STATUS_PAGECACHE_SIZE       7
5633 #define SQLITE_STATUS_SCRATCH_SIZE         8
5634
5635 /*
5636 ** CAPI3REF: Database Connection Status
5637 ** EXPERIMENTAL
5638 **
5639 ** ^This interface is used to retrieve runtime status information 
5640 ** about a single [database connection].  ^The first argument is the
5641 ** database connection object to be interrogated.  ^The second argument
5642 ** is the parameter to interrogate.  ^Currently, the only allowed value
5643 ** for the second parameter is [SQLITE_DBSTATUS_LOOKASIDE_USED].
5644 ** Additional options will likely appear in future releases of SQLite.
5645 **
5646 ** ^The current value of the requested parameter is written into *pCur
5647 ** and the highest instantaneous value is written into *pHiwtr.  ^If
5648 ** the resetFlg is true, then the highest instantaneous value is
5649 ** reset back down to the current value.
5650 **
5651 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
5652 */
5653 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
5654
5655 /*
5656 ** CAPI3REF: Status Parameters for database connections
5657 ** EXPERIMENTAL
5658 **
5659 ** These constants are the available integer "verbs" that can be passed as
5660 ** the second argument to the [sqlite3_db_status()] interface.
5661 **
5662 ** New verbs may be added in future releases of SQLite. Existing verbs
5663 ** might be discontinued. Applications should check the return code from
5664 ** [sqlite3_db_status()] to make sure that the call worked.
5665 ** The [sqlite3_db_status()] interface will return a non-zero error code
5666 ** if a discontinued or unsupported verb is invoked.
5667 **
5668 ** <dl>
5669 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
5670 ** <dd>This parameter returns the number of lookaside memory slots currently
5671 ** checked out.</dd>)^
5672 ** </dl>
5673 */
5674 #define SQLITE_DBSTATUS_LOOKASIDE_USED     0
5675
5676
5677 /*
5678 ** CAPI3REF: Prepared Statement Status
5679 ** EXPERIMENTAL
5680 **
5681 ** ^(Each prepared statement maintains various
5682 ** [SQLITE_STMTSTATUS_SORT | counters] that measure the number
5683 ** of times it has performed specific operations.)^  These counters can
5684 ** be used to monitor the performance characteristics of the prepared
5685 ** statements.  For example, if the number of table steps greatly exceeds
5686 ** the number of table searches or result rows, that would tend to indicate
5687 ** that the prepared statement is using a full table scan rather than
5688 ** an index.  
5689 **
5690 ** ^(This interface is used to retrieve and reset counter values from
5691 ** a [prepared statement].  The first argument is the prepared statement
5692 ** object to be interrogated.  The second argument
5693 ** is an integer code for a specific [SQLITE_STMTSTATUS_SORT | counter]
5694 ** to be interrogated.)^
5695 ** ^The current value of the requested counter is returned.
5696 ** ^If the resetFlg is true, then the counter is reset to zero after this
5697 ** interface call returns.
5698 **
5699 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
5700 */
5701 SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
5702
5703 /*
5704 ** CAPI3REF: Status Parameters for prepared statements
5705 ** EXPERIMENTAL
5706 **
5707 ** These preprocessor macros define integer codes that name counter
5708 ** values associated with the [sqlite3_stmt_status()] interface.
5709 ** The meanings of the various counters are as follows:
5710 **
5711 ** <dl>
5712 ** <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
5713 ** <dd>^This is the number of times that SQLite has stepped forward in
5714 ** a table as part of a full table scan.  Large numbers for this counter
5715 ** may indicate opportunities for performance improvement through 
5716 ** careful use of indices.</dd>
5717 **
5718 ** <dt>SQLITE_STMTSTATUS_SORT</dt>
5719 ** <dd>^This is the number of sort operations that have occurred.
5720 ** A non-zero value in this counter may indicate an opportunity to
5721 ** improvement performance through careful use of indices.</dd>
5722 **
5723 ** </dl>
5724 */
5725 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
5726 #define SQLITE_STMTSTATUS_SORT              2
5727
5728 /*
5729 ** CAPI3REF: Custom Page Cache Object
5730 ** EXPERIMENTAL
5731 **
5732 ** The sqlite3_pcache type is opaque.  It is implemented by
5733 ** the pluggable module.  The SQLite core has no knowledge of
5734 ** its size or internal structure and never deals with the
5735 ** sqlite3_pcache object except by holding and passing pointers
5736 ** to the object.
5737 **
5738 ** See [sqlite3_pcache_methods] for additional information.
5739 */
5740 typedef struct sqlite3_pcache sqlite3_pcache;
5741
5742 /*
5743 ** CAPI3REF: Application Defined Page Cache.
5744 ** KEYWORDS: {page cache}
5745 ** EXPERIMENTAL
5746 **
5747 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE], ...) interface can
5748 ** register an alternative page cache implementation by passing in an 
5749 ** instance of the sqlite3_pcache_methods structure.)^ The majority of the 
5750 ** heap memory used by SQLite is used by the page cache to cache data read 
5751 ** from, or ready to be written to, the database file. By implementing a 
5752 ** custom page cache using this API, an application can control more 
5753 ** precisely the amount of memory consumed by SQLite, the way in which 
5754 ** that memory is allocated and released, and the policies used to 
5755 ** determine exactly which parts of a database file are cached and for 
5756 ** how long.
5757 **
5758 ** ^(The contents of the sqlite3_pcache_methods structure are copied to an
5759 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
5760 ** the application may discard the parameter after the call to
5761 ** [sqlite3_config()] returns.)^
5762 **
5763 ** ^The xInit() method is called once for each call to [sqlite3_initialize()]
5764 ** (usually only once during the lifetime of the process). ^(The xInit()
5765 ** method is passed a copy of the sqlite3_pcache_methods.pArg value.)^
5766 ** ^The xInit() method can set up up global structures and/or any mutexes
5767 ** required by the custom page cache implementation. 
5768 **
5769 ** ^The xShutdown() method is called from within [sqlite3_shutdown()], 
5770 ** if the application invokes this API. It can be used to clean up 
5771 ** any outstanding resources before process shutdown, if required.
5772 **
5773 ** ^SQLite holds a [SQLITE_MUTEX_RECURSIVE] mutex when it invokes
5774 ** the xInit method, so the xInit method need not be threadsafe.  ^The
5775 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
5776 ** not need to be threadsafe either.  All other methods must be threadsafe
5777 ** in multithreaded applications.
5778 **
5779 ** ^SQLite will never invoke xInit() more than once without an intervening
5780 ** call to xShutdown().
5781 **
5782 ** ^The xCreate() method is used to construct a new cache instance.  SQLite
5783 ** will typically create one cache instance for each open database file,
5784 ** though this is not guaranteed. ^The
5785 ** first parameter, szPage, is the size in bytes of the pages that must
5786 ** be allocated by the cache.  ^szPage will not be a power of two.  ^szPage
5787 ** will the page size of the database file that is to be cached plus an
5788 ** increment (here called "R") of about 100 or 200.  ^SQLite will use the
5789 ** extra R bytes on each page to store metadata about the underlying
5790 ** database page on disk.  The value of R depends
5791 ** on the SQLite version, the target platform, and how SQLite was compiled.
5792 ** ^R is constant for a particular build of SQLite.  ^The second argument to
5793 ** xCreate(), bPurgeable, is true if the cache being created will
5794 ** be used to cache database pages of a file stored on disk, or
5795 ** false if it is used for an in-memory database. ^The cache implementation
5796 ** does not have to do anything special based with the value of bPurgeable;
5797 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
5798 ** never invoke xUnpin() except to deliberately delete a page.
5799 ** ^In other words, a cache created with bPurgeable set to false will
5800 ** never contain any unpinned pages.
5801 **
5802 ** ^(The xCachesize() method may be called at any time by SQLite to set the
5803 ** suggested maximum cache-size (number of pages stored by) the cache
5804 ** instance passed as the first argument. This is the value configured using
5805 ** the SQLite "[PRAGMA cache_size]" command.)^  ^As with the bPurgeable
5806 ** parameter, the implementation is not required to do anything with this
5807 ** value; it is advisory only.
5808 **
5809 ** ^The xPagecount() method should return the number of pages currently
5810 ** stored in the cache.
5811 ** 
5812 ** ^The xFetch() method is used to fetch a page and return a pointer to it. 
5813 ** ^A 'page', in this context, is a buffer of szPage bytes aligned at an
5814 ** 8-byte boundary. ^The page to be fetched is determined by the key. ^The
5815 ** mimimum key value is 1. After it has been retrieved using xFetch, the page 
5816 ** is considered to be "pinned".
5817 **
5818 ** ^If the requested page is already in the page cache, then the page cache
5819 ** implementation must return a pointer to the page buffer with its content
5820 ** intact.  ^(If the requested page is not already in the cache, then the
5821 ** behavior of the cache implementation is determined by the value of the
5822 ** createFlag parameter passed to xFetch, according to the following table:
5823 **
5824 ** <table border=1 width=85% align=center>
5825 ** <tr><th> createFlag <th> Behaviour when page is not already in cache
5826 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
5827 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
5828 **                 Otherwise return NULL.
5829 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
5830 **                 NULL if allocating a new page is effectively impossible.
5831 ** </table>)^
5832 **
5833 ** SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  If
5834 ** a call to xFetch() with createFlag==1 returns NULL, then SQLite will
5835 ** attempt to unpin one or more cache pages by spilling the content of
5836 ** pinned pages to disk and synching the operating system disk cache. After
5837 ** attempting to unpin pages, the xFetch() method will be invoked again with
5838 ** a createFlag of 2.
5839 **
5840 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
5841 ** as its second argument. ^(If the third parameter, discard, is non-zero,
5842 ** then the page should be evicted from the cache. In this case SQLite 
5843 ** assumes that the next time the page is retrieved from the cache using
5844 ** the xFetch() method, it will be zeroed.)^ ^If the discard parameter is
5845 ** zero, then the page is considered to be unpinned. ^The cache implementation
5846 ** may choose to evict unpinned pages at any time.
5847 **
5848 ** ^(The cache is not required to perform any reference counting. A single 
5849 ** call to xUnpin() unpins the page regardless of the number of prior calls 
5850 ** to xFetch().)^
5851 **
5852 ** ^The xRekey() method is used to change the key value associated with the
5853 ** page passed as the second argument from oldKey to newKey. ^If the cache
5854 ** previously contains an entry associated with newKey, it should be
5855 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
5856 ** to be pinned.
5857 **
5858 ** ^When SQLite calls the xTruncate() method, the cache must discard all
5859 ** existing cache entries with page numbers (keys) greater than or equal
5860 ** to the value of the iLimit parameter passed to xTruncate(). ^If any
5861 ** of these pages are pinned, they are implicitly unpinned, meaning that
5862 ** they can be safely discarded.
5863 **
5864 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
5865 ** All resources associated with the specified cache should be freed. ^After
5866 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
5867 ** handle invalid, and will not use it with any other sqlite3_pcache_methods
5868 ** functions.
5869 */
5870 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
5871 struct sqlite3_pcache_methods {
5872   void *pArg;
5873   int (*xInit)(void*);
5874   void (*xShutdown)(void*);
5875   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
5876   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
5877   int (*xPagecount)(sqlite3_pcache*);
5878   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
5879   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
5880   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
5881   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
5882   void (*xDestroy)(sqlite3_pcache*);
5883 };
5884
5885 /*
5886 ** CAPI3REF: Online Backup Object
5887 ** EXPERIMENTAL
5888 **
5889 ** The sqlite3_backup object records state information about an ongoing
5890 ** online backup operation.  ^The sqlite3_backup object is created by
5891 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
5892 ** [sqlite3_backup_finish()].
5893 **
5894 ** See Also: [Using the SQLite Online Backup API]
5895 */
5896 typedef struct sqlite3_backup sqlite3_backup;
5897
5898 /*
5899 ** CAPI3REF: Online Backup API.
5900 ** EXPERIMENTAL
5901 **
5902 ** The backup API copies the content of one database into another.
5903 ** It is useful either for creating backups of databases or
5904 ** for copying in-memory databases to or from persistent files. 
5905 **
5906 ** See Also: [Using the SQLite Online Backup API]
5907 **
5908 ** ^Exclusive access is required to the destination database for the 
5909 ** duration of the operation. ^However the source database is only
5910 ** read-locked while it is actually being read; it is not locked
5911 ** continuously for the entire backup operation. ^Thus, the backup may be
5912 ** performed on a live source database without preventing other users from
5913 ** reading or writing to the source database while the backup is underway.
5914 ** 
5915 ** ^(To perform a backup operation: 
5916 **   <ol>
5917 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
5918 **         backup, 
5919 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
5920 **         the data between the two databases, and finally
5921 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
5922 **         associated with the backup operation. 
5923 **   </ol>)^
5924 ** There should be exactly one call to sqlite3_backup_finish() for each
5925 ** successful call to sqlite3_backup_init().
5926 **
5927 ** <b>sqlite3_backup_init()</b>
5928 **
5929 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the 
5930 ** [database connection] associated with the destination database 
5931 ** and the database name, respectively.
5932 ** ^The database name is "main" for the main database, "temp" for the
5933 ** temporary database, or the name specified after the AS keyword in
5934 ** an [ATTACH] statement for an attached database.
5935 ** ^The S and M arguments passed to 
5936 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
5937 ** and database name of the source database, respectively.
5938 ** ^The source and destination [database connections] (parameters S and D)
5939 ** must be different or else sqlite3_backup_init(D,N,S,M) will file with
5940 ** an error.
5941 **
5942 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
5943 ** returned and an error code and error message are store3d in the
5944 ** destination [database connection] D.
5945 ** ^The error code and message for the failed call to sqlite3_backup_init()
5946 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
5947 ** [sqlite3_errmsg16()] functions.
5948 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
5949 ** [sqlite3_backup] object.
5950 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
5951 ** sqlite3_backup_finish() functions to perform the specified backup 
5952 ** operation.
5953 **
5954 ** <b>sqlite3_backup_step()</b>
5955 **
5956 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between 
5957 ** the source and destination databases specified by [sqlite3_backup] object B.
5958 ** ^If N is negative, all remaining source pages are copied. 
5959 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
5960 ** are still more pages to be copied, then the function resturns [SQLITE_OK].
5961 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
5962 ** from source to destination, then it returns [SQLITE_DONE].
5963 ** ^If an error occurs while running sqlite3_backup_step(B,N),
5964 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
5965 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
5966 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
5967 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
5968 **
5969 ** ^The sqlite3_backup_step() might return [SQLITE_READONLY] if the destination
5970 ** database was opened read-only or if
5971 ** the destination is an in-memory database with a different page size
5972 ** from the source database.
5973 **
5974 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
5975 ** the [sqlite3_busy_handler | busy-handler function]
5976 ** is invoked (if one is specified). ^If the 
5977 ** busy-handler returns non-zero before the lock is available, then 
5978 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
5979 ** sqlite3_backup_step() can be retried later. ^If the source
5980 ** [database connection]
5981 ** is being used to write to the source database when sqlite3_backup_step()
5982 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
5983 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
5984 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
5985 ** [SQLITE_READONLY] is returned, then 
5986 ** there is no point in retrying the call to sqlite3_backup_step(). These 
5987 ** errors are considered fatal.)^  The application must accept 
5988 ** that the backup operation has failed and pass the backup operation handle 
5989 ** to the sqlite3_backup_finish() to release associated resources.
5990 **
5991 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
5992 ** on the destination file. ^The exclusive lock is not released until either 
5993 ** sqlite3_backup_finish() is called or the backup operation is complete 
5994 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
5995 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
5996 ** lasts for the duration of the sqlite3_backup_step() call.
5997 ** ^Because the source database is not locked between calls to
5998 ** sqlite3_backup_step(), the source database may be modified mid-way
5999 ** through the backup process.  ^If the source database is modified by an
6000 ** external process or via a database connection other than the one being
6001 ** used by the backup operation, then the backup will be automatically
6002 ** restarted by the next call to sqlite3_backup_step(). ^If the source 
6003 ** database is modified by the using the same database connection as is used
6004 ** by the backup operation, then the backup database is automatically
6005 ** updated at the same time.
6006 **
6007 ** <b>sqlite3_backup_finish()</b>
6008 **
6009 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
6010 ** application wishes to abandon the backup operation, the application
6011 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
6012 ** ^The sqlite3_backup_finish() interfaces releases all
6013 ** resources associated with the [sqlite3_backup] object. 
6014 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
6015 ** active write-transaction on the destination database is rolled back.
6016 ** The [sqlite3_backup] object is invalid
6017 ** and may not be used following a call to sqlite3_backup_finish().
6018 **
6019 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
6020 ** sqlite3_backup_step() errors occurred, regardless or whether or not
6021 ** sqlite3_backup_step() completed.
6022 ** ^If an out-of-memory condition or IO error occurred during any prior
6023 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
6024 ** sqlite3_backup_finish() returns the corresponding [error code].
6025 **
6026 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
6027 ** is not a permanent error and does not affect the return value of
6028 ** sqlite3_backup_finish().
6029 **
6030 ** <b>sqlite3_backup_remaining(), sqlite3_backup_pagecount()</b>
6031 **
6032 ** ^Each call to sqlite3_backup_step() sets two values inside
6033 ** the [sqlite3_backup] object: the number of pages still to be backed
6034 ** up and the total number of pages in the source databae file.
6035 ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
6036 ** retrieve these two values, respectively.
6037 **
6038 ** ^The values returned by these functions are only updated by
6039 ** sqlite3_backup_step(). ^If the source database is modified during a backup
6040 ** operation, then the values are not updated to account for any extra
6041 ** pages that need to be updated or the size of the source database file
6042 ** changing.
6043 **
6044 ** <b>Concurrent Usage of Database Handles</b>
6045 **
6046 ** ^The source [database connection] may be used by the application for other
6047 ** purposes while a backup operation is underway or being initialized.
6048 ** ^If SQLite is compiled and configured to support threadsafe database
6049 ** connections, then the source database connection may be used concurrently
6050 ** from within other threads.
6051 **
6052 ** However, the application must guarantee that the destination 
6053 ** [database connection] is not passed to any other API (by any thread) after 
6054 ** sqlite3_backup_init() is called and before the corresponding call to
6055 ** sqlite3_backup_finish().  SQLite does not currently check to see
6056 ** if the application incorrectly accesses the destination [database connection]
6057 ** and so no error code is reported, but the operations may malfunction
6058 ** nevertheless.  Use of the destination database connection while a
6059 ** backup is in progress might also also cause a mutex deadlock.
6060 **
6061 ** If running in [shared cache mode], the application must
6062 ** guarantee that the shared cache used by the destination database
6063 ** is not accessed while the backup is running. In practice this means
6064 ** that the application must guarantee that the disk file being 
6065 ** backed up to is not accessed by any connection within the process,
6066 ** not just the specific connection that was passed to sqlite3_backup_init().
6067 **
6068 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
6069 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
6070 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
6071 ** APIs are not strictly speaking threadsafe. If they are invoked at the
6072 ** same time as another thread is invoking sqlite3_backup_step() it is
6073 ** possible that they return invalid values.
6074 */
6075 SQLITE_API sqlite3_backup *sqlite3_backup_init(
6076   sqlite3 *pDest,                        /* Destination database handle */
6077   const char *zDestName,                 /* Destination database name */
6078   sqlite3 *pSource,                      /* Source database handle */
6079   const char *zSourceName                /* Source database name */
6080 );
6081 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
6082 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
6083 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
6084 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
6085
6086 /*
6087 ** CAPI3REF: Unlock Notification
6088 ** EXPERIMENTAL
6089 **
6090 ** ^When running in shared-cache mode, a database operation may fail with
6091 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
6092 ** individual tables within the shared-cache cannot be obtained. See
6093 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
6094 ** ^This API may be used to register a callback that SQLite will invoke 
6095 ** when the connection currently holding the required lock relinquishes it.
6096 ** ^This API is only available if the library was compiled with the
6097 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
6098 **
6099 ** See Also: [Using the SQLite Unlock Notification Feature].
6100 **
6101 ** ^Shared-cache locks are released when a database connection concludes
6102 ** its current transaction, either by committing it or rolling it back. 
6103 **
6104 ** ^When a connection (known as the blocked connection) fails to obtain a
6105 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
6106 ** identity of the database connection (the blocking connection) that
6107 ** has locked the required resource is stored internally. ^After an 
6108 ** application receives an SQLITE_LOCKED error, it may call the
6109 ** sqlite3_unlock_notify() method with the blocked connection handle as 
6110 ** the first argument to register for a callback that will be invoked
6111 ** when the blocking connections current transaction is concluded. ^The
6112 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
6113 ** call that concludes the blocking connections transaction.
6114 **
6115 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
6116 ** there is a chance that the blocking connection will have already
6117 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
6118 ** If this happens, then the specified callback is invoked immediately,
6119 ** from within the call to sqlite3_unlock_notify().)^
6120 **
6121 ** ^If the blocked connection is attempting to obtain a write-lock on a
6122 ** shared-cache table, and more than one other connection currently holds
6123 ** a read-lock on the same table, then SQLite arbitrarily selects one of 
6124 ** the other connections to use as the blocking connection.
6125 **
6126 ** ^(There may be at most one unlock-notify callback registered by a 
6127 ** blocked connection. If sqlite3_unlock_notify() is called when the
6128 ** blocked connection already has a registered unlock-notify callback,
6129 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
6130 ** called with a NULL pointer as its second argument, then any existing
6131 ** unlock-notify callback is cancelled. ^The blocked connections 
6132 ** unlock-notify callback may also be canceled by closing the blocked
6133 ** connection using [sqlite3_close()].
6134 **
6135 ** The unlock-notify callback is not reentrant. If an application invokes
6136 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
6137 ** crash or deadlock may be the result.
6138 **
6139 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
6140 ** returns SQLITE_OK.
6141 **
6142 ** <b>Callback Invocation Details</b>
6143 **
6144 ** When an unlock-notify callback is registered, the application provides a 
6145 ** single void* pointer that is passed to the callback when it is invoked.
6146 ** However, the signature of the callback function allows SQLite to pass
6147 ** it an array of void* context pointers. The first argument passed to
6148 ** an unlock-notify callback is a pointer to an array of void* pointers,
6149 ** and the second is the number of entries in the array.
6150 **
6151 ** When a blocking connections transaction is concluded, there may be
6152 ** more than one blocked connection that has registered for an unlock-notify
6153 ** callback. ^If two or more such blocked connections have specified the
6154 ** same callback function, then instead of invoking the callback function
6155 ** multiple times, it is invoked once with the set of void* context pointers
6156 ** specified by the blocked connections bundled together into an array.
6157 ** This gives the application an opportunity to prioritize any actions 
6158 ** related to the set of unblocked database connections.
6159 **
6160 ** <b>Deadlock Detection</b>
6161 **
6162 ** Assuming that after registering for an unlock-notify callback a 
6163 ** database waits for the callback to be issued before taking any further
6164 ** action (a reasonable assumption), then using this API may cause the
6165 ** application to deadlock. For example, if connection X is waiting for
6166 ** connection Y's transaction to be concluded, and similarly connection
6167 ** Y is waiting on connection X's transaction, then neither connection
6168 ** will proceed and the system may remain deadlocked indefinitely.
6169 **
6170 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
6171 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
6172 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
6173 ** unlock-notify callback is registered. The system is said to be in
6174 ** a deadlocked state if connection A has registered for an unlock-notify
6175 ** callback on the conclusion of connection B's transaction, and connection
6176 ** B has itself registered for an unlock-notify callback when connection
6177 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
6178 ** the system is also considered to be deadlocked if connection B has
6179 ** registered for an unlock-notify callback on the conclusion of connection
6180 ** C's transaction, where connection C is waiting on connection A. ^Any
6181 ** number of levels of indirection are allowed.
6182 **
6183 ** <b>The "DROP TABLE" Exception</b>
6184 **
6185 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
6186 ** always appropriate to call sqlite3_unlock_notify(). There is however,
6187 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
6188 ** SQLite checks if there are any currently executing SELECT statements
6189 ** that belong to the same connection. If there are, SQLITE_LOCKED is
6190 ** returned. In this case there is no "blocking connection", so invoking
6191 ** sqlite3_unlock_notify() results in the unlock-notify callback being
6192 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
6193 ** or "DROP INDEX" query, an infinite loop might be the result.
6194 **
6195 ** One way around this problem is to check the extended error code returned
6196 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
6197 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
6198 ** the special "DROP TABLE/INDEX" case, the extended error code is just 
6199 ** SQLITE_LOCKED.)^
6200 */
6201 SQLITE_API int sqlite3_unlock_notify(
6202   sqlite3 *pBlocked,                          /* Waiting connection */
6203   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
6204   void *pNotifyArg                            /* Argument to pass to xNotify */
6205 );
6206
6207
6208 /*
6209 ** CAPI3REF: String Comparison
6210 ** EXPERIMENTAL
6211 **
6212 ** ^The [sqlite3_strnicmp()] API allows applications and extensions to
6213 ** compare the contents of two buffers containing UTF-8 strings in a
6214 ** case-indendent fashion, using the same definition of case independence 
6215 ** that SQLite uses internally when comparing identifiers.
6216 */
6217 SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
6218
6219 /*
6220 ** CAPI3REF: Error Logging Interface
6221 ** EXPERIMENTAL
6222 **
6223 ** ^The [sqlite3_log()] interface writes a message into the error log
6224 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
6225 ** ^If logging is enabled, the zFormat string and subsequent arguments are
6226 ** passed through to [sqlite3_vmprintf()] to generate the final output string.
6227 **
6228 ** The sqlite3_log() interface is intended for use by extensions such as
6229 ** virtual tables, collating functions, and SQL functions.  While there is
6230 ** nothing to prevent an application from calling sqlite3_log(), doing so
6231 ** is considered bad form.
6232 **
6233 ** The zFormat string must not be NULL.
6234 **
6235 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
6236 ** will not use dynamically allocated memory.  The log message is stored in
6237 ** a fixed-length buffer on the stack.  If the log message is longer than
6238 ** a few hundred characters, it will be truncated to the length of the
6239 ** buffer.
6240 */
6241 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
6242
6243 /*
6244 ** Undo the hack that converts floating point types to integer for
6245 ** builds on processors without floating point support.
6246 */
6247 #ifdef SQLITE_OMIT_FLOATING_POINT
6248 # undef double
6249 #endif
6250
6251 #if 0
6252 }  /* End of the 'extern "C"' block */
6253 #endif
6254 #endif
6255
6256
6257 /************** End of sqlite3.h *********************************************/
6258 /************** Continuing where we left off in sqliteInt.h ******************/
6259 /************** Include hash.h in the middle of sqliteInt.h ******************/
6260 /************** Begin file hash.h ********************************************/
6261 /*
6262 ** 2001 September 22
6263 **
6264 ** The author disclaims copyright to this source code.  In place of
6265 ** a legal notice, here is a blessing:
6266 **
6267 **    May you do good and not evil.
6268 **    May you find forgiveness for yourself and forgive others.
6269 **    May you share freely, never taking more than you give.
6270 **
6271 *************************************************************************
6272 ** This is the header file for the generic hash-table implemenation
6273 ** used in SQLite.
6274 */
6275 #ifndef _SQLITE_HASH_H_
6276 #define _SQLITE_HASH_H_
6277
6278 /* Forward declarations of structures. */
6279 typedef struct Hash Hash;
6280 typedef struct HashElem HashElem;
6281
6282 /* A complete hash table is an instance of the following structure.
6283 ** The internals of this structure are intended to be opaque -- client
6284 ** code should not attempt to access or modify the fields of this structure
6285 ** directly.  Change this structure only by using the routines below.
6286 ** However, some of the "procedures" and "functions" for modifying and
6287 ** accessing this structure are really macros, so we can't really make
6288 ** this structure opaque.
6289 **
6290 ** All elements of the hash table are on a single doubly-linked list.
6291 ** Hash.first points to the head of this list.
6292 **
6293 ** There are Hash.htsize buckets.  Each bucket points to a spot in
6294 ** the global doubly-linked list.  The contents of the bucket are the
6295 ** element pointed to plus the next _ht.count-1 elements in the list.
6296 **
6297 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
6298 ** by a linear search of the global list.  For small tables, the 
6299 ** Hash.ht table is never allocated because if there are few elements
6300 ** in the table, it is faster to do a linear search than to manage
6301 ** the hash table.
6302 */
6303 struct Hash {
6304   unsigned int htsize;      /* Number of buckets in the hash table */
6305   unsigned int count;       /* Number of entries in this table */
6306   HashElem *first;          /* The first element of the array */
6307   struct _ht {              /* the hash table */
6308     int count;                 /* Number of entries with this hash */
6309     HashElem *chain;           /* Pointer to first entry with this hash */
6310   } *ht;
6311 };
6312
6313 /* Each element in the hash table is an instance of the following 
6314 ** structure.  All elements are stored on a single doubly-linked list.
6315 **
6316 ** Again, this structure is intended to be opaque, but it can't really
6317 ** be opaque because it is used by macros.
6318 */
6319 struct HashElem {
6320   HashElem *next, *prev;       /* Next and previous elements in the table */
6321   void *data;                  /* Data associated with this element */
6322   const char *pKey; int nKey;  /* Key associated with this element */
6323 };
6324
6325 /*
6326 ** Access routines.  To delete, insert a NULL pointer.
6327 */
6328 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
6329 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, int nKey, void *pData);
6330 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey, int nKey);
6331 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
6332
6333 /*
6334 ** Macros for looping over all elements of a hash table.  The idiom is
6335 ** like this:
6336 **
6337 **   Hash h;
6338 **   HashElem *p;
6339 **   ...
6340 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
6341 **     SomeStructure *pData = sqliteHashData(p);
6342 **     // do something with pData
6343 **   }
6344 */
6345 #define sqliteHashFirst(H)  ((H)->first)
6346 #define sqliteHashNext(E)   ((E)->next)
6347 #define sqliteHashData(E)   ((E)->data)
6348 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
6349 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
6350
6351 /*
6352 ** Number of entries in a hash table
6353 */
6354 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
6355
6356 #endif /* _SQLITE_HASH_H_ */
6357
6358 /************** End of hash.h ************************************************/
6359 /************** Continuing where we left off in sqliteInt.h ******************/
6360 /************** Include parse.h in the middle of sqliteInt.h *****************/
6361 /************** Begin file parse.h *******************************************/
6362 #define TK_SEMI                            1
6363 #define TK_EXPLAIN                         2
6364 #define TK_QUERY                           3
6365 #define TK_PLAN                            4
6366 #define TK_BEGIN                           5
6367 #define TK_TRANSACTION                     6
6368 #define TK_DEFERRED                        7
6369 #define TK_IMMEDIATE                       8
6370 #define TK_EXCLUSIVE                       9
6371 #define TK_COMMIT                         10
6372 #define TK_END                            11
6373 #define TK_ROLLBACK                       12
6374 #define TK_SAVEPOINT                      13
6375 #define TK_RELEASE                        14
6376 #define TK_TO                             15
6377 #define TK_TABLE                          16
6378 #define TK_CREATE                         17
6379 #define TK_IF                             18
6380 #define TK_NOT                            19
6381 #define TK_EXISTS                         20
6382 #define TK_TEMP                           21
6383 #define TK_LP                             22
6384 #define TK_RP                             23
6385 #define TK_AS                             24
6386 #define TK_COMMA                          25
6387 #define TK_ID                             26
6388 #define TK_INDEXED                        27
6389 #define TK_ABORT                          28
6390 #define TK_ACTION                         29
6391 #define TK_AFTER                          30
6392 #define TK_ANALYZE                        31
6393 #define TK_ASC                            32
6394 #define TK_ATTACH                         33
6395 #define TK_BEFORE                         34
6396 #define TK_BY                             35
6397 #define TK_CASCADE                        36
6398 #define TK_CAST                           37
6399 #define TK_COLUMNKW                       38
6400 #define TK_CONFLICT                       39
6401 #define TK_DATABASE                       40
6402 #define TK_DESC                           41
6403 #define TK_DETACH                         42
6404 #define TK_EACH                           43
6405 #define TK_FAIL                           44
6406 #define TK_FOR                            45
6407 #define TK_IGNORE                         46
6408 #define TK_INITIALLY                      47
6409 #define TK_INSTEAD                        48
6410 #define TK_LIKE_KW                        49
6411 #define TK_MATCH                          50
6412 #define TK_NO                             51
6413 #define TK_KEY                            52
6414 #define TK_OF                             53
6415 #define TK_OFFSET                         54
6416 #define TK_PRAGMA                         55
6417 #define TK_RAISE                          56
6418 #define TK_REPLACE                        57
6419 #define TK_RESTRICT                       58
6420 #define TK_ROW                            59
6421 #define TK_TRIGGER                        60
6422 #define TK_VACUUM                         61
6423 #define TK_VIEW                           62
6424 #define TK_VIRTUAL                        63
6425 #define TK_REINDEX                        64
6426 #define TK_RENAME                         65
6427 #define TK_CTIME_KW                       66
6428 #define TK_ANY                            67
6429 #define TK_OR                             68
6430 #define TK_AND                            69
6431 #define TK_IS                             70
6432 #define TK_BETWEEN                        71
6433 #define TK_IN                             72
6434 #define TK_ISNULL                         73
6435 #define TK_NOTNULL                        74
6436 #define TK_NE                             75
6437 #define TK_EQ                             76
6438 #define TK_GT                             77
6439 #define TK_LE                             78
6440 #define TK_LT                             79
6441 #define TK_GE                             80
6442 #define TK_ESCAPE                         81
6443 #define TK_BITAND                         82
6444 #define TK_BITOR                          83
6445 #define TK_LSHIFT                         84
6446 #define TK_RSHIFT                         85
6447 #define TK_PLUS                           86
6448 #define TK_MINUS                          87
6449 #define TK_STAR                           88
6450 #define TK_SLASH                          89
6451 #define TK_REM                            90
6452 #define TK_CONCAT                         91
6453 #define TK_COLLATE                        92
6454 #define TK_BITNOT                         93
6455 #define TK_STRING                         94
6456 #define TK_JOIN_KW                        95
6457 #define TK_CONSTRAINT                     96
6458 #define TK_DEFAULT                        97
6459 #define TK_NULL                           98
6460 #define TK_PRIMARY                        99
6461 #define TK_UNIQUE                         100
6462 #define TK_CHECK                          101
6463 #define TK_REFERENCES                     102
6464 #define TK_AUTOINCR                       103
6465 #define TK_ON                             104
6466 #define TK_INSERT                         105
6467 #define TK_DELETE                         106
6468 #define TK_UPDATE                         107
6469 #define TK_SET                            108
6470 #define TK_DEFERRABLE                     109
6471 #define TK_FOREIGN                        110
6472 #define TK_DROP                           111
6473 #define TK_UNION                          112
6474 #define TK_ALL                            113
6475 #define TK_EXCEPT                         114
6476 #define TK_INTERSECT                      115
6477 #define TK_SELECT                         116
6478 #define TK_DISTINCT                       117
6479 #define TK_DOT                            118
6480 #define TK_FROM                           119
6481 #define TK_JOIN                           120
6482 #define TK_USING                          121
6483 #define TK_ORDER                          122
6484 #define TK_GROUP                          123
6485 #define TK_HAVING                         124
6486 #define TK_LIMIT                          125
6487 #define TK_WHERE                          126
6488 #define TK_INTO                           127
6489 #define TK_VALUES                         128
6490 #define TK_INTEGER                        129
6491 #define TK_FLOAT                          130
6492 #define TK_BLOB                           131
6493 #define TK_REGISTER                       132
6494 #define TK_VARIABLE                       133
6495 #define TK_CASE                           134
6496 #define TK_WHEN                           135
6497 #define TK_THEN                           136
6498 #define TK_ELSE                           137
6499 #define TK_INDEX                          138
6500 #define TK_ALTER                          139
6501 #define TK_ADD                            140
6502 #define TK_TO_TEXT                        141
6503 #define TK_TO_BLOB                        142
6504 #define TK_TO_NUMERIC                     143
6505 #define TK_TO_INT                         144
6506 #define TK_TO_REAL                        145
6507 #define TK_ISNOT                          146
6508 #define TK_END_OF_FILE                    147
6509 #define TK_ILLEGAL                        148
6510 #define TK_SPACE                          149
6511 #define TK_UNCLOSED_STRING                150
6512 #define TK_FUNCTION                       151
6513 #define TK_COLUMN                         152
6514 #define TK_AGG_FUNCTION                   153
6515 #define TK_AGG_COLUMN                     154
6516 #define TK_CONST_FUNC                     155
6517 #define TK_UMINUS                         156
6518 #define TK_UPLUS                          157
6519
6520 /************** End of parse.h ***********************************************/
6521 /************** Continuing where we left off in sqliteInt.h ******************/
6522 #include <stdio.h>
6523 #include <stdlib.h>
6524 #include <string.h>
6525 #include <assert.h>
6526 #include <stddef.h>
6527
6528 /*
6529 ** If compiling for a processor that lacks floating point support,
6530 ** substitute integer for floating-point
6531 */
6532 #ifdef SQLITE_OMIT_FLOATING_POINT
6533 # define double sqlite_int64
6534 # define LONGDOUBLE_TYPE sqlite_int64
6535 # ifndef SQLITE_BIG_DBL
6536 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
6537 # endif
6538 # define SQLITE_OMIT_DATETIME_FUNCS 1
6539 # define SQLITE_OMIT_TRACE 1
6540 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
6541 # undef SQLITE_HAVE_ISNAN
6542 #endif
6543 #ifndef SQLITE_BIG_DBL
6544 # define SQLITE_BIG_DBL (1e99)
6545 #endif
6546
6547 /*
6548 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
6549 ** afterward. Having this macro allows us to cause the C compiler 
6550 ** to omit code used by TEMP tables without messy #ifndef statements.
6551 */
6552 #ifdef SQLITE_OMIT_TEMPDB
6553 #define OMIT_TEMPDB 1
6554 #else
6555 #define OMIT_TEMPDB 0
6556 #endif
6557
6558 /*
6559 ** The "file format" number is an integer that is incremented whenever
6560 ** the VDBE-level file format changes.  The following macros define the
6561 ** the default file format for new databases and the maximum file format
6562 ** that the library can read.
6563 */
6564 #define SQLITE_MAX_FILE_FORMAT 4
6565 #ifndef SQLITE_DEFAULT_FILE_FORMAT
6566 # define SQLITE_DEFAULT_FILE_FORMAT 1
6567 #endif
6568
6569 /*
6570 ** Determine whether triggers are recursive by default.  This can be
6571 ** changed at run-time using a pragma.
6572 */
6573 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
6574 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
6575 #endif
6576
6577 /*
6578 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
6579 ** on the command-line
6580 */
6581 #ifndef SQLITE_TEMP_STORE
6582 # define SQLITE_TEMP_STORE 1
6583 #endif
6584
6585 /*
6586 ** GCC does not define the offsetof() macro so we'll have to do it
6587 ** ourselves.
6588 */
6589 #ifndef offsetof
6590 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
6591 #endif
6592
6593 /*
6594 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
6595 ** not, there are still machines out there that use EBCDIC.)
6596 */
6597 #if 'A' == '\301'
6598 # define SQLITE_EBCDIC 1
6599 #else
6600 # define SQLITE_ASCII 1
6601 #endif
6602
6603 /*
6604 ** Integers of known sizes.  These typedefs might change for architectures
6605 ** where the sizes very.  Preprocessor macros are available so that the
6606 ** types can be conveniently redefined at compile-type.  Like this:
6607 **
6608 **         cc '-DUINTPTR_TYPE=long long int' ...
6609 */
6610 #ifndef UINT32_TYPE
6611 # ifdef HAVE_UINT32_T
6612 #  define UINT32_TYPE uint32_t
6613 # else
6614 #  define UINT32_TYPE unsigned int
6615 # endif
6616 #endif
6617 #ifndef UINT16_TYPE
6618 # ifdef HAVE_UINT16_T
6619 #  define UINT16_TYPE uint16_t
6620 # else
6621 #  define UINT16_TYPE unsigned short int
6622 # endif
6623 #endif
6624 #ifndef INT16_TYPE
6625 # ifdef HAVE_INT16_T
6626 #  define INT16_TYPE int16_t
6627 # else
6628 #  define INT16_TYPE short int
6629 # endif
6630 #endif
6631 #ifndef UINT8_TYPE
6632 # ifdef HAVE_UINT8_T
6633 #  define UINT8_TYPE uint8_t
6634 # else
6635 #  define UINT8_TYPE unsigned char
6636 # endif
6637 #endif
6638 #ifndef INT8_TYPE
6639 # ifdef HAVE_INT8_T
6640 #  define INT8_TYPE int8_t
6641 # else
6642 #  define INT8_TYPE signed char
6643 # endif
6644 #endif
6645 #ifndef LONGDOUBLE_TYPE
6646 # define LONGDOUBLE_TYPE long double
6647 #endif
6648 typedef sqlite_int64 i64;          /* 8-byte signed integer */
6649 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
6650 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
6651 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
6652 typedef INT16_TYPE i16;            /* 2-byte signed integer */
6653 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
6654 typedef INT8_TYPE i8;              /* 1-byte signed integer */
6655
6656 /*
6657 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
6658 ** that can be stored in a u32 without loss of data.  The value
6659 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
6660 ** have to specify the value in the less intuitive manner shown:
6661 */
6662 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
6663
6664 /*
6665 ** Macros to determine whether the machine is big or little endian,
6666 ** evaluated at runtime.
6667 */
6668 #ifdef SQLITE_AMALGAMATION
6669 SQLITE_PRIVATE const int sqlite3one = 1;
6670 #else
6671 SQLITE_PRIVATE const int sqlite3one;
6672 #endif
6673 #if defined(i386) || defined(__i386__) || defined(_M_IX86)\
6674                              || defined(__x86_64) || defined(__x86_64__)
6675 # define SQLITE_BIGENDIAN    0
6676 # define SQLITE_LITTLEENDIAN 1
6677 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
6678 #else
6679 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
6680 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
6681 # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
6682 #endif
6683
6684 /*
6685 ** Constants for the largest and smallest possible 64-bit signed integers.
6686 ** These macros are designed to work correctly on both 32-bit and 64-bit
6687 ** compilers.
6688 */
6689 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
6690 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
6691
6692 /* 
6693 ** Round up a number to the next larger multiple of 8.  This is used
6694 ** to force 8-byte alignment on 64-bit architectures.
6695 */
6696 #define ROUND8(x)     (((x)+7)&~7)
6697
6698 /*
6699 ** Round down to the nearest multiple of 8
6700 */
6701 #define ROUNDDOWN8(x) ((x)&~7)
6702
6703 /*
6704 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
6705 ** macro is used only within assert() to verify that the code gets
6706 ** all alignment restrictions correct.
6707 **
6708 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
6709 ** underlying malloc() implemention might return us 4-byte aligned
6710 ** pointers.  In that case, only verify 4-byte alignment.
6711 */
6712 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
6713 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
6714 #else
6715 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
6716 #endif
6717
6718
6719 /*
6720 ** An instance of the following structure is used to store the busy-handler
6721 ** callback for a given sqlite handle. 
6722 **
6723 ** The sqlite.busyHandler member of the sqlite struct contains the busy
6724 ** callback for the database handle. Each pager opened via the sqlite
6725 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
6726 ** callback is currently invoked only from within pager.c.
6727 */
6728 typedef struct BusyHandler BusyHandler;
6729 struct BusyHandler {
6730   int (*xFunc)(void *,int);  /* The busy callback */
6731   void *pArg;                /* First arg to busy callback */
6732   int nBusy;                 /* Incremented with each busy call */
6733 };
6734
6735 /*
6736 ** Name of the master database table.  The master database table
6737 ** is a special table that holds the names and attributes of all
6738 ** user tables and indices.
6739 */
6740 #define MASTER_NAME       "sqlite_master"
6741 #define TEMP_MASTER_NAME  "sqlite_temp_master"
6742
6743 /*
6744 ** The root-page of the master database table.
6745 */
6746 #define MASTER_ROOT       1
6747
6748 /*
6749 ** The name of the schema table.
6750 */
6751 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
6752
6753 /*
6754 ** A convenience macro that returns the number of elements in
6755 ** an array.
6756 */
6757 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
6758
6759 /*
6760 ** The following value as a destructor means to use sqlite3DbFree().
6761 ** This is an internal extension to SQLITE_STATIC and SQLITE_TRANSIENT.
6762 */
6763 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3DbFree)
6764
6765 /*
6766 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
6767 ** not support Writable Static Data (WSD) such as global and static variables.
6768 ** All variables must either be on the stack or dynamically allocated from
6769 ** the heap.  When WSD is unsupported, the variable declarations scattered
6770 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
6771 ** macro is used for this purpose.  And instead of referencing the variable
6772 ** directly, we use its constant as a key to lookup the run-time allocated
6773 ** buffer that holds real variable.  The constant is also the initializer
6774 ** for the run-time allocated buffer.
6775 **
6776 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
6777 ** macros become no-ops and have zero performance impact.
6778 */
6779 #ifdef SQLITE_OMIT_WSD
6780   #define SQLITE_WSD const
6781   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
6782   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
6783 SQLITE_API   int sqlite3_wsd_init(int N, int J);
6784 SQLITE_API   void *sqlite3_wsd_find(void *K, int L);
6785 #else
6786   #define SQLITE_WSD 
6787   #define GLOBAL(t,v) v
6788   #define sqlite3GlobalConfig sqlite3Config
6789 #endif
6790
6791 /*
6792 ** The following macros are used to suppress compiler warnings and to
6793 ** make it clear to human readers when a function parameter is deliberately 
6794 ** left unused within the body of a function. This usually happens when
6795 ** a function is called via a function pointer. For example the 
6796 ** implementation of an SQL aggregate step callback may not use the
6797 ** parameter indicating the number of arguments passed to the aggregate,
6798 ** if it knows that this is enforced elsewhere.
6799 **
6800 ** When a function parameter is not used at all within the body of a function,
6801 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
6802 ** However, these macros may also be used to suppress warnings related to
6803 ** parameters that may or may not be used depending on compilation options.
6804 ** For example those parameters only used in assert() statements. In these
6805 ** cases the parameters are named as per the usual conventions.
6806 */
6807 #define UNUSED_PARAMETER(x) (void)(x)
6808 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
6809
6810 /*
6811 ** Forward references to structures
6812 */
6813 typedef struct AggInfo AggInfo;
6814 typedef struct AuthContext AuthContext;
6815 typedef struct AutoincInfo AutoincInfo;
6816 typedef struct Bitvec Bitvec;
6817 typedef struct CollSeq CollSeq;
6818 typedef struct Column Column;
6819 typedef struct Db Db;
6820 typedef struct Schema Schema;
6821 typedef struct Expr Expr;
6822 typedef struct ExprList ExprList;
6823 typedef struct ExprSpan ExprSpan;
6824 typedef struct FKey FKey;
6825 typedef struct FuncDef FuncDef;
6826 typedef struct FuncDefHash FuncDefHash;
6827 typedef struct IdList IdList;
6828 typedef struct Index Index;
6829 typedef struct IndexSample IndexSample;
6830 typedef struct KeyClass KeyClass;
6831 typedef struct KeyInfo KeyInfo;
6832 typedef struct Lookaside Lookaside;
6833 typedef struct LookasideSlot LookasideSlot;
6834 typedef struct Module Module;
6835 typedef struct NameContext NameContext;
6836 typedef struct Parse Parse;
6837 typedef struct RowSet RowSet;
6838 typedef struct Savepoint Savepoint;
6839 typedef struct Select Select;
6840 typedef struct SrcList SrcList;
6841 typedef struct StrAccum StrAccum;
6842 typedef struct Table Table;
6843 typedef struct TableLock TableLock;
6844 typedef struct Token Token;
6845 typedef struct Trigger Trigger;
6846 typedef struct TriggerPrg TriggerPrg;
6847 typedef struct TriggerStep TriggerStep;
6848 typedef struct UnpackedRecord UnpackedRecord;
6849 typedef struct VTable VTable;
6850 typedef struct Walker Walker;
6851 typedef struct WherePlan WherePlan;
6852 typedef struct WhereInfo WhereInfo;
6853 typedef struct WhereLevel WhereLevel;
6854
6855 /*
6856 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
6857 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
6858 ** pointer types (i.e. FuncDef) defined above.
6859 */
6860 /************** Include btree.h in the middle of sqliteInt.h *****************/
6861 /************** Begin file btree.h *******************************************/
6862 /*
6863 ** 2001 September 15
6864 **
6865 ** The author disclaims copyright to this source code.  In place of
6866 ** a legal notice, here is a blessing:
6867 **
6868 **    May you do good and not evil.
6869 **    May you find forgiveness for yourself and forgive others.
6870 **    May you share freely, never taking more than you give.
6871 **
6872 *************************************************************************
6873 ** This header file defines the interface that the sqlite B-Tree file
6874 ** subsystem.  See comments in the source code for a detailed description
6875 ** of what each interface routine does.
6876 */
6877 #ifndef _BTREE_H_
6878 #define _BTREE_H_
6879
6880 /* TODO: This definition is just included so other modules compile. It
6881 ** needs to be revisited.
6882 */
6883 #define SQLITE_N_BTREE_META 10
6884
6885 /*
6886 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
6887 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
6888 */
6889 #ifndef SQLITE_DEFAULT_AUTOVACUUM
6890   #define SQLITE_DEFAULT_AUTOVACUUM 0
6891 #endif
6892
6893 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
6894 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
6895 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
6896
6897 /*
6898 ** Forward declarations of structure
6899 */
6900 typedef struct Btree Btree;
6901 typedef struct BtCursor BtCursor;
6902 typedef struct BtShared BtShared;
6903 typedef struct BtreeMutexArray BtreeMutexArray;
6904
6905 /*
6906 ** This structure records all of the Btrees that need to hold
6907 ** a mutex before we enter sqlite3VdbeExec().  The Btrees are
6908 ** are placed in aBtree[] in order of aBtree[]->pBt.  That way,
6909 ** we can always lock and unlock them all quickly.
6910 */
6911 struct BtreeMutexArray {
6912   int nMutex;
6913   Btree *aBtree[SQLITE_MAX_ATTACHED+1];
6914 };
6915
6916
6917 SQLITE_PRIVATE int sqlite3BtreeOpen(
6918   const char *zFilename,   /* Name of database file to open */
6919   sqlite3 *db,             /* Associated database connection */
6920   Btree **ppBtree,         /* Return open Btree* here */
6921   int flags,               /* Flags */
6922   int vfsFlags             /* Flags passed through to VFS open */
6923 );
6924
6925 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
6926 ** following values.
6927 **
6928 ** NOTE:  These values must match the corresponding PAGER_ values in
6929 ** pager.h.
6930 */
6931 #define BTREE_OMIT_JOURNAL  1  /* Do not use journal.  No argument */
6932 #define BTREE_NO_READLOCK   2  /* Omit readlocks on readonly files */
6933 #define BTREE_MEMORY        4  /* In-memory DB.  No argument */
6934 #define BTREE_READONLY      8  /* Open the database in read-only mode */
6935 #define BTREE_READWRITE    16  /* Open for both reading and writing */
6936 #define BTREE_CREATE       32  /* Create the database if it does not exist */
6937
6938 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
6939 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
6940 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree*,int,int);
6941 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
6942 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
6943 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
6944 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
6945 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
6946 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
6947 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
6948 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
6949 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
6950 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
6951 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*);
6952 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
6953 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*);
6954 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
6955 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
6956 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
6957 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
6958 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
6959 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
6960 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
6961 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
6962 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
6963
6964 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
6965 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
6966 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
6967
6968 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
6969
6970 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
6971 ** of the following flags:
6972 */
6973 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
6974 #define BTREE_ZERODATA   2    /* Table has keys only - no data */
6975 #define BTREE_LEAFDATA   4    /* Data stored in leaves only.  Implies INTKEY */
6976
6977 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
6978 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
6979 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree*, int);
6980
6981 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
6982 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
6983
6984 /*
6985 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
6986 ** should be one of the following values. The integer values are assigned 
6987 ** to constants so that the offset of the corresponding field in an
6988 ** SQLite database header may be found using the following formula:
6989 **
6990 **   offset = 36 + (idx * 4)
6991 **
6992 ** For example, the free-page-count field is located at byte offset 36 of
6993 ** the database file header. The incr-vacuum-flag field is located at
6994 ** byte offset 64 (== 36+4*7).
6995 */
6996 #define BTREE_FREE_PAGE_COUNT     0
6997 #define BTREE_SCHEMA_VERSION      1
6998 #define BTREE_FILE_FORMAT         2
6999 #define BTREE_DEFAULT_CACHE_SIZE  3
7000 #define BTREE_LARGEST_ROOT_PAGE   4
7001 #define BTREE_TEXT_ENCODING       5
7002 #define BTREE_USER_VERSION        6
7003 #define BTREE_INCR_VACUUM         7
7004
7005 SQLITE_PRIVATE int sqlite3BtreeCursor(
7006   Btree*,                              /* BTree containing table to open */
7007   int iTable,                          /* Index of root page */
7008   int wrFlag,                          /* 1 for writing.  0 for read-only */
7009   struct KeyInfo*,                     /* First argument to compare function */
7010   BtCursor *pCursor                    /* Space to write cursor structure */
7011 );
7012 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
7013 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
7014
7015 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
7016 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
7017   BtCursor*,
7018   UnpackedRecord *pUnKey,
7019   i64 intKey,
7020   int bias,
7021   int *pRes
7022 );
7023 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*, int*);
7024 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
7025 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
7026                                   const void *pData, int nData,
7027                                   int nZero, int bias, int seekResult);
7028 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
7029 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
7030 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
7031 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
7032 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
7033 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
7034 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
7035 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, int *pAmt);
7036 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, int *pAmt);
7037 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
7038 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
7039 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
7040 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor*);
7041
7042 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
7043 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
7044
7045 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
7046 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *);
7047 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
7048
7049 #ifndef NDEBUG
7050 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
7051 #endif
7052
7053 #ifndef SQLITE_OMIT_BTREECOUNT
7054 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
7055 #endif
7056
7057 #ifdef SQLITE_TEST
7058 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
7059 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
7060 #endif
7061
7062 /*
7063 ** If we are not using shared cache, then there is no need to
7064 ** use mutexes to access the BtShared structures.  So make the
7065 ** Enter and Leave procedures no-ops.
7066 */
7067 #ifndef SQLITE_OMIT_SHARED_CACHE
7068 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
7069 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
7070 #else
7071 # define sqlite3BtreeEnter(X) 
7072 # define sqlite3BtreeEnterAll(X)
7073 #endif
7074
7075 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
7076 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
7077 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
7078 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
7079 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
7080 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayEnter(BtreeMutexArray*);
7081 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayLeave(BtreeMutexArray*);
7082 SQLITE_PRIVATE   void sqlite3BtreeMutexArrayInsert(BtreeMutexArray*, Btree*);
7083 #ifndef NDEBUG
7084   /* These routines are used inside assert() statements only. */
7085 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
7086 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
7087 #endif
7088 #else
7089
7090 # define sqlite3BtreeLeave(X)
7091 # define sqlite3BtreeEnterCursor(X)
7092 # define sqlite3BtreeLeaveCursor(X)
7093 # define sqlite3BtreeLeaveAll(X)
7094 # define sqlite3BtreeMutexArrayEnter(X)
7095 # define sqlite3BtreeMutexArrayLeave(X)
7096 # define sqlite3BtreeMutexArrayInsert(X,Y)
7097
7098 # define sqlite3BtreeHoldsMutex(X) 1
7099 # define sqlite3BtreeHoldsAllMutexes(X) 1
7100 #endif
7101
7102
7103 #endif /* _BTREE_H_ */
7104
7105 /************** End of btree.h ***********************************************/
7106 /************** Continuing where we left off in sqliteInt.h ******************/
7107 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
7108 /************** Begin file vdbe.h ********************************************/
7109 /*
7110 ** 2001 September 15
7111 **
7112 ** The author disclaims copyright to this source code.  In place of
7113 ** a legal notice, here is a blessing:
7114 **
7115 **    May you do good and not evil.
7116 **    May you find forgiveness for yourself and forgive others.
7117 **    May you share freely, never taking more than you give.
7118 **
7119 *************************************************************************
7120 ** Header file for the Virtual DataBase Engine (VDBE)
7121 **
7122 ** This header defines the interface to the virtual database engine
7123 ** or VDBE.  The VDBE implements an abstract machine that runs a
7124 ** simple program to access and modify the underlying database.
7125 */
7126 #ifndef _SQLITE_VDBE_H_
7127 #define _SQLITE_VDBE_H_
7128
7129 /*
7130 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
7131 ** in the source file sqliteVdbe.c are allowed to see the insides
7132 ** of this structure.
7133 */
7134 typedef struct Vdbe Vdbe;
7135
7136 /*
7137 ** The names of the following types declared in vdbeInt.h are required
7138 ** for the VdbeOp definition.
7139 */
7140 typedef struct VdbeFunc VdbeFunc;
7141 typedef struct Mem Mem;
7142 typedef struct SubProgram SubProgram;
7143
7144 /*
7145 ** A single instruction of the virtual machine has an opcode
7146 ** and as many as three operands.  The instruction is recorded
7147 ** as an instance of the following structure:
7148 */
7149 struct VdbeOp {
7150   u8 opcode;          /* What operation to perform */
7151   signed char p4type; /* One of the P4_xxx constants for p4 */
7152   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
7153   u8 p5;              /* Fifth parameter is an unsigned character */
7154   int p1;             /* First operand */
7155   int p2;             /* Second parameter (often the jump destination) */
7156   int p3;             /* The third parameter */
7157   union {             /* fourth parameter */
7158     int i;                 /* Integer value if p4type==P4_INT32 */
7159     void *p;               /* Generic pointer */
7160     char *z;               /* Pointer to data for string (char array) types */
7161     i64 *pI64;             /* Used when p4type is P4_INT64 */
7162     double *pReal;         /* Used when p4type is P4_REAL */
7163     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
7164     VdbeFunc *pVdbeFunc;   /* Used when p4type is P4_VDBEFUNC */
7165     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
7166     Mem *pMem;             /* Used when p4type is P4_MEM */
7167     VTable *pVtab;         /* Used when p4type is P4_VTAB */
7168     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
7169     int *ai;               /* Used when p4type is P4_INTARRAY */
7170     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
7171   } p4;
7172 #ifdef SQLITE_DEBUG
7173   char *zComment;          /* Comment to improve readability */
7174 #endif
7175 #ifdef VDBE_PROFILE
7176   int cnt;                 /* Number of times this instruction was executed */
7177   u64 cycles;              /* Total time spent executing this instruction */
7178 #endif
7179 };
7180 typedef struct VdbeOp VdbeOp;
7181
7182
7183 /*
7184 ** A sub-routine used to implement a trigger program.
7185 */
7186 struct SubProgram {
7187   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
7188   int nOp;                      /* Elements in aOp[] */
7189   int nMem;                     /* Number of memory cells required */
7190   int nCsr;                     /* Number of cursors required */
7191   int nRef;                     /* Number of pointers to this structure */
7192   void *token;                  /* id that may be used to recursive triggers */
7193 };
7194
7195 /*
7196 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
7197 ** it takes up less space.
7198 */
7199 struct VdbeOpList {
7200   u8 opcode;          /* What operation to perform */
7201   signed char p1;     /* First operand */
7202   signed char p2;     /* Second parameter (often the jump destination) */
7203   signed char p3;     /* Third parameter */
7204 };
7205 typedef struct VdbeOpList VdbeOpList;
7206
7207 /*
7208 ** Allowed values of VdbeOp.p4type
7209 */
7210 #define P4_NOTUSED    0   /* The P4 parameter is not used */
7211 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
7212 #define P4_STATIC   (-2)  /* Pointer to a static string */
7213 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
7214 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
7215 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
7216 #define P4_VDBEFUNC (-7)  /* P4 is a pointer to a VdbeFunc structure */
7217 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
7218 #define P4_TRANSIENT (-9) /* P4 is a pointer to a transient string */
7219 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
7220 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
7221 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
7222 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
7223 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
7224 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
7225 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
7226
7227 /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
7228 ** is made.  That copy is freed when the Vdbe is finalized.  But if the
7229 ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used.  It still
7230 ** gets freed when the Vdbe is finalized so it still should be obtained
7231 ** from a single sqliteMalloc().  But no copy is made and the calling
7232 ** function should *not* try to free the KeyInfo.
7233 */
7234 #define P4_KEYINFO_HANDOFF (-16)
7235 #define P4_KEYINFO_STATIC  (-17)
7236
7237 /*
7238 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
7239 ** number of columns of data returned by the statement.
7240 */
7241 #define COLNAME_NAME     0
7242 #define COLNAME_DECLTYPE 1
7243 #define COLNAME_DATABASE 2
7244 #define COLNAME_TABLE    3
7245 #define COLNAME_COLUMN   4
7246 #ifdef SQLITE_ENABLE_COLUMN_METADATA
7247 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
7248 #else
7249 # ifdef SQLITE_OMIT_DECLTYPE
7250 #   define COLNAME_N      1      /* Store only the name */
7251 # else
7252 #   define COLNAME_N      2      /* Store the name and decltype */
7253 # endif
7254 #endif
7255
7256 /*
7257 ** The following macro converts a relative address in the p2 field
7258 ** of a VdbeOp structure into a negative number so that 
7259 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
7260 ** the macro again restores the address.
7261 */
7262 #define ADDR(X)  (-1-(X))
7263
7264 /*
7265 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
7266 ** header file that defines a number for each opcode used by the VDBE.
7267 */
7268 /************** Include opcodes.h in the middle of vdbe.h ********************/
7269 /************** Begin file opcodes.h *****************************************/
7270 /* Automatically generated.  Do not edit */
7271 /* See the mkopcodeh.awk script for details */
7272 #define OP_Goto                                 1
7273 #define OP_Gosub                                2
7274 #define OP_Return                               3
7275 #define OP_Yield                                4
7276 #define OP_HaltIfNull                           5
7277 #define OP_Halt                                 6
7278 #define OP_Integer                              7
7279 #define OP_Int64                                8
7280 #define OP_Real                               130   /* same as TK_FLOAT    */
7281 #define OP_String8                             94   /* same as TK_STRING   */
7282 #define OP_String                               9
7283 #define OP_Null                                10
7284 #define OP_Blob                                11
7285 #define OP_Variable                            12
7286 #define OP_Move                                13
7287 #define OP_Copy                                14
7288 #define OP_SCopy                               15
7289 #define OP_ResultRow                           16
7290 #define OP_Concat                              91   /* same as TK_CONCAT   */
7291 #define OP_Add                                 86   /* same as TK_PLUS     */
7292 #define OP_Subtract                            87   /* same as TK_MINUS    */
7293 #define OP_Multiply                            88   /* same as TK_STAR     */
7294 #define OP_Divide                              89   /* same as TK_SLASH    */
7295 #define OP_Remainder                           90   /* same as TK_REM      */
7296 #define OP_CollSeq                             17
7297 #define OP_Function                            18
7298 #define OP_BitAnd                              82   /* same as TK_BITAND   */
7299 #define OP_BitOr                               83   /* same as TK_BITOR    */
7300 #define OP_ShiftLeft                           84   /* same as TK_LSHIFT   */
7301 #define OP_ShiftRight                          85   /* same as TK_RSHIFT   */
7302 #define OP_AddImm                              20
7303 #define OP_MustBeInt                           21
7304 #define OP_RealAffinity                        22
7305 #define OP_ToText                             141   /* same as TK_TO_TEXT  */
7306 #define OP_ToBlob                             142   /* same as TK_TO_BLOB  */
7307 #define OP_ToNumeric                          143   /* same as TK_TO_NUMERIC*/
7308 #define OP_ToInt                              144   /* same as TK_TO_INT   */
7309 #define OP_ToReal                             145   /* same as TK_TO_REAL  */
7310 #define OP_Eq                                  76   /* same as TK_EQ       */
7311 #define OP_Ne                                  75   /* same as TK_NE       */
7312 #define OP_Lt                                  79   /* same as TK_LT       */
7313 #define OP_Le                                  78   /* same as TK_LE       */
7314 #define OP_Gt                                  77   /* same as TK_GT       */
7315 #define OP_Ge                                  80   /* same as TK_GE       */
7316 #define OP_Permutation                         23
7317 #define OP_Compare                             24
7318 #define OP_Jump                                25
7319 #define OP_And                                 69   /* same as TK_AND      */
7320 #define OP_Or                                  68   /* same as TK_OR       */
7321 #define OP_Not                                 19   /* same as TK_NOT      */
7322 #define OP_BitNot                              93   /* same as TK_BITNOT   */
7323 #define OP_If                                  26
7324 #define OP_IfNot                               27
7325 #define OP_IsNull                              73   /* same as TK_ISNULL   */
7326 #define OP_NotNull                             74   /* same as TK_NOTNULL  */
7327 #define OP_Column                              28
7328 #define OP_Affinity                            29
7329 #define OP_MakeRecord                          30
7330 #define OP_Count                               31
7331 #define OP_Savepoint                           32
7332 #define OP_AutoCommit                          33
7333 #define OP_Transaction                         34
7334 #define OP_ReadCookie                          35
7335 #define OP_SetCookie                           36
7336 #define OP_VerifyCookie                        37
7337 #define OP_OpenRead                            38
7338 #define OP_OpenWrite                           39
7339 #define OP_OpenEphemeral                       40
7340 #define OP_OpenPseudo                          41
7341 #define OP_Close                               42
7342 #define OP_SeekLt                              43
7343 #define OP_SeekLe                              44
7344 #define OP_SeekGe                              45
7345 #define OP_SeekGt                              46
7346 #define OP_Seek                                47
7347 #define OP_NotFound                            48
7348 #define OP_Found                               49
7349 #define OP_IsUnique                            50
7350 #define OP_NotExists                           51
7351 #define OP_Sequence                            52
7352 #define OP_NewRowid                            53
7353 #define OP_Insert                              54
7354 #define OP_InsertInt                           55
7355 #define OP_Delete                              56
7356 #define OP_ResetCount                          57
7357 #define OP_RowKey                              58
7358 #define OP_RowData                             59
7359 #define OP_Rowid                               60
7360 #define OP_NullRow                             61
7361 #define OP_Last                                62
7362 #define OP_Sort                                63
7363 #define OP_Rewind                              64
7364 #define OP_Prev                                65
7365 #define OP_Next                                66
7366 #define OP_IdxInsert                           67
7367 #define OP_IdxDelete                           70
7368 #define OP_IdxRowid                            71
7369 #define OP_IdxLT                               72
7370 #define OP_IdxGE                               81
7371 #define OP_Destroy                             92
7372 #define OP_Clear                               95
7373 #define OP_CreateIndex                         96
7374 #define OP_CreateTable                         97
7375 #define OP_ParseSchema                         98
7376 #define OP_LoadAnalysis                        99
7377 #define OP_DropTable                          100
7378 #define OP_DropIndex                          101
7379 #define OP_DropTrigger                        102
7380 #define OP_IntegrityCk                        103
7381 #define OP_RowSetAdd                          104
7382 #define OP_RowSetRead                         105
7383 #define OP_RowSetTest                         106
7384 #define OP_Program                            107
7385 #define OP_Param                              108
7386 #define OP_FkCounter                          109
7387 #define OP_FkIfZero                           110
7388 #define OP_MemMax                             111
7389 #define OP_IfPos                              112
7390 #define OP_IfNeg                              113
7391 #define OP_IfZero                             114
7392 #define OP_AggStep                            115
7393 #define OP_AggFinal                           116
7394 #define OP_Vacuum                             117
7395 #define OP_IncrVacuum                         118
7396 #define OP_Expire                             119
7397 #define OP_TableLock                          120
7398 #define OP_VBegin                             121
7399 #define OP_VCreate                            122
7400 #define OP_VDestroy                           123
7401 #define OP_VOpen                              124
7402 #define OP_VFilter                            125
7403 #define OP_VColumn                            126
7404 #define OP_VNext                              127
7405 #define OP_VRename                            128
7406 #define OP_VUpdate                            129
7407 #define OP_Pagecount                          131
7408 #define OP_Trace                              132
7409 #define OP_Noop                               133
7410 #define OP_Explain                            134
7411
7412 /* The following opcode values are never used */
7413 #define OP_NotUsed_135                        135
7414 #define OP_NotUsed_136                        136
7415 #define OP_NotUsed_137                        137
7416 #define OP_NotUsed_138                        138
7417 #define OP_NotUsed_139                        139
7418 #define OP_NotUsed_140                        140
7419
7420
7421 /* Properties such as "out2" or "jump" that are specified in
7422 ** comments following the "case" for each opcode in the vdbe.c
7423 ** are encoded into bitvectors as follows:
7424 */
7425 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
7426 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
7427 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
7428 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
7429 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
7430 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
7431 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
7432 #define OPFLG_INITIALIZER {\
7433 /*   0 */ 0x00, 0x01, 0x05, 0x04, 0x04, 0x10, 0x00, 0x02,\
7434 /*   8 */ 0x02, 0x02, 0x02, 0x02, 0x00, 0x00, 0x24, 0x24,\
7435 /*  16 */ 0x00, 0x00, 0x00, 0x24, 0x04, 0x05, 0x04, 0x00,\
7436 /*  24 */ 0x00, 0x01, 0x05, 0x05, 0x00, 0x00, 0x00, 0x02,\
7437 /*  32 */ 0x00, 0x00, 0x00, 0x02, 0x10, 0x00, 0x00, 0x00,\
7438 /*  40 */ 0x00, 0x00, 0x00, 0x11, 0x11, 0x11, 0x11, 0x08,\
7439 /*  48 */ 0x11, 0x11, 0x11, 0x11, 0x02, 0x02, 0x00, 0x00,\
7440 /*  56 */ 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x01, 0x01,\
7441 /*  64 */ 0x01, 0x01, 0x01, 0x08, 0x4c, 0x4c, 0x00, 0x02,\
7442 /*  72 */ 0x01, 0x05, 0x05, 0x15, 0x15, 0x15, 0x15, 0x15,\
7443 /*  80 */ 0x15, 0x01, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c,\
7444 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x02, 0x24, 0x02, 0x00,\
7445 /*  96 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
7446 /* 104 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x00, 0x01, 0x08,\
7447 /* 112 */ 0x05, 0x05, 0x05, 0x00, 0x00, 0x00, 0x01, 0x00,\
7448 /* 120 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01,\
7449 /* 128 */ 0x00, 0x00, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00,\
7450 /* 136 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x04, 0x04,\
7451 /* 144 */ 0x04, 0x04,}
7452
7453 /************** End of opcodes.h *********************************************/
7454 /************** Continuing where we left off in vdbe.h ***********************/
7455
7456 /*
7457 ** Prototypes for the VDBE interface.  See comments on the implementation
7458 ** for a description of what each of these routines does.
7459 */
7460 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3*);
7461 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
7462 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
7463 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
7464 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
7465 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
7466 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
7467 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
7468 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
7469 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
7470 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
7471 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
7472 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
7473 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
7474 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
7475 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
7476 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
7477 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
7478 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
7479 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
7480 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,int,int,int,int,int,int);
7481 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
7482 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
7483 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
7484 #ifdef SQLITE_DEBUG
7485 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
7486 SQLITE_PRIVATE   void sqlite3VdbeTrace(Vdbe*,FILE*);
7487 #endif
7488 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
7489 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
7490 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
7491 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
7492 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
7493 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
7494 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
7495 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
7496 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
7497 SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *, SubProgram *, int);
7498 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
7499 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
7500 #ifndef SQLITE_OMIT_TRACE
7501 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
7502 #endif
7503
7504 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
7505 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord*);
7506 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
7507
7508
7509 #ifndef NDEBUG
7510 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
7511 # define VdbeComment(X)  sqlite3VdbeComment X
7512 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
7513 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
7514 #else
7515 # define VdbeComment(X)
7516 # define VdbeNoopComment(X)
7517 #endif
7518
7519 #endif
7520
7521 /************** End of vdbe.h ************************************************/
7522 /************** Continuing where we left off in sqliteInt.h ******************/
7523 /************** Include pager.h in the middle of sqliteInt.h *****************/
7524 /************** Begin file pager.h *******************************************/
7525 /*
7526 ** 2001 September 15
7527 **
7528 ** The author disclaims copyright to this source code.  In place of
7529 ** a legal notice, here is a blessing:
7530 **
7531 **    May you do good and not evil.
7532 **    May you find forgiveness for yourself and forgive others.
7533 **    May you share freely, never taking more than you give.
7534 **
7535 *************************************************************************
7536 ** This header file defines the interface that the sqlite page cache
7537 ** subsystem.  The page cache subsystem reads and writes a file a page
7538 ** at a time and provides a journal for rollback.
7539 */
7540
7541 #ifndef _PAGER_H_
7542 #define _PAGER_H_
7543
7544 /*
7545 ** Default maximum size for persistent journal files. A negative 
7546 ** value means no limit. This value may be overridden using the 
7547 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
7548 */
7549 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
7550   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
7551 #endif
7552
7553 /*
7554 ** The type used to represent a page number.  The first page in a file
7555 ** is called page 1.  0 is used to represent "not a page".
7556 */
7557 typedef u32 Pgno;
7558
7559 /*
7560 ** Each open file is managed by a separate instance of the "Pager" structure.
7561 */
7562 typedef struct Pager Pager;
7563
7564 /*
7565 ** Handle type for pages.
7566 */
7567 typedef struct PgHdr DbPage;
7568
7569 /*
7570 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
7571 ** reserved for working around a windows/posix incompatibility). It is
7572 ** used in the journal to signify that the remainder of the journal file 
7573 ** is devoted to storing a master journal name - there are no more pages to
7574 ** roll back. See comments for function writeMasterJournal() in pager.c 
7575 ** for details.
7576 */
7577 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
7578
7579 /*
7580 ** Allowed values for the flags parameter to sqlite3PagerOpen().
7581 **
7582 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
7583 */
7584 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
7585 #define PAGER_NO_READLOCK   0x0002    /* Omit readlocks on readonly files */
7586
7587 /*
7588 ** Valid values for the second argument to sqlite3PagerLockingMode().
7589 */
7590 #define PAGER_LOCKINGMODE_QUERY      -1
7591 #define PAGER_LOCKINGMODE_NORMAL      0
7592 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
7593
7594 /*
7595 ** Valid values for the second argument to sqlite3PagerJournalMode().
7596 */
7597 #define PAGER_JOURNALMODE_QUERY      -1
7598 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
7599 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
7600 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
7601 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
7602 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
7603
7604 /*
7605 ** The remainder of this file contains the declarations of the functions
7606 ** that make up the Pager sub-system API. See source code comments for 
7607 ** a detailed description of each routine.
7608 */
7609
7610 /* Open and close a Pager connection. */ 
7611 SQLITE_PRIVATE int sqlite3PagerOpen(
7612   sqlite3_vfs*,
7613   Pager **ppPager,
7614   const char*,
7615   int,
7616   int,
7617   int,
7618   void(*)(DbPage*)
7619 );
7620 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
7621 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
7622
7623 /* Functions used to configure a Pager object. */
7624 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
7625 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u16*, int);
7626 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
7627 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
7628 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager*,int,int);
7629 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
7630 SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *, int);
7631 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
7632 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
7633
7634 /* Functions used to obtain and release page references. */ 
7635 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
7636 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
7637 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
7638 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
7639 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
7640
7641 /* Operations on page references. */
7642 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
7643 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
7644 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
7645 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
7646 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
7647 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
7648
7649 /* Functions used to manage pager transactions and savepoints. */
7650 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager*, int*);
7651 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
7652 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
7653 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager);
7654 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
7655 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
7656 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
7657 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
7658 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
7659
7660 /* Functions used to query pager state and configuration. */
7661 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
7662 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
7663 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*);
7664 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
7665 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
7666 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
7667 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
7668 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
7669 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
7670
7671 /* Functions used to truncate the database file. */
7672 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
7673
7674 /* Functions to support testing and debugging. */
7675 #if !defined(NDEBUG) || defined(SQLITE_TEST)
7676 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
7677 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
7678 #endif
7679 #ifdef SQLITE_TEST
7680 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
7681 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
7682   void disable_simulated_io_errors(void);
7683   void enable_simulated_io_errors(void);
7684 #else
7685 # define disable_simulated_io_errors()
7686 # define enable_simulated_io_errors()
7687 #endif
7688
7689 #endif /* _PAGER_H_ */
7690
7691 /************** End of pager.h ***********************************************/
7692 /************** Continuing where we left off in sqliteInt.h ******************/
7693 /************** Include pcache.h in the middle of sqliteInt.h ****************/
7694 /************** Begin file pcache.h ******************************************/
7695 /*
7696 ** 2008 August 05
7697 **
7698 ** The author disclaims copyright to this source code.  In place of
7699 ** a legal notice, here is a blessing:
7700 **
7701 **    May you do good and not evil.
7702 **    May you find forgiveness for yourself and forgive others.
7703 **    May you share freely, never taking more than you give.
7704 **
7705 *************************************************************************
7706 ** This header file defines the interface that the sqlite page cache
7707 ** subsystem. 
7708 */
7709
7710 #ifndef _PCACHE_H_
7711
7712 typedef struct PgHdr PgHdr;
7713 typedef struct PCache PCache;
7714
7715 /*
7716 ** Every page in the cache is controlled by an instance of the following
7717 ** structure.
7718 */
7719 struct PgHdr {
7720   void *pData;                   /* Content of this page */
7721   void *pExtra;                  /* Extra content */
7722   PgHdr *pDirty;                 /* Transient list of dirty pages */
7723   Pgno pgno;                     /* Page number for this page */
7724   Pager *pPager;                 /* The pager this page is part of */
7725 #ifdef SQLITE_CHECK_PAGES
7726   u32 pageHash;                  /* Hash of page content */
7727 #endif
7728   u16 flags;                     /* PGHDR flags defined below */
7729
7730   /**********************************************************************
7731   ** Elements above are public.  All that follows is private to pcache.c
7732   ** and should not be accessed by other modules.
7733   */
7734   i16 nRef;                      /* Number of users of this page */
7735   PCache *pCache;                /* Cache that owns this page */
7736
7737   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
7738   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
7739 };
7740
7741 /* Bit values for PgHdr.flags */
7742 #define PGHDR_DIRTY             0x002  /* Page has changed */
7743 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
7744                                        ** writing this page to the database */
7745 #define PGHDR_NEED_READ         0x008  /* Content is unread */
7746 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
7747 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
7748
7749 /* Initialize and shutdown the page cache subsystem */
7750 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
7751 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
7752
7753 /* Page cache buffer management:
7754 ** These routines implement SQLITE_CONFIG_PAGECACHE.
7755 */
7756 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
7757
7758 /* Create a new pager cache.
7759 ** Under memory stress, invoke xStress to try to make pages clean.
7760 ** Only clean and unpinned pages can be reclaimed.
7761 */
7762 SQLITE_PRIVATE void sqlite3PcacheOpen(
7763   int szPage,                    /* Size of every page */
7764   int szExtra,                   /* Extra space associated with each page */
7765   int bPurgeable,                /* True if pages are on backing store */
7766   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
7767   void *pStress,                 /* Argument to xStress */
7768   PCache *pToInit                /* Preallocated space for the PCache */
7769 );
7770
7771 /* Modify the page-size after the cache has been created. */
7772 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *, int);
7773
7774 /* Return the size in bytes of a PCache object.  Used to preallocate
7775 ** storage space.
7776 */
7777 SQLITE_PRIVATE int sqlite3PcacheSize(void);
7778
7779 /* One release per successful fetch.  Page is pinned until released.
7780 ** Reference counted. 
7781 */
7782 SQLITE_PRIVATE int sqlite3PcacheFetch(PCache*, Pgno, int createFlag, PgHdr**);
7783 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
7784
7785 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
7786 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
7787 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
7788 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
7789
7790 /* Change a page number.  Used by incr-vacuum. */
7791 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
7792
7793 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
7794 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
7795
7796 /* Get a list of all dirty pages in the cache, sorted by page number */
7797 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
7798
7799 /* Reset and close the cache object */
7800 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
7801
7802 /* Clear flags from pages of the page cache */
7803 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
7804
7805 /* Discard the contents of the cache */
7806 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
7807
7808 /* Return the total number of outstanding page references */
7809 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
7810
7811 /* Increment the reference count of an existing page */
7812 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
7813
7814 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
7815
7816 /* Return the total number of pages stored in the cache */
7817 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
7818
7819 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
7820 /* Iterate through all dirty pages currently stored in the cache. This
7821 ** interface is only available if SQLITE_CHECK_PAGES is defined when the 
7822 ** library is built.
7823 */
7824 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
7825 #endif
7826
7827 /* Set and get the suggested cache-size for the specified pager-cache.
7828 **
7829 ** If no global maximum is configured, then the system attempts to limit
7830 ** the total number of pages cached by purgeable pager-caches to the sum
7831 ** of the suggested cache-sizes.
7832 */
7833 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
7834 #ifdef SQLITE_TEST
7835 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
7836 #endif
7837
7838 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
7839 /* Try to return memory used by the pcache module to the main memory heap */
7840 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
7841 #endif
7842
7843 #ifdef SQLITE_TEST
7844 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
7845 #endif
7846
7847 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
7848
7849 #endif /* _PCACHE_H_ */
7850
7851 /************** End of pcache.h **********************************************/
7852 /************** Continuing where we left off in sqliteInt.h ******************/
7853
7854 /************** Include os.h in the middle of sqliteInt.h ********************/
7855 /************** Begin file os.h **********************************************/
7856 /*
7857 ** 2001 September 16
7858 **
7859 ** The author disclaims copyright to this source code.  In place of
7860 ** a legal notice, here is a blessing:
7861 **
7862 **    May you do good and not evil.
7863 **    May you find forgiveness for yourself and forgive others.
7864 **    May you share freely, never taking more than you give.
7865 **
7866 ******************************************************************************
7867 **
7868 ** This header file (together with is companion C source-code file
7869 ** "os.c") attempt to abstract the underlying operating system so that
7870 ** the SQLite library will work on both POSIX and windows systems.
7871 **
7872 ** This header file is #include-ed by sqliteInt.h and thus ends up
7873 ** being included by every source file.
7874 */
7875 #ifndef _SQLITE_OS_H_
7876 #define _SQLITE_OS_H_
7877
7878 /*
7879 ** Figure out if we are dealing with Unix, Windows, or some other
7880 ** operating system.  After the following block of preprocess macros,
7881 ** all of SQLITE_OS_UNIX, SQLITE_OS_WIN, SQLITE_OS_OS2, and SQLITE_OS_OTHER 
7882 ** will defined to either 1 or 0.  One of the four will be 1.  The other 
7883 ** three will be 0.
7884 */
7885 #if defined(SQLITE_OS_OTHER)
7886 # if SQLITE_OS_OTHER==1
7887 #   undef SQLITE_OS_UNIX
7888 #   define SQLITE_OS_UNIX 0
7889 #   undef SQLITE_OS_WIN
7890 #   define SQLITE_OS_WIN 0
7891 #   undef SQLITE_OS_OS2
7892 #   define SQLITE_OS_OS2 0
7893 # else
7894 #   undef SQLITE_OS_OTHER
7895 # endif
7896 #endif
7897 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
7898 # define SQLITE_OS_OTHER 0
7899 # ifndef SQLITE_OS_WIN
7900 #   if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__BORLANDC__)
7901 #     define SQLITE_OS_WIN 1
7902 #     define SQLITE_OS_UNIX 0
7903 #     define SQLITE_OS_OS2 0
7904 #   elif defined(__EMX__) || defined(_OS2) || defined(OS2) || defined(_OS2_) || defined(__OS2__)
7905 #     define SQLITE_OS_WIN 0
7906 #     define SQLITE_OS_UNIX 0
7907 #     define SQLITE_OS_OS2 1
7908 #   else
7909 #     define SQLITE_OS_WIN 0
7910 #     define SQLITE_OS_UNIX 1
7911 #     define SQLITE_OS_OS2 0
7912 #  endif
7913 # else
7914 #  define SQLITE_OS_UNIX 0
7915 #  define SQLITE_OS_OS2 0
7916 # endif
7917 #else
7918 # ifndef SQLITE_OS_WIN
7919 #  define SQLITE_OS_WIN 0
7920 # endif
7921 #endif
7922
7923 /*
7924 ** Determine if we are dealing with WindowsCE - which has a much
7925 ** reduced API.
7926 */
7927 #if defined(_WIN32_WCE)
7928 # define SQLITE_OS_WINCE 1
7929 #else
7930 # define SQLITE_OS_WINCE 0
7931 #endif
7932
7933
7934 /*
7935 ** Define the maximum size of a temporary filename
7936 */
7937 #if SQLITE_OS_WIN
7938 # include <windows.h>
7939 # define SQLITE_TEMPNAME_SIZE (MAX_PATH+50)
7940 #elif SQLITE_OS_OS2
7941 # if (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 3) && defined(OS2_HIGH_MEMORY)
7942 #  include <os2safe.h> /* has to be included before os2.h for linking to work */
7943 # endif
7944 # define INCL_DOSDATETIME
7945 # define INCL_DOSFILEMGR
7946 # define INCL_DOSERRORS
7947 # define INCL_DOSMISC
7948 # define INCL_DOSPROCESS
7949 # define INCL_DOSMODULEMGR
7950 # define INCL_DOSSEMAPHORES
7951 # include <os2.h>
7952 # include <uconv.h>
7953 # define SQLITE_TEMPNAME_SIZE (CCHMAXPATHCOMP)
7954 #else
7955 # define SQLITE_TEMPNAME_SIZE 200
7956 #endif
7957
7958 /* If the SET_FULLSYNC macro is not defined above, then make it
7959 ** a no-op
7960 */
7961 #ifndef SET_FULLSYNC
7962 # define SET_FULLSYNC(x,y)
7963 #endif
7964
7965 /*
7966 ** The default size of a disk sector
7967 */
7968 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
7969 # define SQLITE_DEFAULT_SECTOR_SIZE 512
7970 #endif
7971
7972 /*
7973 ** Temporary files are named starting with this prefix followed by 16 random
7974 ** alphanumeric characters, and no file extension. They are stored in the
7975 ** OS's standard temporary file directory, and are deleted prior to exit.
7976 ** If sqlite is being embedded in another program, you may wish to change the
7977 ** prefix to reflect your program's name, so that if your program exits
7978 ** prematurely, old temporary files can be easily identified. This can be done
7979 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
7980 **
7981 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
7982 ** Mcafee started using SQLite in their anti-virus product and it
7983 ** started putting files with the "sqlite" name in the c:/temp folder.
7984 ** This annoyed many windows users.  Those users would then do a 
7985 ** Google search for "sqlite", find the telephone numbers of the
7986 ** developers and call to wake them up at night and complain.
7987 ** For this reason, the default name prefix is changed to be "sqlite" 
7988 ** spelled backwards.  So the temp files are still identified, but
7989 ** anybody smart enough to figure out the code is also likely smart
7990 ** enough to know that calling the developer will not help get rid
7991 ** of the file.
7992 */
7993 #ifndef SQLITE_TEMP_FILE_PREFIX
7994 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
7995 #endif
7996
7997 /*
7998 ** The following values may be passed as the second argument to
7999 ** sqlite3OsLock(). The various locks exhibit the following semantics:
8000 **
8001 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
8002 ** RESERVED:  A single process may hold a RESERVED lock on a file at
8003 **            any time. Other processes may hold and obtain new SHARED locks.
8004 ** PENDING:   A single process may hold a PENDING lock on a file at
8005 **            any one time. Existing SHARED locks may persist, but no new
8006 **            SHARED locks may be obtained by other processes.
8007 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
8008 **
8009 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
8010 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
8011 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
8012 ** sqlite3OsLock().
8013 */
8014 #define NO_LOCK         0
8015 #define SHARED_LOCK     1
8016 #define RESERVED_LOCK   2
8017 #define PENDING_LOCK    3
8018 #define EXCLUSIVE_LOCK  4
8019
8020 /*
8021 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
8022 **
8023 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
8024 ** those functions are not available.  So we use only LockFile() and
8025 ** UnlockFile().
8026 **
8027 ** LockFile() prevents not just writing but also reading by other processes.
8028 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
8029 ** byte out of a specific range of bytes. The lock byte is obtained at 
8030 ** random so two separate readers can probably access the file at the 
8031 ** same time, unless they are unlucky and choose the same lock byte.
8032 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
8033 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
8034 ** a single byte of the file that is designated as the reserved lock byte.
8035 ** A PENDING_LOCK is obtained by locking a designated byte different from
8036 ** the RESERVED_LOCK byte.
8037 **
8038 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
8039 ** which means we can use reader/writer locks.  When reader/writer locks
8040 ** are used, the lock is placed on the same range of bytes that is used
8041 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
8042 ** will support two or more Win95 readers or two or more WinNT readers.
8043 ** But a single Win95 reader will lock out all WinNT readers and a single
8044 ** WinNT reader will lock out all other Win95 readers.
8045 **
8046 ** The following #defines specify the range of bytes used for locking.
8047 ** SHARED_SIZE is the number of bytes available in the pool from which
8048 ** a random byte is selected for a shared lock.  The pool of bytes for
8049 ** shared locks begins at SHARED_FIRST. 
8050 **
8051 ** The same locking strategy and
8052 ** byte ranges are used for Unix.  This leaves open the possiblity of having
8053 ** clients on win95, winNT, and unix all talking to the same shared file
8054 ** and all locking correctly.  To do so would require that samba (or whatever
8055 ** tool is being used for file sharing) implements locks correctly between
8056 ** windows and unix.  I'm guessing that isn't likely to happen, but by
8057 ** using the same locking range we are at least open to the possibility.
8058 **
8059 ** Locking in windows is manditory.  For this reason, we cannot store
8060 ** actual data in the bytes used for locking.  The pager never allocates
8061 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
8062 ** that all locks will fit on a single page even at the minimum page size.
8063 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
8064 ** is set high so that we don't have to allocate an unused page except
8065 ** for very large databases.  But one should test the page skipping logic 
8066 ** by setting PENDING_BYTE low and running the entire regression suite.
8067 **
8068 ** Changing the value of PENDING_BYTE results in a subtly incompatible
8069 ** file format.  Depending on how it is changed, you might not notice
8070 ** the incompatibility right away, even running a full regression test.
8071 ** The default location of PENDING_BYTE is the first byte past the
8072 ** 1GB boundary.
8073 **
8074 */
8075 #define PENDING_BYTE      sqlite3PendingByte
8076 #define RESERVED_BYTE     (PENDING_BYTE+1)
8077 #define SHARED_FIRST      (PENDING_BYTE+2)
8078 #define SHARED_SIZE       510
8079
8080 /*
8081 ** Wrapper around OS specific sqlite3_os_init() function.
8082 */
8083 SQLITE_PRIVATE int sqlite3OsInit(void);
8084
8085 /* 
8086 ** Functions for accessing sqlite3_file methods 
8087 */
8088 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
8089 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
8090 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
8091 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
8092 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
8093 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
8094 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
8095 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
8096 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
8097 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
8098 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
8099 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
8100 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
8101
8102 /* 
8103 ** Functions for accessing sqlite3_vfs methods 
8104 */
8105 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
8106 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
8107 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
8108 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
8109 #ifndef SQLITE_OMIT_LOAD_EXTENSION
8110 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
8111 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
8112 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
8113 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
8114 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
8115 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
8116 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
8117 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *, double*);
8118
8119 /*
8120 ** Convenience functions for opening and closing files using 
8121 ** sqlite3_malloc() to obtain space for the file-handle structure.
8122 */
8123 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
8124 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
8125
8126 #endif /* _SQLITE_OS_H_ */
8127
8128 /************** End of os.h **************************************************/
8129 /************** Continuing where we left off in sqliteInt.h ******************/
8130 /************** Include mutex.h in the middle of sqliteInt.h *****************/
8131 /************** Begin file mutex.h *******************************************/
8132 /*
8133 ** 2007 August 28
8134 **
8135 ** The author disclaims copyright to this source code.  In place of
8136 ** a legal notice, here is a blessing:
8137 **
8138 **    May you do good and not evil.
8139 **    May you find forgiveness for yourself and forgive others.
8140 **    May you share freely, never taking more than you give.
8141 **
8142 *************************************************************************
8143 **
8144 ** This file contains the common header for all mutex implementations.
8145 ** The sqliteInt.h header #includes this file so that it is available
8146 ** to all source files.  We break it out in an effort to keep the code
8147 ** better organized.
8148 **
8149 ** NOTE:  source files should *not* #include this header file directly.
8150 ** Source files should #include the sqliteInt.h file and let that file
8151 ** include this one indirectly.
8152 */
8153
8154
8155 /*
8156 ** Figure out what version of the code to use.  The choices are
8157 **
8158 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
8159 **                             mutexes implemention cannot be overridden
8160 **                             at start-time.
8161 **
8162 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
8163 **                             mutual exclusion is provided.  But this
8164 **                             implementation can be overridden at
8165 **                             start-time.
8166 **
8167 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
8168 **
8169 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
8170 **
8171 **   SQLITE_MUTEX_OS2          For multi-threaded applications on OS/2.
8172 */
8173 #if !SQLITE_THREADSAFE
8174 # define SQLITE_MUTEX_OMIT
8175 #endif
8176 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
8177 #  if SQLITE_OS_UNIX
8178 #    define SQLITE_MUTEX_PTHREADS
8179 #  elif SQLITE_OS_WIN
8180 #    define SQLITE_MUTEX_W32
8181 #  elif SQLITE_OS_OS2
8182 #    define SQLITE_MUTEX_OS2
8183 #  else
8184 #    define SQLITE_MUTEX_NOOP
8185 #  endif
8186 #endif
8187
8188 #ifdef SQLITE_MUTEX_OMIT
8189 /*
8190 ** If this is a no-op implementation, implement everything as macros.
8191 */
8192 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
8193 #define sqlite3_mutex_free(X)
8194 #define sqlite3_mutex_enter(X)
8195 #define sqlite3_mutex_try(X)      SQLITE_OK
8196 #define sqlite3_mutex_leave(X)
8197 #define sqlite3_mutex_held(X)     1
8198 #define sqlite3_mutex_notheld(X)  1
8199 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
8200 #define sqlite3MutexInit()        SQLITE_OK
8201 #define sqlite3MutexEnd()
8202 #endif /* defined(SQLITE_MUTEX_OMIT) */
8203
8204 /************** End of mutex.h ***********************************************/
8205 /************** Continuing where we left off in sqliteInt.h ******************/
8206
8207
8208 /*
8209 ** Each database file to be accessed by the system is an instance
8210 ** of the following structure.  There are normally two of these structures
8211 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
8212 ** aDb[1] is the database file used to hold temporary tables.  Additional
8213 ** databases may be attached.
8214 */
8215 struct Db {
8216   char *zName;         /* Name of this database */
8217   Btree *pBt;          /* The B*Tree structure for this database file */
8218   u8 inTrans;          /* 0: not writable.  1: Transaction.  2: Checkpoint */
8219   u8 safety_level;     /* How aggressive at syncing data to disk */
8220   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
8221 };
8222
8223 /*
8224 ** An instance of the following structure stores a database schema.
8225 **
8226 ** If there are no virtual tables configured in this schema, the
8227 ** Schema.db variable is set to NULL. After the first virtual table
8228 ** has been added, it is set to point to the database connection 
8229 ** used to create the connection. Once a virtual table has been
8230 ** added to the Schema structure and the Schema.db variable populated, 
8231 ** only that database connection may use the Schema to prepare 
8232 ** statements.
8233 */
8234 struct Schema {
8235   int schema_cookie;   /* Database schema version number for this file */
8236   Hash tblHash;        /* All tables indexed by name */
8237   Hash idxHash;        /* All (named) indices indexed by name */
8238   Hash trigHash;       /* All triggers indexed by name */
8239   Hash fkeyHash;       /* All foreign keys by referenced table name */
8240   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
8241   u8 file_format;      /* Schema format version for this file */
8242   u8 enc;              /* Text encoding used by this database */
8243   u16 flags;           /* Flags associated with this schema */
8244   int cache_size;      /* Number of pages to use in the cache */
8245 #ifndef SQLITE_OMIT_VIRTUALTABLE
8246   sqlite3 *db;         /* "Owner" connection. See comment above */
8247 #endif
8248 };
8249
8250 /*
8251 ** These macros can be used to test, set, or clear bits in the 
8252 ** Db.pSchema->flags field.
8253 */
8254 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->flags&(P))==(P))
8255 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->flags&(P))!=0)
8256 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->flags|=(P)
8257 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->flags&=~(P)
8258
8259 /*
8260 ** Allowed values for the DB.pSchema->flags field.
8261 **
8262 ** The DB_SchemaLoaded flag is set after the database schema has been
8263 ** read into internal hash tables.
8264 **
8265 ** DB_UnresetViews means that one or more views have column names that
8266 ** have been filled out.  If the schema changes, these column names might
8267 ** changes and so the view will need to be reset.
8268 */
8269 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
8270 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
8271 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
8272
8273 /*
8274 ** The number of different kinds of things that can be limited
8275 ** using the sqlite3_limit() interface.
8276 */
8277 #define SQLITE_N_LIMIT (SQLITE_LIMIT_TRIGGER_DEPTH+1)
8278
8279 /*
8280 ** Lookaside malloc is a set of fixed-size buffers that can be used
8281 ** to satisfy small transient memory allocation requests for objects
8282 ** associated with a particular database connection.  The use of
8283 ** lookaside malloc provides a significant performance enhancement
8284 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
8285 ** SQL statements.
8286 **
8287 ** The Lookaside structure holds configuration information about the
8288 ** lookaside malloc subsystem.  Each available memory allocation in
8289 ** the lookaside subsystem is stored on a linked list of LookasideSlot
8290 ** objects.
8291 **
8292 ** Lookaside allocations are only allowed for objects that are associated
8293 ** with a particular database connection.  Hence, schema information cannot
8294 ** be stored in lookaside because in shared cache mode the schema information
8295 ** is shared by multiple database connections.  Therefore, while parsing
8296 ** schema information, the Lookaside.bEnabled flag is cleared so that
8297 ** lookaside allocations are not used to construct the schema objects.
8298 */
8299 struct Lookaside {
8300   u16 sz;                 /* Size of each buffer in bytes */
8301   u8 bEnabled;            /* False to disable new lookaside allocations */
8302   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
8303   int nOut;               /* Number of buffers currently checked out */
8304   int mxOut;              /* Highwater mark for nOut */
8305   LookasideSlot *pFree;   /* List of available buffers */
8306   void *pStart;           /* First byte of available memory space */
8307   void *pEnd;             /* First byte past end of available space */
8308 };
8309 struct LookasideSlot {
8310   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
8311 };
8312
8313 /*
8314 ** A hash table for function definitions.
8315 **
8316 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
8317 ** Collisions are on the FuncDef.pHash chain.
8318 */
8319 struct FuncDefHash {
8320   FuncDef *a[23];       /* Hash table for functions */
8321 };
8322
8323 /*
8324 ** Each database connection is an instance of the following structure.
8325 **
8326 ** The sqlite.lastRowid records the last insert rowid generated by an
8327 ** insert statement.  Inserts on views do not affect its value.  Each
8328 ** trigger has its own context, so that lastRowid can be updated inside
8329 ** triggers as usual.  The previous value will be restored once the trigger
8330 ** exits.  Upon entering a before or instead of trigger, lastRowid is no
8331 ** longer (since after version 2.8.12) reset to -1.
8332 **
8333 ** The sqlite.nChange does not count changes within triggers and keeps no
8334 ** context.  It is reset at start of sqlite3_exec.
8335 ** The sqlite.lsChange represents the number of changes made by the last
8336 ** insert, update, or delete statement.  It remains constant throughout the
8337 ** length of a statement and is then updated by OP_SetCounts.  It keeps a
8338 ** context stack just like lastRowid so that the count of changes
8339 ** within a trigger is not seen outside the trigger.  Changes to views do not
8340 ** affect the value of lsChange.
8341 ** The sqlite.csChange keeps track of the number of current changes (since
8342 ** the last statement) and is used to update sqlite_lsChange.
8343 **
8344 ** The member variables sqlite.errCode, sqlite.zErrMsg and sqlite.zErrMsg16
8345 ** store the most recent error code and, if applicable, string. The
8346 ** internal function sqlite3Error() is used to set these variables
8347 ** consistently.
8348 */
8349 struct sqlite3 {
8350   sqlite3_vfs *pVfs;            /* OS Interface */
8351   int nDb;                      /* Number of backends currently in use */
8352   Db *aDb;                      /* All backends */
8353   int flags;                    /* Miscellaneous flags. See below */
8354   int openFlags;                /* Flags passed to sqlite3_vfs.xOpen() */
8355   int errCode;                  /* Most recent error code (SQLITE_*) */
8356   int errMask;                  /* & result codes with this before returning */
8357   u8 autoCommit;                /* The auto-commit flag. */
8358   u8 temp_store;                /* 1: file 2: memory 0: default */
8359   u8 mallocFailed;              /* True if we have seen a malloc failure */
8360   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
8361   u8 dfltJournalMode;           /* Default journal mode for attached dbs */
8362   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
8363   u8 suppressErr;               /* Do not issue error messages if true */
8364   int nextPagesize;             /* Pagesize after VACUUM if >0 */
8365   int nTable;                   /* Number of tables in the database */
8366   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
8367   i64 lastRowid;                /* ROWID of most recent insert (see above) */
8368   u32 magic;                    /* Magic number for detect library misuse */
8369   int nChange;                  /* Value returned by sqlite3_changes() */
8370   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
8371   sqlite3_mutex *mutex;         /* Connection mutex */
8372   int aLimit[SQLITE_N_LIMIT];   /* Limits */
8373   struct sqlite3InitInfo {      /* Information used during initialization */
8374     int iDb;                    /* When back is being initialized */
8375     int newTnum;                /* Rootpage of table being initialized */
8376     u8 busy;                    /* TRUE if currently initializing */
8377     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
8378   } init;
8379   int nExtension;               /* Number of loaded extensions */
8380   void **aExtension;            /* Array of shared library handles */
8381   struct Vdbe *pVdbe;           /* List of active virtual machines */
8382   int activeVdbeCnt;            /* Number of VDBEs currently executing */
8383   int writeVdbeCnt;             /* Number of active VDBEs that are writing */
8384   void (*xTrace)(void*,const char*);        /* Trace function */
8385   void *pTraceArg;                          /* Argument to the trace function */
8386   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
8387   void *pProfileArg;                        /* Argument to profile function */
8388   void *pCommitArg;                 /* Argument to xCommitCallback() */   
8389   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
8390   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
8391   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
8392   void *pUpdateArg;
8393   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
8394   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
8395   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
8396   void *pCollNeededArg;
8397   sqlite3_value *pErr;          /* Most recent error message */
8398   char *zErrMsg;                /* Most recent error message (UTF-8 encoded) */
8399   char *zErrMsg16;              /* Most recent error message (UTF-16 encoded) */
8400   union {
8401     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
8402     double notUsed1;            /* Spacer */
8403   } u1;
8404   Lookaside lookaside;          /* Lookaside malloc configuration */
8405 #ifndef SQLITE_OMIT_AUTHORIZATION
8406   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
8407                                 /* Access authorization function */
8408   void *pAuthArg;               /* 1st argument to the access auth function */
8409 #endif
8410 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
8411   int (*xProgress)(void *);     /* The progress callback */
8412   void *pProgressArg;           /* Argument to the progress callback */
8413   int nProgressOps;             /* Number of opcodes for progress callback */
8414 #endif
8415 #ifndef SQLITE_OMIT_VIRTUALTABLE
8416   Hash aModule;                 /* populated by sqlite3_create_module() */
8417   Table *pVTab;                 /* vtab with active Connect/Create method */
8418   VTable **aVTrans;             /* Virtual tables with open transactions */
8419   int nVTrans;                  /* Allocated size of aVTrans */
8420   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
8421 #endif
8422   FuncDefHash aFunc;            /* Hash table of connection functions */
8423   Hash aCollSeq;                /* All collating sequences */
8424   BusyHandler busyHandler;      /* Busy callback */
8425   int busyTimeout;              /* Busy handler timeout, in msec */
8426   Db aDbStatic[2];              /* Static space for the 2 default backends */
8427   Savepoint *pSavepoint;        /* List of active savepoints */
8428   int nSavepoint;               /* Number of non-transaction savepoints */
8429   int nStatement;               /* Number of nested statement-transactions  */
8430   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
8431   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
8432
8433 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
8434   /* The following variables are all protected by the STATIC_MASTER 
8435   ** mutex, not by sqlite3.mutex. They are used by code in notify.c. 
8436   **
8437   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
8438   ** unlock so that it can proceed.
8439   **
8440   ** When X.pBlockingConnection==Y, that means that something that X tried
8441   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
8442   ** held by Y.
8443   */
8444   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
8445   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
8446   void *pUnlockArg;                     /* Argument to xUnlockNotify */
8447   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
8448   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
8449 #endif
8450 };
8451
8452 /*
8453 ** A macro to discover the encoding of a database.
8454 */
8455 #define ENC(db) ((db)->aDb[0].pSchema->enc)
8456
8457 /*
8458 ** Possible values for the sqlite3.flags.
8459 */
8460 #define SQLITE_VdbeTrace      0x00000100  /* True to trace VDBE execution */
8461 #define SQLITE_InternChanges  0x00000200  /* Uncommitted Hash table changes */
8462 #define SQLITE_FullColNames   0x00000400  /* Show full column names on SELECT */
8463 #define SQLITE_ShortColNames  0x00000800  /* Show short columns names */
8464 #define SQLITE_CountRows      0x00001000  /* Count rows changed by INSERT, */
8465                                           /*   DELETE, or UPDATE and return */
8466                                           /*   the count using a callback. */
8467 #define SQLITE_NullCallback   0x00002000  /* Invoke the callback once if the */
8468                                           /*   result set is empty */
8469 #define SQLITE_SqlTrace       0x00004000  /* Debug print SQL as it executes */
8470 #define SQLITE_VdbeListing    0x00008000  /* Debug listings of VDBE programs */
8471 #define SQLITE_WriteSchema    0x00010000  /* OK to update SQLITE_MASTER */
8472 #define SQLITE_NoReadlock     0x00020000  /* Readlocks are omitted when 
8473                                           ** accessing read-only databases */
8474 #define SQLITE_IgnoreChecks   0x00040000  /* Do not enforce check constraints */
8475 #define SQLITE_ReadUncommitted 0x0080000  /* For shared-cache mode */
8476 #define SQLITE_LegacyFileFmt  0x00100000  /* Create new databases in format 1 */
8477 #define SQLITE_FullFSync      0x00200000  /* Use full fsync on the backend */
8478 #define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
8479 #define SQLITE_RecoveryMode   0x00800000  /* Ignore schema errors */
8480 #define SQLITE_ReverseOrder   0x01000000  /* Reverse unordered SELECTs */
8481 #define SQLITE_RecTriggers    0x02000000  /* Enable recursive triggers */
8482 #define SQLITE_ForeignKeys    0x04000000  /* Enforce foreign key constraints  */
8483
8484 /*
8485 ** Bits of the sqlite3.flags field that are used by the
8486 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface.
8487 ** These must be the low-order bits of the flags field.
8488 */
8489 #define SQLITE_QueryFlattener 0x01        /* Disable query flattening */
8490 #define SQLITE_ColumnCache    0x02        /* Disable the column cache */
8491 #define SQLITE_IndexSort      0x04        /* Disable indexes for sorting */
8492 #define SQLITE_IndexSearch    0x08        /* Disable indexes for searching */
8493 #define SQLITE_IndexCover     0x10        /* Disable index covering table */
8494 #define SQLITE_OptMask        0x1f        /* Mask of all disablable opts */
8495
8496 /*
8497 ** Possible values for the sqlite.magic field.
8498 ** The numbers are obtained at random and have no special meaning, other
8499 ** than being distinct from one another.
8500 */
8501 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
8502 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
8503 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
8504 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
8505 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
8506
8507 /*
8508 ** Each SQL function is defined by an instance of the following
8509 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
8510 ** hash table.  When multiple functions have the same name, the hash table
8511 ** points to a linked list of these structures.
8512 */
8513 struct FuncDef {
8514   i16 nArg;            /* Number of arguments.  -1 means unlimited */
8515   u8 iPrefEnc;         /* Preferred text encoding (SQLITE_UTF8, 16LE, 16BE) */
8516   u8 flags;            /* Some combination of SQLITE_FUNC_* */
8517   void *pUserData;     /* User data parameter */
8518   FuncDef *pNext;      /* Next function with same name */
8519   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
8520   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
8521   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
8522   char *zName;         /* SQL name of the function. */
8523   FuncDef *pHash;      /* Next with a different name but the same hash */
8524 };
8525
8526 /*
8527 ** Possible values for FuncDef.flags
8528 */
8529 #define SQLITE_FUNC_LIKE     0x01 /* Candidate for the LIKE optimization */
8530 #define SQLITE_FUNC_CASE     0x02 /* Case-sensitive LIKE-type function */
8531 #define SQLITE_FUNC_EPHEM    0x04 /* Ephemeral.  Delete with VDBE */
8532 #define SQLITE_FUNC_NEEDCOLL 0x08 /* sqlite3GetFuncCollSeq() might be called */
8533 #define SQLITE_FUNC_PRIVATE  0x10 /* Allowed for internal use only */
8534 #define SQLITE_FUNC_COUNT    0x20 /* Built-in count(*) aggregate */
8535 #define SQLITE_FUNC_COALESCE 0x40 /* Built-in coalesce() or ifnull() function */
8536
8537 /*
8538 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
8539 ** used to create the initializers for the FuncDef structures.
8540 **
8541 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
8542 **     Used to create a scalar function definition of a function zName 
8543 **     implemented by C function xFunc that accepts nArg arguments. The
8544 **     value passed as iArg is cast to a (void*) and made available
8545 **     as the user-data (sqlite3_user_data()) for the function. If 
8546 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
8547 **
8548 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
8549 **     Used to create an aggregate function definition implemented by
8550 **     the C functions xStep and xFinal. The first four parameters
8551 **     are interpreted in the same way as the first 4 parameters to
8552 **     FUNCTION().
8553 **
8554 **   LIKEFUNC(zName, nArg, pArg, flags)
8555 **     Used to create a scalar function definition of a function zName 
8556 **     that accepts nArg arguments and is implemented by a call to C 
8557 **     function likeFunc. Argument pArg is cast to a (void *) and made
8558 **     available as the function user-data (sqlite3_user_data()). The
8559 **     FuncDef.flags variable is set to the value passed as the flags
8560 **     parameter.
8561 */
8562 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
8563   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8564    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0}
8565 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
8566   {nArg, SQLITE_UTF8, bNC*SQLITE_FUNC_NEEDCOLL, \
8567    pArg, 0, xFunc, 0, 0, #zName, 0}
8568 #define LIKEFUNC(zName, nArg, arg, flags) \
8569   {nArg, SQLITE_UTF8, flags, (void *)arg, 0, likeFunc, 0, 0, #zName, 0}
8570 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
8571   {nArg, SQLITE_UTF8, nc*SQLITE_FUNC_NEEDCOLL, \
8572    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0}
8573
8574 /*
8575 ** All current savepoints are stored in a linked list starting at
8576 ** sqlite3.pSavepoint. The first element in the list is the most recently
8577 ** opened savepoint. Savepoints are added to the list by the vdbe
8578 ** OP_Savepoint instruction.
8579 */
8580 struct Savepoint {
8581   char *zName;                        /* Savepoint name (nul-terminated) */
8582   i64 nDeferredCons;                  /* Number of deferred fk violations */
8583   Savepoint *pNext;                   /* Parent savepoint (if any) */
8584 };
8585
8586 /*
8587 ** The following are used as the second parameter to sqlite3Savepoint(),
8588 ** and as the P1 argument to the OP_Savepoint instruction.
8589 */
8590 #define SAVEPOINT_BEGIN      0
8591 #define SAVEPOINT_RELEASE    1
8592 #define SAVEPOINT_ROLLBACK   2
8593
8594
8595 /*
8596 ** Each SQLite module (virtual table definition) is defined by an
8597 ** instance of the following structure, stored in the sqlite3.aModule
8598 ** hash table.
8599 */
8600 struct Module {
8601   const sqlite3_module *pModule;       /* Callback pointers */
8602   const char *zName;                   /* Name passed to create_module() */
8603   void *pAux;                          /* pAux passed to create_module() */
8604   void (*xDestroy)(void *);            /* Module destructor function */
8605 };
8606
8607 /*
8608 ** information about each column of an SQL table is held in an instance
8609 ** of this structure.
8610 */
8611 struct Column {
8612   char *zName;     /* Name of this column */
8613   Expr *pDflt;     /* Default value of this column */
8614   char *zDflt;     /* Original text of the default value */
8615   char *zType;     /* Data type for this column */
8616   char *zColl;     /* Collating sequence.  If NULL, use the default */
8617   u8 notNull;      /* True if there is a NOT NULL constraint */
8618   u8 isPrimKey;    /* True if this column is part of the PRIMARY KEY */
8619   char affinity;   /* One of the SQLITE_AFF_... values */
8620 #ifndef SQLITE_OMIT_VIRTUALTABLE
8621   u8 isHidden;     /* True if this column is 'hidden' */
8622 #endif
8623 };
8624
8625 /*
8626 ** A "Collating Sequence" is defined by an instance of the following
8627 ** structure. Conceptually, a collating sequence consists of a name and
8628 ** a comparison routine that defines the order of that sequence.
8629 **
8630 ** There may two separate implementations of the collation function, one
8631 ** that processes text in UTF-8 encoding (CollSeq.xCmp) and another that
8632 ** processes text encoded in UTF-16 (CollSeq.xCmp16), using the machine
8633 ** native byte order. When a collation sequence is invoked, SQLite selects
8634 ** the version that will require the least expensive encoding
8635 ** translations, if any.
8636 **
8637 ** The CollSeq.pUser member variable is an extra parameter that passed in
8638 ** as the first argument to the UTF-8 comparison function, xCmp.
8639 ** CollSeq.pUser16 is the equivalent for the UTF-16 comparison function,
8640 ** xCmp16.
8641 **
8642 ** If both CollSeq.xCmp and CollSeq.xCmp16 are NULL, it means that the
8643 ** collating sequence is undefined.  Indices built on an undefined
8644 ** collating sequence may not be read or written.
8645 */
8646 struct CollSeq {
8647   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
8648   u8 enc;               /* Text encoding handled by xCmp() */
8649   u8 type;              /* One of the SQLITE_COLL_... values below */
8650   void *pUser;          /* First argument to xCmp() */
8651   int (*xCmp)(void*,int, const void*, int, const void*);
8652   void (*xDel)(void*);  /* Destructor for pUser */
8653 };
8654
8655 /*
8656 ** Allowed values of CollSeq.type:
8657 */
8658 #define SQLITE_COLL_BINARY  1  /* The default memcmp() collating sequence */
8659 #define SQLITE_COLL_NOCASE  2  /* The built-in NOCASE collating sequence */
8660 #define SQLITE_COLL_REVERSE 3  /* The built-in REVERSE collating sequence */
8661 #define SQLITE_COLL_USER    0  /* Any other user-defined collating sequence */
8662
8663 /*
8664 ** A sort order can be either ASC or DESC.
8665 */
8666 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
8667 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
8668
8669 /*
8670 ** Column affinity types.
8671 **
8672 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
8673 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
8674 ** the speed a little by numbering the values consecutively.  
8675 **
8676 ** But rather than start with 0 or 1, we begin with 'a'.  That way,
8677 ** when multiple affinity types are concatenated into a string and
8678 ** used as the P4 operand, they will be more readable.
8679 **
8680 ** Note also that the numeric types are grouped together so that testing
8681 ** for a numeric type is a single comparison.
8682 */
8683 #define SQLITE_AFF_TEXT     'a'
8684 #define SQLITE_AFF_NONE     'b'
8685 #define SQLITE_AFF_NUMERIC  'c'
8686 #define SQLITE_AFF_INTEGER  'd'
8687 #define SQLITE_AFF_REAL     'e'
8688
8689 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
8690
8691 /*
8692 ** The SQLITE_AFF_MASK values masks off the significant bits of an
8693 ** affinity value. 
8694 */
8695 #define SQLITE_AFF_MASK     0x67
8696
8697 /*
8698 ** Additional bit values that can be ORed with an affinity without
8699 ** changing the affinity.
8700 */
8701 #define SQLITE_JUMPIFNULL   0x08  /* jumps if either operand is NULL */
8702 #define SQLITE_STOREP2      0x10  /* Store result in reg[P2] rather than jump */
8703 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
8704
8705 /*
8706 ** An object of this type is created for each virtual table present in
8707 ** the database schema. 
8708 **
8709 ** If the database schema is shared, then there is one instance of this
8710 ** structure for each database connection (sqlite3*) that uses the shared
8711 ** schema. This is because each database connection requires its own unique
8712 ** instance of the sqlite3_vtab* handle used to access the virtual table 
8713 ** implementation. sqlite3_vtab* handles can not be shared between 
8714 ** database connections, even when the rest of the in-memory database 
8715 ** schema is shared, as the implementation often stores the database
8716 ** connection handle passed to it via the xConnect() or xCreate() method
8717 ** during initialization internally. This database connection handle may
8718 ** then used by the virtual table implementation to access real tables 
8719 ** within the database. So that they appear as part of the callers 
8720 ** transaction, these accesses need to be made via the same database 
8721 ** connection as that used to execute SQL operations on the virtual table.
8722 **
8723 ** All VTable objects that correspond to a single table in a shared
8724 ** database schema are initially stored in a linked-list pointed to by
8725 ** the Table.pVTable member variable of the corresponding Table object.
8726 ** When an sqlite3_prepare() operation is required to access the virtual
8727 ** table, it searches the list for the VTable that corresponds to the
8728 ** database connection doing the preparing so as to use the correct
8729 ** sqlite3_vtab* handle in the compiled query.
8730 **
8731 ** When an in-memory Table object is deleted (for example when the
8732 ** schema is being reloaded for some reason), the VTable objects are not 
8733 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed 
8734 ** immediately. Instead, they are moved from the Table.pVTable list to
8735 ** another linked list headed by the sqlite3.pDisconnect member of the
8736 ** corresponding sqlite3 structure. They are then deleted/xDisconnected 
8737 ** next time a statement is prepared using said sqlite3*. This is done
8738 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
8739 ** Refer to comments above function sqlite3VtabUnlockList() for an
8740 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
8741 ** list without holding the corresponding sqlite3.mutex mutex.
8742 **
8743 ** The memory for objects of this type is always allocated by 
8744 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as 
8745 ** the first argument.
8746 */
8747 struct VTable {
8748   sqlite3 *db;              /* Database connection associated with this table */
8749   Module *pMod;             /* Pointer to module implementation */
8750   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
8751   int nRef;                 /* Number of pointers to this structure */
8752   VTable *pNext;            /* Next in linked list (see above) */
8753 };
8754
8755 /*
8756 ** Each SQL table is represented in memory by an instance of the
8757 ** following structure.
8758 **
8759 ** Table.zName is the name of the table.  The case of the original
8760 ** CREATE TABLE statement is stored, but case is not significant for
8761 ** comparisons.
8762 **
8763 ** Table.nCol is the number of columns in this table.  Table.aCol is a
8764 ** pointer to an array of Column structures, one for each column.
8765 **
8766 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
8767 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
8768 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
8769 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
8770 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
8771 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
8772 ** the table has any PRIMARY KEY, INTEGER or otherwise.
8773 **
8774 ** Table.tnum is the page number for the root BTree page of the table in the
8775 ** database file.  If Table.iDb is the index of the database table backend
8776 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
8777 ** holds temporary tables and indices.  If TF_Ephemeral is set
8778 ** then the table is stored in a file that is automatically deleted
8779 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
8780 ** refers VDBE cursor number that holds the table open, not to the root
8781 ** page number.  Transient tables are used to hold the results of a
8782 ** sub-query that appears instead of a real table name in the FROM clause 
8783 ** of a SELECT statement.
8784 */
8785 struct Table {
8786   sqlite3 *dbMem;      /* DB connection used for lookaside allocations. */
8787   char *zName;         /* Name of the table or view */
8788   int iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
8789   int nCol;            /* Number of columns in this table */
8790   Column *aCol;        /* Information about each column */
8791   Index *pIndex;       /* List of SQL indexes on this table. */
8792   int tnum;            /* Root BTree node for this table (see note above) */
8793   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
8794   u16 nRef;            /* Number of pointers to this Table */
8795   u8 tabFlags;         /* Mask of TF_* values */
8796   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
8797   FKey *pFKey;         /* Linked list of all foreign keys in this table */
8798   char *zColAff;       /* String defining the affinity of each column */
8799 #ifndef SQLITE_OMIT_CHECK
8800   Expr *pCheck;        /* The AND of all CHECK constraints */
8801 #endif
8802 #ifndef SQLITE_OMIT_ALTERTABLE
8803   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
8804 #endif
8805 #ifndef SQLITE_OMIT_VIRTUALTABLE
8806   VTable *pVTable;     /* List of VTable objects. */
8807   int nModuleArg;      /* Number of arguments to the module */
8808   char **azModuleArg;  /* Text of all module args. [0] is module name */
8809 #endif
8810   Trigger *pTrigger;   /* List of triggers stored in pSchema */
8811   Schema *pSchema;     /* Schema that contains this table */
8812   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
8813 };
8814
8815 /*
8816 ** Allowed values for Tabe.tabFlags.
8817 */
8818 #define TF_Readonly        0x01    /* Read-only system table */
8819 #define TF_Ephemeral       0x02    /* An ephemeral table */
8820 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
8821 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
8822 #define TF_Virtual         0x10    /* Is a virtual table */
8823 #define TF_NeedMetadata    0x20    /* aCol[].zType and aCol[].pColl missing */
8824
8825
8826
8827 /*
8828 ** Test to see whether or not a table is a virtual table.  This is
8829 ** done as a macro so that it will be optimized out when virtual
8830 ** table support is omitted from the build.
8831 */
8832 #ifndef SQLITE_OMIT_VIRTUALTABLE
8833 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
8834 #  define IsHiddenColumn(X) ((X)->isHidden)
8835 #else
8836 #  define IsVirtual(X)      0
8837 #  define IsHiddenColumn(X) 0
8838 #endif
8839
8840 /*
8841 ** Each foreign key constraint is an instance of the following structure.
8842 **
8843 ** A foreign key is associated with two tables.  The "from" table is
8844 ** the table that contains the REFERENCES clause that creates the foreign
8845 ** key.  The "to" table is the table that is named in the REFERENCES clause.
8846 ** Consider this example:
8847 **
8848 **     CREATE TABLE ex1(
8849 **       a INTEGER PRIMARY KEY,
8850 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
8851 **     );
8852 **
8853 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
8854 **
8855 ** Each REFERENCES clause generates an instance of the following structure
8856 ** which is attached to the from-table.  The to-table need not exist when
8857 ** the from-table is created.  The existence of the to-table is not checked.
8858 */
8859 struct FKey {
8860   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
8861   FKey *pNextFrom;  /* Next foreign key in pFrom */
8862   char *zTo;        /* Name of table that the key points to (aka: Parent) */
8863   FKey *pNextTo;    /* Next foreign key on table named zTo */
8864   FKey *pPrevTo;    /* Previous foreign key on table named zTo */
8865   int nCol;         /* Number of columns in this key */
8866   /* EV: R-30323-21917 */
8867   u8 isDeferred;    /* True if constraint checking is deferred till COMMIT */
8868   u8 aAction[2];          /* ON DELETE and ON UPDATE actions, respectively */
8869   Trigger *apTrigger[2];  /* Triggers for aAction[] actions */
8870   struct sColMap {  /* Mapping of columns in pFrom to columns in zTo */
8871     int iFrom;         /* Index of column in pFrom */
8872     char *zCol;        /* Name of column in zTo.  If 0 use PRIMARY KEY */
8873   } aCol[1];        /* One entry for each of nCol column s */
8874 };
8875
8876 /*
8877 ** SQLite supports many different ways to resolve a constraint
8878 ** error.  ROLLBACK processing means that a constraint violation
8879 ** causes the operation in process to fail and for the current transaction
8880 ** to be rolled back.  ABORT processing means the operation in process
8881 ** fails and any prior changes from that one operation are backed out,
8882 ** but the transaction is not rolled back.  FAIL processing means that
8883 ** the operation in progress stops and returns an error code.  But prior
8884 ** changes due to the same operation are not backed out and no rollback
8885 ** occurs.  IGNORE means that the particular row that caused the constraint
8886 ** error is not inserted or updated.  Processing continues and no error
8887 ** is returned.  REPLACE means that preexisting database rows that caused
8888 ** a UNIQUE constraint violation are removed so that the new insert or
8889 ** update can proceed.  Processing continues and no error is reported.
8890 **
8891 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
8892 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
8893 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
8894 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
8895 ** referenced table row is propagated into the row that holds the
8896 ** foreign key.
8897 ** 
8898 ** The following symbolic values are used to record which type
8899 ** of action to take.
8900 */
8901 #define OE_None     0   /* There is no constraint to check */
8902 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
8903 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
8904 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
8905 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
8906 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
8907
8908 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
8909 #define OE_SetNull  7   /* Set the foreign key value to NULL */
8910 #define OE_SetDflt  8   /* Set the foreign key value to its default */
8911 #define OE_Cascade  9   /* Cascade the changes */
8912
8913 #define OE_Default  99  /* Do whatever the default action is */
8914
8915
8916 /*
8917 ** An instance of the following structure is passed as the first
8918 ** argument to sqlite3VdbeKeyCompare and is used to control the 
8919 ** comparison of the two index keys.
8920 */
8921 struct KeyInfo {
8922   sqlite3 *db;        /* The database connection */
8923   u8 enc;             /* Text encoding - one of the TEXT_Utf* values */
8924   u16 nField;         /* Number of entries in aColl[] */
8925   u8 *aSortOrder;     /* If defined an aSortOrder[i] is true, sort DESC */
8926   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
8927 };
8928
8929 /*
8930 ** An instance of the following structure holds information about a
8931 ** single index record that has already been parsed out into individual
8932 ** values.
8933 **
8934 ** A record is an object that contains one or more fields of data.
8935 ** Records are used to store the content of a table row and to store
8936 ** the key of an index.  A blob encoding of a record is created by
8937 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
8938 ** OP_Column opcode.
8939 **
8940 ** This structure holds a record that has already been disassembled
8941 ** into its constituent fields.
8942 */
8943 struct UnpackedRecord {
8944   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
8945   u16 nField;         /* Number of entries in apMem[] */
8946   u16 flags;          /* Boolean settings.  UNPACKED_... below */
8947   i64 rowid;          /* Used by UNPACKED_PREFIX_SEARCH */
8948   Mem *aMem;          /* Values */
8949 };
8950
8951 /*
8952 ** Allowed values of UnpackedRecord.flags
8953 */
8954 #define UNPACKED_NEED_FREE     0x0001  /* Memory is from sqlite3Malloc() */
8955 #define UNPACKED_NEED_DESTROY  0x0002  /* apMem[]s should all be destroyed */
8956 #define UNPACKED_IGNORE_ROWID  0x0004  /* Ignore trailing rowid on key1 */
8957 #define UNPACKED_INCRKEY       0x0008  /* Make this key an epsilon larger */
8958 #define UNPACKED_PREFIX_MATCH  0x0010  /* A prefix match is considered OK */
8959 #define UNPACKED_PREFIX_SEARCH 0x0020  /* A prefix match is considered OK */
8960
8961 /*
8962 ** Each SQL index is represented in memory by an
8963 ** instance of the following structure.
8964 **
8965 ** The columns of the table that are to be indexed are described
8966 ** by the aiColumn[] field of this structure.  For example, suppose
8967 ** we have the following table and index:
8968 **
8969 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
8970 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
8971 **
8972 ** In the Table structure describing Ex1, nCol==3 because there are
8973 ** three columns in the table.  In the Index structure describing
8974 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
8975 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
8976 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
8977 ** The second column to be indexed (c1) has an index of 0 in
8978 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
8979 **
8980 ** The Index.onError field determines whether or not the indexed columns
8981 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
8982 ** it means this is not a unique index.  Otherwise it is a unique index
8983 ** and the value of Index.onError indicate the which conflict resolution 
8984 ** algorithm to employ whenever an attempt is made to insert a non-unique
8985 ** element.
8986 */
8987 struct Index {
8988   char *zName;     /* Name of this index */
8989   int nColumn;     /* Number of columns in the table used by this index */
8990   int *aiColumn;   /* Which columns are used by this index.  1st is 0 */
8991   unsigned *aiRowEst; /* Result of ANALYZE: Est. rows selected by each column */
8992   Table *pTable;   /* The SQL table being indexed */
8993   int tnum;        /* Page containing root of this index in database file */
8994   u8 onError;      /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
8995   u8 autoIndex;    /* True if is automatically created (ex: by UNIQUE) */
8996   char *zColAff;   /* String defining the affinity of each column */
8997   Index *pNext;    /* The next index associated with the same table */
8998   Schema *pSchema; /* Schema containing this index */
8999   u8 *aSortOrder;  /* Array of size Index.nColumn. True==DESC, False==ASC */
9000   char **azColl;   /* Array of collation sequence names for index */
9001   IndexSample *aSample;    /* Array of SQLITE_INDEX_SAMPLES samples */
9002 };
9003
9004 /*
9005 ** Each sample stored in the sqlite_stat2 table is represented in memory 
9006 ** using a structure of this type.
9007 */
9008 struct IndexSample {
9009   union {
9010     char *z;        /* Value if eType is SQLITE_TEXT or SQLITE_BLOB */
9011     double r;       /* Value if eType is SQLITE_FLOAT or SQLITE_INTEGER */
9012   } u;
9013   u8 eType;         /* SQLITE_NULL, SQLITE_INTEGER ... etc. */
9014   u8 nByte;         /* Size in byte of text or blob. */
9015 };
9016
9017 /*
9018 ** Each token coming out of the lexer is an instance of
9019 ** this structure.  Tokens are also used as part of an expression.
9020 **
9021 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
9022 ** may contain random values.  Do not make any assumptions about Token.dyn
9023 ** and Token.n when Token.z==0.
9024 */
9025 struct Token {
9026   const char *z;     /* Text of the token.  Not NULL-terminated! */
9027   unsigned int n;    /* Number of characters in this token */
9028 };
9029
9030 /*
9031 ** An instance of this structure contains information needed to generate
9032 ** code for a SELECT that contains aggregate functions.
9033 **
9034 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
9035 ** pointer to this structure.  The Expr.iColumn field is the index in
9036 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
9037 ** code for that node.
9038 **
9039 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
9040 ** original Select structure that describes the SELECT statement.  These
9041 ** fields do not need to be freed when deallocating the AggInfo structure.
9042 */
9043 struct AggInfo {
9044   u8 directMode;          /* Direct rendering mode means take data directly
9045                           ** from source tables rather than from accumulators */
9046   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
9047                           ** than the source table */
9048   int sortingIdx;         /* Cursor number of the sorting index */
9049   ExprList *pGroupBy;     /* The group by clause */
9050   int nSortingColumn;     /* Number of columns in the sorting index */
9051   struct AggInfo_col {    /* For each column used in source tables */
9052     Table *pTab;             /* Source table */
9053     int iTable;              /* Cursor number of the source table */
9054     int iColumn;             /* Column number within the source table */
9055     int iSorterColumn;       /* Column number in the sorting index */
9056     int iMem;                /* Memory location that acts as accumulator */
9057     Expr *pExpr;             /* The original expression */
9058   } *aCol;
9059   int nColumn;            /* Number of used entries in aCol[] */
9060   int nColumnAlloc;       /* Number of slots allocated for aCol[] */
9061   int nAccumulator;       /* Number of columns that show through to the output.
9062                           ** Additional columns are used only as parameters to
9063                           ** aggregate functions */
9064   struct AggInfo_func {   /* For each aggregate function */
9065     Expr *pExpr;             /* Expression encoding the function */
9066     FuncDef *pFunc;          /* The aggregate function implementation */
9067     int iMem;                /* Memory location that acts as accumulator */
9068     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
9069   } *aFunc;
9070   int nFunc;              /* Number of entries in aFunc[] */
9071   int nFuncAlloc;         /* Number of slots allocated for aFunc[] */
9072 };
9073
9074 /*
9075 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
9076 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
9077 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
9078 ** it uses less memory in the Expr object, which is a big memory user
9079 ** in systems with lots of prepared statements.  And few applications
9080 ** need more than about 10 or 20 variables.  But some extreme users want
9081 ** to have prepared statements with over 32767 variables, and for them
9082 ** the option is available (at compile-time).
9083 */
9084 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
9085 typedef i16 ynVar;
9086 #else
9087 typedef int ynVar;
9088 #endif
9089
9090 /*
9091 ** Each node of an expression in the parse tree is an instance
9092 ** of this structure.
9093 **
9094 ** Expr.op is the opcode. The integer parser token codes are reused
9095 ** as opcodes here. For example, the parser defines TK_GE to be an integer
9096 ** code representing the ">=" operator. This same integer code is reused
9097 ** to represent the greater-than-or-equal-to operator in the expression
9098 ** tree.
9099 **
9100 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, 
9101 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
9102 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the 
9103 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
9104 ** then Expr.token contains the name of the function.
9105 **
9106 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
9107 ** binary operator. Either or both may be NULL.
9108 **
9109 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
9110 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
9111 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
9112 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
9113 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is 
9114 ** valid.
9115 **
9116 ** An expression of the form ID or ID.ID refers to a column in a table.
9117 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
9118 ** the integer cursor number of a VDBE cursor pointing to that table and
9119 ** Expr.iColumn is the column number for the specific column.  If the
9120 ** expression is used as a result in an aggregate SELECT, then the
9121 ** value is also stored in the Expr.iAgg column in the aggregate so that
9122 ** it can be accessed after all aggregates are computed.
9123 **
9124 ** If the expression is an unbound variable marker (a question mark 
9125 ** character '?' in the original SQL) then the Expr.iTable holds the index 
9126 ** number for that variable.
9127 **
9128 ** If the expression is a subquery then Expr.iColumn holds an integer
9129 ** register number containing the result of the subquery.  If the
9130 ** subquery gives a constant result, then iTable is -1.  If the subquery
9131 ** gives a different answer at different times during statement processing
9132 ** then iTable is the address of a subroutine that computes the subquery.
9133 **
9134 ** If the Expr is of type OP_Column, and the table it is selecting from
9135 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
9136 ** corresponding table definition.
9137 **
9138 ** ALLOCATION NOTES:
9139 **
9140 ** Expr objects can use a lot of memory space in database schema.  To
9141 ** help reduce memory requirements, sometimes an Expr object will be
9142 ** truncated.  And to reduce the number of memory allocations, sometimes
9143 ** two or more Expr objects will be stored in a single memory allocation,
9144 ** together with Expr.zToken strings.
9145 **
9146 ** If the EP_Reduced and EP_TokenOnly flags are set when
9147 ** an Expr object is truncated.  When EP_Reduced is set, then all
9148 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
9149 ** are contained within the same memory allocation.  Note, however, that
9150 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
9151 ** allocated, regardless of whether or not EP_Reduced is set.
9152 */
9153 struct Expr {
9154   u8 op;                 /* Operation performed by this node */
9155   char affinity;         /* The affinity of the column or 0 if not a column */
9156   u16 flags;             /* Various flags.  EP_* See below */
9157   union {
9158     char *zToken;          /* Token value. Zero terminated and dequoted */
9159     int iValue;            /* Integer value if EP_IntValue */
9160   } u;
9161
9162   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
9163   ** space is allocated for the fields below this point. An attempt to
9164   ** access them will result in a segfault or malfunction. 
9165   *********************************************************************/
9166
9167   Expr *pLeft;           /* Left subnode */
9168   Expr *pRight;          /* Right subnode */
9169   union {
9170     ExprList *pList;     /* Function arguments or in "<expr> IN (<expr-list)" */
9171     Select *pSelect;     /* Used for sub-selects and "<expr> IN (<select>)" */
9172   } x;
9173   CollSeq *pColl;        /* The collation type of the column or 0 */
9174
9175   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
9176   ** space is allocated for the fields below this point. An attempt to
9177   ** access them will result in a segfault or malfunction.
9178   *********************************************************************/
9179
9180   int iTable;            /* TK_COLUMN: cursor number of table holding column
9181                          ** TK_REGISTER: register number
9182                          ** TK_TRIGGER: 1 -> new, 0 -> old */
9183   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
9184                          ** TK_VARIABLE: variable number (always >= 1). */
9185   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
9186   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
9187   u8 flags2;             /* Second set of flags.  EP2_... */
9188   u8 op2;                /* If a TK_REGISTER, the original value of Expr.op */
9189   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
9190   Table *pTab;           /* Table for TK_COLUMN expressions. */
9191 #if SQLITE_MAX_EXPR_DEPTH>0
9192   int nHeight;           /* Height of the tree headed by this node */
9193 #endif
9194 };
9195
9196 /*
9197 ** The following are the meanings of bits in the Expr.flags field.
9198 */
9199 #define EP_FromJoin   0x0001  /* Originated in ON or USING clause of a join */
9200 #define EP_Agg        0x0002  /* Contains one or more aggregate functions */
9201 #define EP_Resolved   0x0004  /* IDs have been resolved to COLUMNs */
9202 #define EP_Error      0x0008  /* Expression contains one or more errors */
9203 #define EP_Distinct   0x0010  /* Aggregate function with DISTINCT keyword */
9204 #define EP_VarSelect  0x0020  /* pSelect is correlated, not constant */
9205 #define EP_DblQuoted  0x0040  /* token.z was originally in "..." */
9206 #define EP_InfixFunc  0x0080  /* True for an infix function: LIKE, GLOB, etc */
9207 #define EP_ExpCollate 0x0100  /* Collating sequence specified explicitly */
9208 #define EP_FixedDest  0x0200  /* Result needed in a specific register */
9209 #define EP_IntValue   0x0400  /* Integer value contained in u.iValue */
9210 #define EP_xIsSelect  0x0800  /* x.pSelect is valid (otherwise x.pList is) */
9211
9212 #define EP_Reduced    0x1000  /* Expr struct is EXPR_REDUCEDSIZE bytes only */
9213 #define EP_TokenOnly  0x2000  /* Expr struct is EXPR_TOKENONLYSIZE bytes only */
9214 #define EP_Static     0x4000  /* Held in memory not obtained from malloc() */
9215
9216 /*
9217 ** The following are the meanings of bits in the Expr.flags2 field.
9218 */
9219 #define EP2_MallocedToken  0x0001  /* Need to sqlite3DbFree() Expr.zToken */
9220 #define EP2_Irreducible    0x0002  /* Cannot EXPRDUP_REDUCE this Expr */
9221
9222 /*
9223 ** The pseudo-routine sqlite3ExprSetIrreducible sets the EP2_Irreducible
9224 ** flag on an expression structure.  This flag is used for VV&A only.  The
9225 ** routine is implemented as a macro that only works when in debugging mode,
9226 ** so as not to burden production code.
9227 */
9228 #ifdef SQLITE_DEBUG
9229 # define ExprSetIrreducible(X)  (X)->flags2 |= EP2_Irreducible
9230 #else
9231 # define ExprSetIrreducible(X)
9232 #endif
9233
9234 /*
9235 ** These macros can be used to test, set, or clear bits in the 
9236 ** Expr.flags field.
9237 */
9238 #define ExprHasProperty(E,P)     (((E)->flags&(P))==(P))
9239 #define ExprHasAnyProperty(E,P)  (((E)->flags&(P))!=0)
9240 #define ExprSetProperty(E,P)     (E)->flags|=(P)
9241 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
9242
9243 /*
9244 ** Macros to determine the number of bytes required by a normal Expr 
9245 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags 
9246 ** and an Expr struct with the EP_TokenOnly flag set.
9247 */
9248 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
9249 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
9250 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
9251
9252 /*
9253 ** Flags passed to the sqlite3ExprDup() function. See the header comment 
9254 ** above sqlite3ExprDup() for details.
9255 */
9256 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
9257
9258 /*
9259 ** A list of expressions.  Each expression may optionally have a
9260 ** name.  An expr/name combination can be used in several ways, such
9261 ** as the list of "expr AS ID" fields following a "SELECT" or in the
9262 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
9263 ** also be used as the argument to a function, in which case the a.zName
9264 ** field is not used.
9265 */
9266 struct ExprList {
9267   int nExpr;             /* Number of expressions on the list */
9268   int nAlloc;            /* Number of entries allocated below */
9269   int iECursor;          /* VDBE Cursor associated with this ExprList */
9270   struct ExprList_item {
9271     Expr *pExpr;           /* The list of expressions */
9272     char *zName;           /* Token associated with this expression */
9273     char *zSpan;           /* Original text of the expression */
9274     u8 sortOrder;          /* 1 for DESC or 0 for ASC */
9275     u8 done;               /* A flag to indicate when processing is finished */
9276     u16 iCol;              /* For ORDER BY, column number in result set */
9277     u16 iAlias;            /* Index into Parse.aAlias[] for zName */
9278   } *a;                  /* One entry for each expression */
9279 };
9280
9281 /*
9282 ** An instance of this structure is used by the parser to record both
9283 ** the parse tree for an expression and the span of input text for an
9284 ** expression.
9285 */
9286 struct ExprSpan {
9287   Expr *pExpr;          /* The expression parse tree */
9288   const char *zStart;   /* First character of input text */
9289   const char *zEnd;     /* One character past the end of input text */
9290 };
9291
9292 /*
9293 ** An instance of this structure can hold a simple list of identifiers,
9294 ** such as the list "a,b,c" in the following statements:
9295 **
9296 **      INSERT INTO t(a,b,c) VALUES ...;
9297 **      CREATE INDEX idx ON t(a,b,c);
9298 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
9299 **
9300 ** The IdList.a.idx field is used when the IdList represents the list of
9301 ** column names after a table name in an INSERT statement.  In the statement
9302 **
9303 **     INSERT INTO t(a,b,c) ...
9304 **
9305 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
9306 */
9307 struct IdList {
9308   struct IdList_item {
9309     char *zName;      /* Name of the identifier */
9310     int idx;          /* Index in some Table.aCol[] of a column named zName */
9311   } *a;
9312   int nId;         /* Number of identifiers on the list */
9313   int nAlloc;      /* Number of entries allocated for a[] below */
9314 };
9315
9316 /*
9317 ** The bitmask datatype defined below is used for various optimizations.
9318 **
9319 ** Changing this from a 64-bit to a 32-bit type limits the number of
9320 ** tables in a join to 32 instead of 64.  But it also reduces the size
9321 ** of the library by 738 bytes on ix86.
9322 */
9323 typedef u64 Bitmask;
9324
9325 /*
9326 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
9327 */
9328 #define BMS  ((int)(sizeof(Bitmask)*8))
9329
9330 /*
9331 ** The following structure describes the FROM clause of a SELECT statement.
9332 ** Each table or subquery in the FROM clause is a separate element of
9333 ** the SrcList.a[] array.
9334 **
9335 ** With the addition of multiple database support, the following structure
9336 ** can also be used to describe a particular table such as the table that
9337 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
9338 ** such a table must be a simple name: ID.  But in SQLite, the table can
9339 ** now be identified by a database name, a dot, then the table name: ID.ID.
9340 **
9341 ** The jointype starts out showing the join type between the current table
9342 ** and the next table on the list.  The parser builds the list this way.
9343 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
9344 ** jointype expresses the join between the table and the previous table.
9345 */
9346 struct SrcList {
9347   i16 nSrc;        /* Number of tables or subqueries in the FROM clause */
9348   i16 nAlloc;      /* Number of entries allocated in a[] below */
9349   struct SrcList_item {
9350     char *zDatabase;  /* Name of database holding this table */
9351     char *zName;      /* Name of the table */
9352     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
9353     Table *pTab;      /* An SQL table corresponding to zName */
9354     Select *pSelect;  /* A SELECT statement used in place of a table name */
9355     u8 isPopulated;   /* Temporary table associated with SELECT is populated */
9356     u8 jointype;      /* Type of join between this able and the previous */
9357     u8 notIndexed;    /* True if there is a NOT INDEXED clause */
9358     int iCursor;      /* The VDBE cursor number used to access this table */
9359     Expr *pOn;        /* The ON clause of a join */
9360     IdList *pUsing;   /* The USING clause of a join */
9361     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
9362     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
9363     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
9364   } a[1];             /* One entry for each identifier on the list */
9365 };
9366
9367 /*
9368 ** Permitted values of the SrcList.a.jointype field
9369 */
9370 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
9371 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
9372 #define JT_NATURAL   0x0004    /* True for a "natural" join */
9373 #define JT_LEFT      0x0008    /* Left outer join */
9374 #define JT_RIGHT     0x0010    /* Right outer join */
9375 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
9376 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
9377
9378
9379 /*
9380 ** A WherePlan object holds information that describes a lookup
9381 ** strategy.
9382 **
9383 ** This object is intended to be opaque outside of the where.c module.
9384 ** It is included here only so that that compiler will know how big it
9385 ** is.  None of the fields in this object should be used outside of
9386 ** the where.c module.
9387 **
9388 ** Within the union, pIdx is only used when wsFlags&WHERE_INDEXED is true.
9389 ** pTerm is only used when wsFlags&WHERE_MULTI_OR is true.  And pVtabIdx
9390 ** is only used when wsFlags&WHERE_VIRTUALTABLE is true.  It is never the
9391 ** case that more than one of these conditions is true.
9392 */
9393 struct WherePlan {
9394   u32 wsFlags;                   /* WHERE_* flags that describe the strategy */
9395   u32 nEq;                       /* Number of == constraints */
9396   union {
9397     Index *pIdx;                   /* Index when WHERE_INDEXED is true */
9398     struct WhereTerm *pTerm;       /* WHERE clause term for OR-search */
9399     sqlite3_index_info *pVtabIdx;  /* Virtual table index to use */
9400   } u;
9401 };
9402
9403 /*
9404 ** For each nested loop in a WHERE clause implementation, the WhereInfo
9405 ** structure contains a single instance of this structure.  This structure
9406 ** is intended to be private the the where.c module and should not be
9407 ** access or modified by other modules.
9408 **
9409 ** The pIdxInfo field is used to help pick the best index on a
9410 ** virtual table.  The pIdxInfo pointer contains indexing
9411 ** information for the i-th table in the FROM clause before reordering.
9412 ** All the pIdxInfo pointers are freed by whereInfoFree() in where.c.
9413 ** All other information in the i-th WhereLevel object for the i-th table
9414 ** after FROM clause ordering.
9415 */
9416 struct WhereLevel {
9417   WherePlan plan;       /* query plan for this element of the FROM clause */
9418   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
9419   int iTabCur;          /* The VDBE cursor used to access the table */
9420   int iIdxCur;          /* The VDBE cursor used to access pIdx */
9421   int addrBrk;          /* Jump here to break out of the loop */
9422   int addrNxt;          /* Jump here to start the next IN combination */
9423   int addrCont;         /* Jump here to continue with the next loop cycle */
9424   int addrFirst;        /* First instruction of interior of the loop */
9425   u8 iFrom;             /* Which entry in the FROM clause */
9426   u8 op, p5;            /* Opcode and P5 of the opcode that ends the loop */
9427   int p1, p2;           /* Operands of the opcode used to ends the loop */
9428   union {               /* Information that depends on plan.wsFlags */
9429     struct {
9430       int nIn;              /* Number of entries in aInLoop[] */
9431       struct InLoop {
9432         int iCur;              /* The VDBE cursor used by this IN operator */
9433         int addrInTop;         /* Top of the IN loop */
9434       } *aInLoop;           /* Information about each nested IN operator */
9435     } in;                 /* Used when plan.wsFlags&WHERE_IN_ABLE */
9436   } u;
9437
9438   /* The following field is really not part of the current level.  But
9439   ** we need a place to cache virtual table index information for each
9440   ** virtual table in the FROM clause and the WhereLevel structure is
9441   ** a convenient place since there is one WhereLevel for each FROM clause
9442   ** element.
9443   */
9444   sqlite3_index_info *pIdxInfo;  /* Index info for n-th source table */
9445 };
9446
9447 /*
9448 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
9449 ** and the WhereInfo.wctrlFlags member.
9450 */
9451 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
9452 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
9453 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
9454 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
9455 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
9456 #define WHERE_OMIT_OPEN        0x0010 /* Table cursor are already open */
9457 #define WHERE_OMIT_CLOSE       0x0020 /* Omit close of table & index cursors */
9458 #define WHERE_FORCE_TABLE      0x0040 /* Do not use an index-only search */
9459 #define WHERE_ONETABLE_ONLY    0x0080 /* Only code the 1st table in pTabList */
9460
9461 /*
9462 ** The WHERE clause processing routine has two halves.  The
9463 ** first part does the start of the WHERE loop and the second
9464 ** half does the tail of the WHERE loop.  An instance of
9465 ** this structure is returned by the first half and passed
9466 ** into the second half to give some continuity.
9467 */
9468 struct WhereInfo {
9469   Parse *pParse;       /* Parsing and code generating context */
9470   u16 wctrlFlags;      /* Flags originally passed to sqlite3WhereBegin() */
9471   u8 okOnePass;        /* Ok to use one-pass algorithm for UPDATE or DELETE */
9472   u8 untestedTerms;    /* Not all WHERE terms resolved by outer loop */
9473   SrcList *pTabList;             /* List of tables in the join */
9474   int iTop;                      /* The very beginning of the WHERE loop */
9475   int iContinue;                 /* Jump here to continue with next record */
9476   int iBreak;                    /* Jump here to break out of the loop */
9477   int nLevel;                    /* Number of nested loop */
9478   struct WhereClause *pWC;       /* Decomposition of the WHERE clause */
9479   WhereLevel a[1];               /* Information about each nest loop in WHERE */
9480 };
9481
9482 /*
9483 ** A NameContext defines a context in which to resolve table and column
9484 ** names.  The context consists of a list of tables (the pSrcList) field and
9485 ** a list of named expression (pEList).  The named expression list may
9486 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
9487 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
9488 ** pEList corresponds to the result set of a SELECT and is NULL for
9489 ** other statements.
9490 **
9491 ** NameContexts can be nested.  When resolving names, the inner-most 
9492 ** context is searched first.  If no match is found, the next outer
9493 ** context is checked.  If there is still no match, the next context
9494 ** is checked.  This process continues until either a match is found
9495 ** or all contexts are check.  When a match is found, the nRef member of
9496 ** the context containing the match is incremented. 
9497 **
9498 ** Each subquery gets a new NameContext.  The pNext field points to the
9499 ** NameContext in the parent query.  Thus the process of scanning the
9500 ** NameContext list corresponds to searching through successively outer
9501 ** subqueries looking for a match.
9502 */
9503 struct NameContext {
9504   Parse *pParse;       /* The parser */
9505   SrcList *pSrcList;   /* One or more tables used to resolve names */
9506   ExprList *pEList;    /* Optional list of named expressions */
9507   int nRef;            /* Number of names resolved by this context */
9508   int nErr;            /* Number of errors encountered while resolving names */
9509   u8 allowAgg;         /* Aggregate functions allowed here */
9510   u8 hasAgg;           /* True if aggregates are seen */
9511   u8 isCheck;          /* True if resolving names in a CHECK constraint */
9512   int nDepth;          /* Depth of subquery recursion. 1 for no recursion */
9513   AggInfo *pAggInfo;   /* Information about aggregates at this level */
9514   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
9515 };
9516
9517 /*
9518 ** An instance of the following structure contains all information
9519 ** needed to generate code for a single SELECT statement.
9520 **
9521 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
9522 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
9523 ** limit and nOffset to the value of the offset (or 0 if there is not
9524 ** offset).  But later on, nLimit and nOffset become the memory locations
9525 ** in the VDBE that record the limit and offset counters.
9526 **
9527 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
9528 ** These addresses must be stored so that we can go back and fill in
9529 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
9530 ** the number of columns in P2 can be computed at the same time
9531 ** as the OP_OpenEphm instruction is coded because not
9532 ** enough information about the compound query is known at that point.
9533 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
9534 ** for the result set.  The KeyInfo for addrOpenTran[2] contains collating
9535 ** sequences for the ORDER BY clause.
9536 */
9537 struct Select {
9538   ExprList *pEList;      /* The fields of the result */
9539   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
9540   char affinity;         /* MakeRecord with this affinity for SRT_Set */
9541   u16 selFlags;          /* Various SF_* values */
9542   SrcList *pSrc;         /* The FROM clause */
9543   Expr *pWhere;          /* The WHERE clause */
9544   ExprList *pGroupBy;    /* The GROUP BY clause */
9545   Expr *pHaving;         /* The HAVING clause */
9546   ExprList *pOrderBy;    /* The ORDER BY clause */
9547   Select *pPrior;        /* Prior select in a compound select statement */
9548   Select *pNext;         /* Next select to the left in a compound */
9549   Select *pRightmost;    /* Right-most select in a compound select statement */
9550   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
9551   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
9552   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
9553   int addrOpenEphm[3];   /* OP_OpenEphem opcodes related to this select */
9554 };
9555
9556 /*
9557 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
9558 ** "Select Flag".
9559 */
9560 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
9561 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
9562 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
9563 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
9564 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
9565 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
9566
9567
9568 /*
9569 ** The results of a select can be distributed in several ways.  The
9570 ** "SRT" prefix means "SELECT Result Type".
9571 */
9572 #define SRT_Union        1  /* Store result as keys in an index */
9573 #define SRT_Except       2  /* Remove result from a UNION index */
9574 #define SRT_Exists       3  /* Store 1 if the result is not empty */
9575 #define SRT_Discard      4  /* Do not save the results anywhere */
9576
9577 /* The ORDER BY clause is ignored for all of the above */
9578 #define IgnorableOrderby(X) ((X->eDest)<=SRT_Discard)
9579
9580 #define SRT_Output       5  /* Output each row of result */
9581 #define SRT_Mem          6  /* Store result in a memory cell */
9582 #define SRT_Set          7  /* Store results as keys in an index */
9583 #define SRT_Table        8  /* Store result as data with an automatic rowid */
9584 #define SRT_EphemTab     9  /* Create transient tab and store like SRT_Table */
9585 #define SRT_Coroutine   10  /* Generate a single row of result */
9586
9587 /*
9588 ** A structure used to customize the behavior of sqlite3Select(). See
9589 ** comments above sqlite3Select() for details.
9590 */
9591 typedef struct SelectDest SelectDest;
9592 struct SelectDest {
9593   u8 eDest;         /* How to dispose of the results */
9594   u8 affinity;      /* Affinity used when eDest==SRT_Set */
9595   int iParm;        /* A parameter used by the eDest disposal method */
9596   int iMem;         /* Base register where results are written */
9597   int nMem;         /* Number of registers allocated */
9598 };
9599
9600 /*
9601 ** During code generation of statements that do inserts into AUTOINCREMENT 
9602 ** tables, the following information is attached to the Table.u.autoInc.p
9603 ** pointer of each autoincrement table to record some side information that
9604 ** the code generator needs.  We have to keep per-table autoincrement
9605 ** information in case inserts are down within triggers.  Triggers do not
9606 ** normally coordinate their activities, but we do need to coordinate the
9607 ** loading and saving of autoincrement information.
9608 */
9609 struct AutoincInfo {
9610   AutoincInfo *pNext;   /* Next info block in a list of them all */
9611   Table *pTab;          /* Table this info block refers to */
9612   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
9613   int regCtr;           /* Memory register holding the rowid counter */
9614 };
9615
9616 /*
9617 ** Size of the column cache
9618 */
9619 #ifndef SQLITE_N_COLCACHE
9620 # define SQLITE_N_COLCACHE 10
9621 #endif
9622
9623 /*
9624 ** At least one instance of the following structure is created for each 
9625 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
9626 ** statement. All such objects are stored in the linked list headed at
9627 ** Parse.pTriggerPrg and deleted once statement compilation has been
9628 ** completed.
9629 **
9630 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
9631 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
9632 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
9633 ** The Parse.pTriggerPrg list never contains two entries with the same
9634 ** values for both pTrigger and orconf.
9635 **
9636 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
9637 ** accessed (or set to 0 for triggers fired as a result of INSERT 
9638 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
9639 ** a mask of new.* columns used by the program.
9640 */
9641 struct TriggerPrg {
9642   Trigger *pTrigger;      /* Trigger this program was coded from */
9643   int orconf;             /* Default ON CONFLICT policy */
9644   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
9645   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
9646   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
9647 };
9648
9649 /*
9650 ** An SQL parser context.  A copy of this structure is passed through
9651 ** the parser and down into all the parser action routine in order to
9652 ** carry around information that is global to the entire parse.
9653 **
9654 ** The structure is divided into two parts.  When the parser and code
9655 ** generate call themselves recursively, the first part of the structure
9656 ** is constant but the second part is reset at the beginning and end of
9657 ** each recursion.
9658 **
9659 ** The nTableLock and aTableLock variables are only used if the shared-cache 
9660 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
9661 ** used to store the set of table-locks required by the statement being
9662 ** compiled. Function sqlite3TableLock() is used to add entries to the
9663 ** list.
9664 */
9665 struct Parse {
9666   sqlite3 *db;         /* The main database structure */
9667   int rc;              /* Return code from execution */
9668   char *zErrMsg;       /* An error message */
9669   Vdbe *pVdbe;         /* An engine for executing database bytecode */
9670   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
9671   u8 nameClash;        /* A permanent table name clashes with temp table name */
9672   u8 checkSchema;      /* Causes schema cookie check after an error */
9673   u8 nested;           /* Number of nested calls to the parser/code generator */
9674   u8 parseError;       /* True after a parsing error.  Ticket #1794 */
9675   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
9676   u8 nTempInUse;       /* Number of aTempReg[] currently checked out */
9677   int aTempReg[8];     /* Holding area for temporary registers */
9678   int nRangeReg;       /* Size of the temporary register block */
9679   int iRangeReg;       /* First register in temporary register block */
9680   int nErr;            /* Number of errors seen */
9681   int nTab;            /* Number of previously allocated VDBE cursors */
9682   int nMem;            /* Number of memory cells used so far */
9683   int nSet;            /* Number of sets used so far */
9684   int ckBase;          /* Base register of data during check constraints */
9685   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
9686   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
9687   u8 nColCache;        /* Number of entries in the column cache */
9688   u8 iColCache;        /* Next entry of the cache to replace */
9689   struct yColCache {
9690     int iTable;           /* Table cursor number */
9691     int iColumn;          /* Table column number */
9692     u8 tempReg;           /* iReg is a temp register that needs to be freed */
9693     int iLevel;           /* Nesting level */
9694     int iReg;             /* Reg with value of this column. 0 means none. */
9695     int lru;              /* Least recently used entry has the smallest value */
9696   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
9697   u32 writeMask;       /* Start a write transaction on these databases */
9698   u32 cookieMask;      /* Bitmask of schema verified databases */
9699   u8 isMultiWrite;     /* True if statement may affect/insert multiple rows */
9700   u8 mayAbort;         /* True if statement may throw an ABORT exception */
9701   int cookieGoto;      /* Address of OP_Goto to cookie verifier subroutine */
9702   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
9703 #ifndef SQLITE_OMIT_SHARED_CACHE
9704   int nTableLock;        /* Number of locks in aTableLock */
9705   TableLock *aTableLock; /* Required table locks for shared-cache mode */
9706 #endif
9707   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
9708   int regRoot;         /* Register holding root page number for new objects */
9709   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
9710   int nMaxArg;         /* Max args passed to user function by sub-program */
9711
9712   /* Information used while coding trigger programs. */
9713   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
9714   Table *pTriggerTab;  /* Table triggers are being coded for */
9715   u32 oldmask;         /* Mask of old.* columns referenced */
9716   u32 newmask;         /* Mask of new.* columns referenced */
9717   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
9718   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
9719   u8 disableTriggers;  /* True to disable triggers */
9720
9721   /* Above is constant between recursions.  Below is reset before and after
9722   ** each recursion */
9723
9724   int nVar;            /* Number of '?' variables seen in the SQL so far */
9725   int nVarExpr;        /* Number of used slots in apVarExpr[] */
9726   int nVarExprAlloc;   /* Number of allocated slots in apVarExpr[] */
9727   Expr **apVarExpr;    /* Pointers to :aaa and $aaaa wildcard expressions */
9728   Vdbe *pReprepare;    /* VM being reprepared (sqlite3Reprepare()) */
9729   int nAlias;          /* Number of aliased result set columns */
9730   int nAliasAlloc;     /* Number of allocated slots for aAlias[] */
9731   int *aAlias;         /* Register used to hold aliased result */
9732   u8 explain;          /* True if the EXPLAIN flag is found on the query */
9733   Token sNameToken;    /* Token with unqualified schema object name */
9734   Token sLastToken;    /* The last token parsed */
9735   const char *zTail;   /* All SQL text past the last semicolon parsed */
9736   Table *pNewTable;    /* A table being constructed by CREATE TABLE */
9737   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
9738   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
9739 #ifndef SQLITE_OMIT_VIRTUALTABLE
9740   Token sArg;                /* Complete text of a module argument */
9741   u8 declareVtab;            /* True if inside sqlite3_declare_vtab() */
9742   int nVtabLock;             /* Number of virtual tables to lock */
9743   Table **apVtabLock;        /* Pointer to virtual tables needing locking */
9744 #endif
9745   int nHeight;            /* Expression tree height of current sub-select */
9746   Table *pZombieTab;      /* List of Table objects to delete after code gen */
9747   TriggerPrg *pTriggerPrg;    /* Linked list of coded triggers */
9748 };
9749
9750 #ifdef SQLITE_OMIT_VIRTUALTABLE
9751   #define IN_DECLARE_VTAB 0
9752 #else
9753   #define IN_DECLARE_VTAB (pParse->declareVtab)
9754 #endif
9755
9756 /*
9757 ** An instance of the following structure can be declared on a stack and used
9758 ** to save the Parse.zAuthContext value so that it can be restored later.
9759 */
9760 struct AuthContext {
9761   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
9762   Parse *pParse;              /* The Parse structure */
9763 };
9764
9765 /*
9766 ** Bitfield flags for P5 value in OP_Insert and OP_Delete
9767 */
9768 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
9769 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
9770 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
9771 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
9772 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
9773 #define OPFLAG_CLEARCACHE    0x20    /* Clear pseudo-table cache in OP_Column */
9774
9775 /*
9776  * Each trigger present in the database schema is stored as an instance of
9777  * struct Trigger. 
9778  *
9779  * Pointers to instances of struct Trigger are stored in two ways.
9780  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
9781  *    database). This allows Trigger structures to be retrieved by name.
9782  * 2. All triggers associated with a single table form a linked list, using the
9783  *    pNext member of struct Trigger. A pointer to the first element of the
9784  *    linked list is stored as the "pTrigger" member of the associated
9785  *    struct Table.
9786  *
9787  * The "step_list" member points to the first element of a linked list
9788  * containing the SQL statements specified as the trigger program.
9789  */
9790 struct Trigger {
9791   char *zName;            /* The name of the trigger                        */
9792   char *table;            /* The table or view to which the trigger applies */
9793   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
9794   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
9795   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
9796   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
9797                              the <column-list> is stored here */
9798   Schema *pSchema;        /* Schema containing the trigger */
9799   Schema *pTabSchema;     /* Schema containing the table */
9800   TriggerStep *step_list; /* Link list of trigger program steps             */
9801   Trigger *pNext;         /* Next trigger associated with the table */
9802 };
9803
9804 /*
9805 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
9806 ** determine which. 
9807 **
9808 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
9809 ** In that cases, the constants below can be ORed together.
9810 */
9811 #define TRIGGER_BEFORE  1
9812 #define TRIGGER_AFTER   2
9813
9814 /*
9815  * An instance of struct TriggerStep is used to store a single SQL statement
9816  * that is a part of a trigger-program. 
9817  *
9818  * Instances of struct TriggerStep are stored in a singly linked list (linked
9819  * using the "pNext" member) referenced by the "step_list" member of the 
9820  * associated struct Trigger instance. The first element of the linked list is
9821  * the first step of the trigger-program.
9822  * 
9823  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
9824  * "SELECT" statement. The meanings of the other members is determined by the 
9825  * value of "op" as follows:
9826  *
9827  * (op == TK_INSERT)
9828  * orconf    -> stores the ON CONFLICT algorithm
9829  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
9830  *              this stores a pointer to the SELECT statement. Otherwise NULL.
9831  * target    -> A token holding the quoted name of the table to insert into.
9832  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
9833  *              this stores values to be inserted. Otherwise NULL.
9834  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
9835  *              statement, then this stores the column-names to be
9836  *              inserted into.
9837  *
9838  * (op == TK_DELETE)
9839  * target    -> A token holding the quoted name of the table to delete from.
9840  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
9841  *              Otherwise NULL.
9842  * 
9843  * (op == TK_UPDATE)
9844  * target    -> A token holding the quoted name of the table to update rows of.
9845  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
9846  *              Otherwise NULL.
9847  * pExprList -> A list of the columns to update and the expressions to update
9848  *              them to. See sqlite3Update() documentation of "pChanges"
9849  *              argument.
9850  * 
9851  */
9852 struct TriggerStep {
9853   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
9854   u8 orconf;           /* OE_Rollback etc. */
9855   Trigger *pTrig;      /* The trigger that this step is a part of */
9856   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
9857   Token target;        /* Target table for DELETE, UPDATE, INSERT */
9858   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
9859   ExprList *pExprList; /* SET clause for UPDATE.  VALUES clause for INSERT */
9860   IdList *pIdList;     /* Column names for INSERT */
9861   TriggerStep *pNext;  /* Next in the link-list */
9862   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
9863 };
9864
9865 /*
9866 ** The following structure contains information used by the sqliteFix...
9867 ** routines as they walk the parse tree to make database references
9868 ** explicit.  
9869 */
9870 typedef struct DbFixer DbFixer;
9871 struct DbFixer {
9872   Parse *pParse;      /* The parsing context.  Error messages written here */
9873   const char *zDb;    /* Make sure all objects are contained in this database */
9874   const char *zType;  /* Type of the container - used for error messages */
9875   const Token *pName; /* Name of the container - used for error messages */
9876 };
9877
9878 /*
9879 ** An objected used to accumulate the text of a string where we
9880 ** do not necessarily know how big the string will be in the end.
9881 */
9882 struct StrAccum {
9883   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
9884   char *zBase;         /* A base allocation.  Not from malloc. */
9885   char *zText;         /* The string collected so far */
9886   int  nChar;          /* Length of the string so far */
9887   int  nAlloc;         /* Amount of space allocated in zText */
9888   int  mxAlloc;        /* Maximum allowed string length */
9889   u8   mallocFailed;   /* Becomes true if any memory allocation fails */
9890   u8   useMalloc;      /* True if zText is enlargeable using realloc */
9891   u8   tooBig;         /* Becomes true if string size exceeds limits */
9892 };
9893
9894 /*
9895 ** A pointer to this structure is used to communicate information
9896 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
9897 */
9898 typedef struct {
9899   sqlite3 *db;        /* The database being initialized */
9900   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
9901   char **pzErrMsg;    /* Error message stored here */
9902   int rc;             /* Result code stored here */
9903 } InitData;
9904
9905 /*
9906 ** Structure containing global configuration data for the SQLite library.
9907 **
9908 ** This structure also contains some state information.
9909 */
9910 struct Sqlite3Config {
9911   int bMemstat;                     /* True to enable memory status */
9912   int bCoreMutex;                   /* True to enable core mutexing */
9913   int bFullMutex;                   /* True to enable full mutexing */
9914   int mxStrlen;                     /* Maximum string length */
9915   int szLookaside;                  /* Default lookaside buffer size */
9916   int nLookaside;                   /* Default lookaside buffer count */
9917   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
9918   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
9919   sqlite3_pcache_methods pcache;    /* Low-level page-cache interface */
9920   void *pHeap;                      /* Heap storage space */
9921   int nHeap;                        /* Size of pHeap[] */
9922   int mnReq, mxReq;                 /* Min and max heap requests sizes */
9923   void *pScratch;                   /* Scratch memory */
9924   int szScratch;                    /* Size of each scratch buffer */
9925   int nScratch;                     /* Number of scratch buffers */
9926   void *pPage;                      /* Page cache memory */
9927   int szPage;                       /* Size of each page in pPage[] */
9928   int nPage;                        /* Number of pages in pPage[] */
9929   int mxParserStack;                /* maximum depth of the parser stack */
9930   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
9931   /* The above might be initialized to non-zero.  The following need to always
9932   ** initially be zero, however. */
9933   int isInit;                       /* True after initialization has finished */
9934   int inProgress;                   /* True while initialization in progress */
9935   int isMutexInit;                  /* True after mutexes are initialized */
9936   int isMallocInit;                 /* True after malloc is initialized */
9937   int isPCacheInit;                 /* True after malloc is initialized */
9938   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
9939   int nRefInitMutex;                /* Number of users of pInitMutex */
9940   void (*xLog)(void*,int,const char*); /* Function for logging */
9941   void *pLogArg;                       /* First argument to xLog() */
9942 };
9943
9944 /*
9945 ** Context pointer passed down through the tree-walk.
9946 */
9947 struct Walker {
9948   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
9949   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
9950   Parse *pParse;                            /* Parser context.  */
9951   union {                                   /* Extra data for callback */
9952     NameContext *pNC;                          /* Naming context */
9953     int i;                                     /* Integer value */
9954   } u;
9955 };
9956
9957 /* Forward declarations */
9958 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
9959 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
9960 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
9961 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
9962 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
9963
9964 /*
9965 ** Return code from the parse-tree walking primitives and their
9966 ** callbacks.
9967 */
9968 #define WRC_Continue    0   /* Continue down into children */
9969 #define WRC_Prune       1   /* Omit children but continue walking siblings */
9970 #define WRC_Abort       2   /* Abandon the tree walk */
9971
9972 /*
9973 ** Assuming zIn points to the first byte of a UTF-8 character,
9974 ** advance zIn to point to the first byte of the next UTF-8 character.
9975 */
9976 #define SQLITE_SKIP_UTF8(zIn) {                        \
9977   if( (*(zIn++))>=0xc0 ){                              \
9978     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
9979   }                                                    \
9980 }
9981
9982 /*
9983 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
9984 ** the same name but without the _BKPT suffix.  These macros invoke
9985 ** routines that report the line-number on which the error originated
9986 ** using sqlite3_log().  The routines also provide a convenient place
9987 ** to set a debugger breakpoint.
9988 */
9989 SQLITE_PRIVATE int sqlite3CorruptError(int);
9990 SQLITE_PRIVATE int sqlite3MisuseError(int);
9991 SQLITE_PRIVATE int sqlite3CantopenError(int);
9992 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
9993 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
9994 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
9995
9996
9997 /*
9998 ** FTS4 is really an extension for FTS3.  It is enabled using the
9999 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
10000 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
10001 */
10002 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
10003 # define SQLITE_ENABLE_FTS3
10004 #endif
10005
10006 /*
10007 ** The ctype.h header is needed for non-ASCII systems.  It is also
10008 ** needed by FTS3 when FTS3 is included in the amalgamation.
10009 */
10010 #if !defined(SQLITE_ASCII) || \
10011     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
10012 # include <ctype.h>
10013 #endif
10014
10015 /*
10016 ** The following macros mimic the standard library functions toupper(),
10017 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
10018 ** sqlite versions only work for ASCII characters, regardless of locale.
10019 */
10020 #ifdef SQLITE_ASCII
10021 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
10022 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
10023 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
10024 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
10025 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
10026 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
10027 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
10028 #else
10029 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
10030 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
10031 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
10032 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
10033 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
10034 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
10035 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
10036 #endif
10037
10038 /*
10039 ** Internal function prototypes
10040 */
10041 SQLITE_PRIVATE int sqlite3StrICmp(const char *, const char *);
10042 SQLITE_PRIVATE int sqlite3IsNumber(const char*, int*, u8);
10043 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
10044 #define sqlite3StrNICmp sqlite3_strnicmp
10045
10046 SQLITE_PRIVATE int sqlite3MallocInit(void);
10047 SQLITE_PRIVATE void sqlite3MallocEnd(void);
10048 SQLITE_PRIVATE void *sqlite3Malloc(int);
10049 SQLITE_PRIVATE void *sqlite3MallocZero(int);
10050 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, int);
10051 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, int);
10052 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
10053 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, int);
10054 SQLITE_PRIVATE void *sqlite3Realloc(void*, int);
10055 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, int);
10056 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, int);
10057 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
10058 SQLITE_PRIVATE int sqlite3MallocSize(void*);
10059 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
10060 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
10061 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
10062 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
10063 SQLITE_PRIVATE void sqlite3PageFree(void*);
10064 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
10065 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
10066 SQLITE_PRIVATE int sqlite3MemoryAlarm(void (*)(void*, sqlite3_int64, int), void*, sqlite3_int64);
10067
10068 /*
10069 ** On systems with ample stack space and that support alloca(), make
10070 ** use of alloca() to obtain space for large automatic objects.  By default,
10071 ** obtain space from malloc().
10072 **
10073 ** The alloca() routine never returns NULL.  This will cause code paths
10074 ** that deal with sqlite3StackAlloc() failures to be unreachable.
10075 */
10076 #ifdef SQLITE_USE_ALLOCA
10077 # define sqlite3StackAllocRaw(D,N)   alloca(N)
10078 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
10079 # define sqlite3StackFree(D,P)       
10080 #else
10081 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
10082 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
10083 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
10084 #endif
10085
10086 #ifdef SQLITE_ENABLE_MEMSYS3
10087 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
10088 #endif
10089 #ifdef SQLITE_ENABLE_MEMSYS5
10090 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
10091 #endif
10092
10093
10094 #ifndef SQLITE_MUTEX_OMIT
10095 SQLITE_PRIVATE   sqlite3_mutex_methods *sqlite3DefaultMutex(void);
10096 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
10097 SQLITE_PRIVATE   int sqlite3MutexInit(void);
10098 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
10099 #endif
10100
10101 SQLITE_PRIVATE int sqlite3StatusValue(int);
10102 SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
10103 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
10104
10105 #ifndef SQLITE_OMIT_FLOATING_POINT
10106 SQLITE_PRIVATE   int sqlite3IsNaN(double);
10107 #else
10108 # define sqlite3IsNaN(X)  0
10109 #endif
10110
10111 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, int, const char*, va_list);
10112 #ifndef SQLITE_OMIT_TRACE
10113 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, const char*, ...);
10114 #endif
10115 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
10116 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
10117 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
10118 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
10119 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
10120 #endif
10121 #if defined(SQLITE_TEST)
10122 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
10123 #endif
10124 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
10125 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
10126 SQLITE_PRIVATE int sqlite3Dequote(char*);
10127 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
10128 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
10129 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
10130 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
10131 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
10132 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
10133 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
10134 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
10135 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
10136 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
10137 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
10138 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
10139 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
10140 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
10141 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
10142 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
10143 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
10144 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
10145 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
10146 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
10147 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
10148 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
10149 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3*, int);
10150 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
10151 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
10152 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
10153 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
10154 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
10155 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
10156 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
10157 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
10158 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
10159 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
10160 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
10161 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
10162 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,Select*);
10163
10164 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
10165 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
10166 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
10167 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
10168 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
10169 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
10170 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
10171
10172 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
10173 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
10174 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
10175 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, u8 iBatch, i64);
10176 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
10177
10178 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
10179
10180 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
10181 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
10182 #else
10183 # define sqlite3ViewGetColumnNames(A,B) 0
10184 #endif
10185
10186 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
10187 SQLITE_PRIVATE void sqlite3DeleteTable(Table*);
10188 #ifndef SQLITE_OMIT_AUTOINCREMENT
10189 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
10190 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
10191 #else
10192 # define sqlite3AutoincrementBegin(X)
10193 # define sqlite3AutoincrementEnd(X)
10194 #endif
10195 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, ExprList*, Select*, IdList*, int);
10196 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int,int*,int*,int*);
10197 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
10198 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
10199 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
10200 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
10201 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
10202                                       Token*, Select*, Expr*, IdList*);
10203 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
10204 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
10205 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
10206 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
10207 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
10208 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
10209 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
10210                         Token*, int, int);
10211 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
10212 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
10213 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
10214                          Expr*,ExprList*,int,Expr*,Expr*);
10215 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
10216 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
10217 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
10218 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
10219 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
10220 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse *, SrcList *, Expr *, ExprList *, Expr *, Expr *, char *);
10221 #endif
10222 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
10223 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
10224 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*, SrcList*, Expr*, ExprList**, u16);
10225 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
10226 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int);
10227 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
10228 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse*, int, int, int);
10229 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
10230 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
10231 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*, int);
10232 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
10233 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
10234 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
10235 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse*,int,int);
10236 SQLITE_PRIVATE int sqlite3ExprCode(Parse*, Expr*, int);
10237 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
10238 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
10239 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse*, Expr*, int);
10240 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse*, Expr*);
10241 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, int);
10242 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
10243 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
10244 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
10245 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
10246 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
10247 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
10248 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
10249 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
10250 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
10251 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
10252 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*);
10253 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
10254 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
10255 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
10256 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
10257 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
10258 SQLITE_PRIVATE void sqlite3PrngResetState(void);
10259 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*);
10260 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
10261 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
10262 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
10263 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
10264 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
10265 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
10266 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
10267 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
10268 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*);
10269 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
10270 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
10271 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(Vdbe*, const Expr*, int, int);
10272 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
10273 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
10274 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*, Table*, int, int, int, Trigger *, int);
10275 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int*);
10276 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int);
10277 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int,int,
10278                                      int*,int,int,int,int,int*);
10279 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*, Table*, int, int, int*, int, int, int);
10280 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int);
10281 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
10282 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
10283 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
10284 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, char*, int);
10285 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
10286 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
10287 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
10288 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
10289 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
10290 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
10291 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,int);
10292 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
10293 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
10294 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
10295 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
10296 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
10297 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
10298
10299 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
10300 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
10301 #endif
10302
10303 #ifndef SQLITE_OMIT_TRIGGER
10304 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
10305                            Expr*,int, int);
10306 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
10307 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
10308 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
10309 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
10310 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
10311 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
10312                             int, int, int);
10313 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
10314   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
10315 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
10316 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
10317 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
10318                                         ExprList*,Select*,u8);
10319 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
10320 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
10321 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
10322 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
10323 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
10324 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
10325 #else
10326 # define sqlite3TriggersExist(B,C,D,E,F) 0
10327 # define sqlite3DeleteTrigger(A,B)
10328 # define sqlite3DropTriggerPtr(A,B)
10329 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
10330 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
10331 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
10332 # define sqlite3TriggerList(X, Y) 0
10333 # define sqlite3ParseToplevel(p) p
10334 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
10335 #endif
10336
10337 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
10338 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
10339 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
10340 #ifndef SQLITE_OMIT_AUTHORIZATION
10341 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
10342 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
10343 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
10344 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
10345 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
10346 #else
10347 # define sqlite3AuthRead(a,b,c,d)
10348 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
10349 # define sqlite3AuthContextPush(a,b,c)
10350 # define sqlite3AuthContextPop(a)  ((void)(a))
10351 #endif
10352 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
10353 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
10354 SQLITE_PRIVATE int sqlite3BtreeFactory(sqlite3 *db, const char *zFilename,
10355                        int omitJournal, int nCache, int flags, Btree **ppBtree);
10356 SQLITE_PRIVATE int sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
10357 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
10358 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
10359 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
10360 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
10361 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
10362 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*);
10363 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
10364 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *, int);
10365 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
10366 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
10367 SQLITE_PRIVATE int sqlite3Utf8Read(const u8*, const u8**);
10368
10369 /*
10370 ** Routines to read and write variable-length integers.  These used to
10371 ** be defined locally, but now we use the varint routines in the util.c
10372 ** file.  Code should use the MACRO forms below, as the Varint32 versions
10373 ** are coded to assume the single byte case is already handled (which 
10374 ** the MACRO form does).
10375 */
10376 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
10377 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char*, u32);
10378 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
10379 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
10380 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
10381
10382 /*
10383 ** The header of a record consists of a sequence variable-length integers.
10384 ** These integers are almost always small and are encoded as a single byte.
10385 ** The following macros take advantage this fact to provide a fast encode
10386 ** and decode of the integers in a record header.  It is faster for the common
10387 ** case where the integer is a single byte.  It is a little slower when the
10388 ** integer is two or more bytes.  But overall it is faster.
10389 **
10390 ** The following expressions are equivalent:
10391 **
10392 **     x = sqlite3GetVarint32( A, &B );
10393 **     x = sqlite3PutVarint32( A, B );
10394 **
10395 **     x = getVarint32( A, B );
10396 **     x = putVarint32( A, B );
10397 **
10398 */
10399 #define getVarint32(A,B)  (u8)((*(A)<(u8)0x80) ? ((B) = (u32)*(A)),1 : sqlite3GetVarint32((A), (u32 *)&(B)))
10400 #define putVarint32(A,B)  (u8)(((u32)(B)<(u32)0x80) ? (*(A) = (unsigned char)(B)),1 : sqlite3PutVarint32((A), (B)))
10401 #define getVarint    sqlite3GetVarint
10402 #define putVarint    sqlite3PutVarint
10403
10404
10405 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
10406 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *, Table *);
10407 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
10408 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
10409 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
10410 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*);
10411 SQLITE_PRIVATE void sqlite3Error(sqlite3*, int, const char*,...);
10412 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
10413 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
10414 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
10415 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
10416 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
10417 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
10418 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
10419 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *, Token *);
10420 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
10421 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
10422 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
10423
10424 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
10425 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
10426 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
10427                         void(*)(void*));
10428 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
10429 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
10430 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
10431 #ifdef SQLITE_ENABLE_STAT2
10432 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *, u8, char *, int, int *);
10433 #endif
10434 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
10435 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
10436 #ifndef SQLITE_AMALGAMATION
10437 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
10438 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
10439 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
10440 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
10441 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10442 SQLITE_PRIVATE int sqlite3PendingByte;
10443 #endif
10444 SQLITE_PRIVATE void sqlite3RootPageMoved(Db*, int, int);
10445 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
10446 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3*);
10447 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
10448 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
10449 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
10450 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
10451 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
10452 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
10453 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
10454 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
10455 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
10456 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
10457 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
10458 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
10459 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(sqlite3*, u8, CollSeq *, const char*);
10460 SQLITE_PRIVATE char sqlite3AffinityType(const char*);
10461 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
10462 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
10463 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
10464 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
10465 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
10466 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index*);
10467 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
10468 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
10469 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
10470 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
10471 SQLITE_PRIVATE void sqlite3SchemaFree(void *);
10472 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
10473 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
10474 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *, Index *);
10475 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
10476   void (*)(sqlite3_context*,int,sqlite3_value **),
10477   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*));
10478 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
10479 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
10480
10481 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
10482 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
10483 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
10484 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
10485 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
10486 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
10487
10488 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
10489 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
10490
10491 /*
10492 ** The interface to the LEMON-generated parser
10493 */
10494 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(size_t));
10495 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
10496 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
10497 #ifdef YYTRACKMAXSTACKDEPTH
10498 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
10499 #endif
10500
10501 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
10502 #ifndef SQLITE_OMIT_LOAD_EXTENSION
10503 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
10504 #else
10505 # define sqlite3CloseExtensions(X)
10506 #endif
10507
10508 #ifndef SQLITE_OMIT_SHARED_CACHE
10509 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
10510 #else
10511   #define sqlite3TableLock(v,w,x,y,z)
10512 #endif
10513
10514 #ifdef SQLITE_TEST
10515 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
10516 #endif
10517
10518 #ifdef SQLITE_OMIT_VIRTUALTABLE
10519 #  define sqlite3VtabClear(Y)
10520 #  define sqlite3VtabSync(X,Y) SQLITE_OK
10521 #  define sqlite3VtabRollback(X)
10522 #  define sqlite3VtabCommit(X)
10523 #  define sqlite3VtabInSync(db) 0
10524 #  define sqlite3VtabLock(X) 
10525 #  define sqlite3VtabUnlock(X)
10526 #  define sqlite3VtabUnlockList(X)
10527 #else
10528 SQLITE_PRIVATE    void sqlite3VtabClear(Table*);
10529 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, char **);
10530 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
10531 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
10532 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
10533 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
10534 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
10535 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
10536 #endif
10537 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
10538 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*);
10539 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
10540 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
10541 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
10542 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
10543 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
10544 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
10545 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
10546 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
10547 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
10548 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
10549 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
10550 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
10551 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
10552 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
10553 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
10554 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
10555
10556 /* Declarations for functions in fkey.c. All of these are replaced by
10557 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
10558 ** key functionality is available. If OMIT_TRIGGER is defined but
10559 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
10560 ** this case foreign keys are parsed, but no other functionality is 
10561 ** provided (enforcement of FK constraints requires the triggers sub-system).
10562 */
10563 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
10564 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int);
10565 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
10566 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int);
10567 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
10568 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
10569 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
10570 #else
10571   #define sqlite3FkActions(a,b,c,d)
10572   #define sqlite3FkCheck(a,b,c,d)
10573   #define sqlite3FkDropTable(a,b,c)
10574   #define sqlite3FkOldmask(a,b)      0
10575   #define sqlite3FkRequired(a,b,c,d) 0
10576 #endif
10577 #ifndef SQLITE_OMIT_FOREIGN_KEY
10578 SQLITE_PRIVATE   void sqlite3FkDelete(Table*);
10579 #else
10580   #define sqlite3FkDelete(a)
10581 #endif
10582
10583
10584 /*
10585 ** Available fault injectors.  Should be numbered beginning with 0.
10586 */
10587 #define SQLITE_FAULTINJECTOR_MALLOC     0
10588 #define SQLITE_FAULTINJECTOR_COUNT      1
10589
10590 /*
10591 ** The interface to the code in fault.c used for identifying "benign"
10592 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
10593 ** is not defined.
10594 */
10595 #ifndef SQLITE_OMIT_BUILTIN_TEST
10596 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
10597 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
10598 #else
10599   #define sqlite3BeginBenignMalloc()
10600   #define sqlite3EndBenignMalloc()
10601 #endif
10602
10603 #define IN_INDEX_ROWID           1
10604 #define IN_INDEX_EPH             2
10605 #define IN_INDEX_INDEX           3
10606 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, int*);
10607
10608 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
10609 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
10610 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
10611 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
10612 #else
10613   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
10614 #endif
10615
10616 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
10617 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
10618 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
10619
10620 #if SQLITE_MAX_EXPR_DEPTH>0
10621 SQLITE_PRIVATE   void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
10622 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
10623 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
10624 #else
10625   #define sqlite3ExprSetHeight(x,y)
10626   #define sqlite3SelectExprHeight(x) 0
10627   #define sqlite3ExprCheckHeight(x,y)
10628 #endif
10629
10630 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
10631 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
10632
10633 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
10634 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
10635 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
10636 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
10637 #else
10638   #define sqlite3ConnectionBlocked(x,y)
10639   #define sqlite3ConnectionUnlocked(x)
10640   #define sqlite3ConnectionClosed(x)
10641 #endif
10642
10643 #ifdef SQLITE_DEBUG
10644 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
10645 #endif
10646
10647 /*
10648 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
10649 ** sqlite3IoTrace is a pointer to a printf-like routine used to
10650 ** print I/O tracing messages. 
10651 */
10652 #ifdef SQLITE_ENABLE_IOTRACE
10653 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
10654 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
10655 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
10656 #else
10657 # define IOTRACE(A)
10658 # define sqlite3VdbeIOTraceSql(X)
10659 #endif
10660
10661 #endif
10662
10663 /************** End of sqliteInt.h *******************************************/
10664 /************** Begin file global.c ******************************************/
10665 /*
10666 ** 2008 June 13
10667 **
10668 ** The author disclaims copyright to this source code.  In place of
10669 ** a legal notice, here is a blessing:
10670 **
10671 **    May you do good and not evil.
10672 **    May you find forgiveness for yourself and forgive others.
10673 **    May you share freely, never taking more than you give.
10674 **
10675 *************************************************************************
10676 **
10677 ** This file contains definitions of global variables and contants.
10678 */
10679
10680 /* An array to map all upper-case characters into their corresponding
10681 ** lower-case character. 
10682 **
10683 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
10684 ** handle case conversions for the UTF character set since the tables
10685 ** involved are nearly as big or bigger than SQLite itself.
10686 */
10687 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
10688 #ifdef SQLITE_ASCII
10689       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
10690      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
10691      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
10692      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
10693     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
10694     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
10695     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
10696     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
10697     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
10698     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
10699     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
10700     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
10701     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
10702     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
10703     252,253,254,255
10704 #endif
10705 #ifdef SQLITE_EBCDIC
10706       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
10707      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
10708      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
10709      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
10710      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
10711      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
10712      96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
10713     112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
10714     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
10715     144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
10716     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
10717     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
10718     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
10719     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
10720     224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
10721     239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
10722 #endif
10723 };
10724
10725 /*
10726 ** The following 256 byte lookup table is used to support SQLites built-in
10727 ** equivalents to the following standard library functions:
10728 **
10729 **   isspace()                        0x01
10730 **   isalpha()                        0x02
10731 **   isdigit()                        0x04
10732 **   isalnum()                        0x06
10733 **   isxdigit()                       0x08
10734 **   toupper()                        0x20
10735 **   SQLite identifier character      0x40
10736 **
10737 ** Bit 0x20 is set if the mapped character requires translation to upper
10738 ** case. i.e. if the character is a lower-case ASCII character.
10739 ** If x is a lower-case ASCII character, then its upper-case equivalent
10740 ** is (x - 0x20). Therefore toupper() can be implemented as:
10741 **
10742 **   (x & ~(map[x]&0x20))
10743 **
10744 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
10745 ** array. tolower() is used more often than toupper() by SQLite.
10746 **
10747 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an 
10748 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
10749 ** non-ASCII UTF character. Hence the test for whether or not a character is
10750 ** part of an identifier is 0x46.
10751 **
10752 ** SQLite's versions are identical to the standard versions assuming a
10753 ** locale of "C". They are implemented as macros in sqliteInt.h.
10754 */
10755 #ifdef SQLITE_ASCII
10756 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
10757   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
10758   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
10759   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
10760   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
10761   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
10762   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
10763   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
10764   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
10765
10766   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
10767   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
10768   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
10769   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
10770   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
10771   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
10772   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
10773   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
10774
10775   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
10776   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
10777   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
10778   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
10779   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
10780   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
10781   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
10782   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
10783
10784   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
10785   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
10786   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
10787   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
10788   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
10789   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
10790   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
10791   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
10792 };
10793 #endif
10794
10795
10796
10797 /*
10798 ** The following singleton contains the global configuration for
10799 ** the SQLite library.
10800 */
10801 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
10802    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
10803    1,                         /* bCoreMutex */
10804    SQLITE_THREADSAFE==1,      /* bFullMutex */
10805    0x7ffffffe,                /* mxStrlen */
10806    100,                       /* szLookaside */
10807    500,                       /* nLookaside */
10808    {0,0,0,0,0,0,0,0},         /* m */
10809    {0,0,0,0,0,0,0,0,0},       /* mutex */
10810    {0,0,0,0,0,0,0,0,0,0,0},   /* pcache */
10811    (void*)0,                  /* pHeap */
10812    0,                         /* nHeap */
10813    0, 0,                      /* mnHeap, mxHeap */
10814    (void*)0,                  /* pScratch */
10815    0,                         /* szScratch */
10816    0,                         /* nScratch */
10817    (void*)0,                  /* pPage */
10818    0,                         /* szPage */
10819    0,                         /* nPage */
10820    0,                         /* mxParserStack */
10821    0,                         /* sharedCacheEnabled */
10822    /* All the rest should always be initialized to zero */
10823    0,                         /* isInit */
10824    0,                         /* inProgress */
10825    0,                         /* isMutexInit */
10826    0,                         /* isMallocInit */
10827    0,                         /* isPCacheInit */
10828    0,                         /* pInitMutex */
10829    0,                         /* nRefInitMutex */
10830    0,                         /* xLog */
10831    0,                         /* pLogArg */
10832 };
10833
10834
10835 /*
10836 ** Hash table for global functions - functions common to all
10837 ** database connections.  After initialization, this table is
10838 ** read-only.
10839 */
10840 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
10841
10842 /*
10843 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
10844 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
10845 ** the database page that contains the pending byte.  It never attempts
10846 ** to read or write that page.  The pending byte page is set assign
10847 ** for use by the VFS layers as space for managing file locks.
10848 **
10849 ** During testing, it is often desirable to move the pending byte to
10850 ** a different position in the file.  This allows code that has to
10851 ** deal with the pending byte to run on files that are much smaller
10852 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
10853 ** move the pending byte.
10854 **
10855 ** IMPORTANT:  Changing the pending byte to any value other than
10856 ** 0x40000000 results in an incompatible database file format!
10857 ** Changing the pending byte during operating results in undefined
10858 ** and dileterious behavior.
10859 */
10860 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
10861
10862 /*
10863 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
10864 ** created by mkopcodeh.awk during compilation.  Data is obtained
10865 ** from the comments following the "case OP_xxxx:" statements in
10866 ** the vdbe.c file.  
10867 */
10868 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
10869
10870 /************** End of global.c **********************************************/
10871 /************** Begin file ctime.c *******************************************/
10872 /*
10873 ** 2010 February 23
10874 **
10875 ** The author disclaims copyright to this source code.  In place of
10876 ** a legal notice, here is a blessing:
10877 **
10878 **    May you do good and not evil.
10879 **    May you find forgiveness for yourself and forgive others.
10880 **    May you share freely, never taking more than you give.
10881 **
10882 *************************************************************************
10883 **
10884 ** This file implements routines used to report what compile-time options
10885 ** SQLite was built with.
10886 */
10887
10888 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
10889
10890
10891 /*
10892 ** An array of names of all compile-time options.  This array should 
10893 ** be sorted A-Z.
10894 **
10895 ** This array looks large, but in a typical installation actually uses
10896 ** only a handful of compile-time options, so most times this array is usually
10897 ** rather short and uses little memory space.
10898 */
10899 static const char * const azCompileOpt[] = {
10900
10901 /* These macros are provided to "stringify" the value of the define
10902 ** for those options in which the value is meaningful. */
10903 #define CTIMEOPT_VAL_(opt) #opt
10904 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
10905
10906 #ifdef SQLITE_32BIT_ROWID
10907   "32BIT_ROWID",
10908 #endif
10909 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
10910   "4_BYTE_ALIGNED_MALLOC",
10911 #endif
10912 #ifdef SQLITE_CASE_SENSITIVE_LIKE
10913   "CASE_SENSITIVE_LIKE",
10914 #endif
10915 #ifdef SQLITE_CHECK_PAGES
10916   "CHECK_PAGES",
10917 #endif
10918 #ifdef SQLITE_COVERAGE_TEST
10919   "COVERAGE_TEST",
10920 #endif
10921 #ifdef SQLITE_DEBUG
10922   "DEBUG",
10923 #endif
10924 #ifdef SQLITE_DEFAULT_LOCKING_MODE
10925   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
10926 #endif
10927 #ifdef SQLITE_DISABLE_DIRSYNC
10928   "DISABLE_DIRSYNC",
10929 #endif
10930 #ifdef SQLITE_DISABLE_LFS
10931   "DISABLE_LFS",
10932 #endif
10933 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
10934   "ENABLE_ATOMIC_WRITE",
10935 #endif
10936 #ifdef SQLITE_ENABLE_CEROD
10937   "ENABLE_CEROD",
10938 #endif
10939 #ifdef SQLITE_ENABLE_COLUMN_METADATA
10940   "ENABLE_COLUMN_METADATA",
10941 #endif
10942 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
10943   "ENABLE_EXPENSIVE_ASSERT",
10944 #endif
10945 #ifdef SQLITE_ENABLE_FTS1
10946   "ENABLE_FTS1",
10947 #endif
10948 #ifdef SQLITE_ENABLE_FTS2
10949   "ENABLE_FTS2",
10950 #endif
10951 #ifdef SQLITE_ENABLE_FTS3
10952   "ENABLE_FTS3",
10953 #endif
10954 #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
10955   "ENABLE_FTS3_PARENTHESIS",
10956 #endif
10957 #ifdef SQLITE_ENABLE_FTS4
10958   "ENABLE_FTS4",
10959 #endif
10960 #ifdef SQLITE_ENABLE_ICU
10961   "ENABLE_ICU",
10962 #endif
10963 #ifdef SQLITE_ENABLE_IOTRACE
10964   "ENABLE_IOTRACE",
10965 #endif
10966 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
10967   "ENABLE_LOAD_EXTENSION",
10968 #endif
10969 #ifdef SQLITE_ENABLE_LOCKING_STYLE
10970   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
10971 #endif
10972 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
10973   "ENABLE_MEMORY_MANAGEMENT",
10974 #endif
10975 #ifdef SQLITE_ENABLE_MEMSYS3
10976   "ENABLE_MEMSYS3",
10977 #endif
10978 #ifdef SQLITE_ENABLE_MEMSYS5
10979   "ENABLE_MEMSYS5",
10980 #endif
10981 #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
10982   "ENABLE_OVERSIZE_CELL_CHECK",
10983 #endif
10984 #ifdef SQLITE_ENABLE_RTREE
10985   "ENABLE_RTREE",
10986 #endif
10987 #ifdef SQLITE_ENABLE_STAT2
10988   "ENABLE_STAT2",
10989 #endif
10990 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
10991   "ENABLE_UNLOCK_NOTIFY",
10992 #endif
10993 #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
10994   "ENABLE_UPDATE_DELETE_LIMIT",
10995 #endif
10996 #ifdef SQLITE_HAS_CODEC
10997   "HAS_CODEC",
10998 #endif
10999 #ifdef SQLITE_HAVE_ISNAN
11000   "HAVE_ISNAN",
11001 #endif
11002 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
11003   "HOMEGROWN_RECURSIVE_MUTEX",
11004 #endif
11005 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
11006   "IGNORE_AFP_LOCK_ERRORS",
11007 #endif
11008 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
11009   "IGNORE_FLOCK_LOCK_ERRORS",
11010 #endif
11011 #ifdef SQLITE_INT64_TYPE
11012   "INT64_TYPE",
11013 #endif
11014 #ifdef SQLITE_LOCK_TRACE
11015   "LOCK_TRACE",
11016 #endif
11017 #ifdef SQLITE_MEMDEBUG
11018   "MEMDEBUG",
11019 #endif
11020 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
11021   "MIXED_ENDIAN_64BIT_FLOAT",
11022 #endif
11023 #ifdef SQLITE_NO_SYNC
11024   "NO_SYNC",
11025 #endif
11026 #ifdef SQLITE_OMIT_ALTERTABLE
11027   "OMIT_ALTERTABLE",
11028 #endif
11029 #ifdef SQLITE_OMIT_ANALYZE
11030   "OMIT_ANALYZE",
11031 #endif
11032 #ifdef SQLITE_OMIT_ATTACH
11033   "OMIT_ATTACH",
11034 #endif
11035 #ifdef SQLITE_OMIT_AUTHORIZATION
11036   "OMIT_AUTHORIZATION",
11037 #endif
11038 #ifdef SQLITE_OMIT_AUTOINCREMENT
11039   "OMIT_AUTOINCREMENT",
11040 #endif
11041 #ifdef SQLITE_OMIT_AUTOINIT
11042   "OMIT_AUTOINIT",
11043 #endif
11044 #ifdef SQLITE_OMIT_AUTOVACUUM
11045   "OMIT_AUTOVACUUM",
11046 #endif
11047 #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
11048   "OMIT_BETWEEN_OPTIMIZATION",
11049 #endif
11050 #ifdef SQLITE_OMIT_BLOB_LITERAL
11051   "OMIT_BLOB_LITERAL",
11052 #endif
11053 #ifdef SQLITE_OMIT_BTREECOUNT
11054   "OMIT_BTREECOUNT",
11055 #endif
11056 #ifdef SQLITE_OMIT_BUILTIN_TEST
11057   "OMIT_BUILTIN_TEST",
11058 #endif
11059 #ifdef SQLITE_OMIT_CAST
11060   "OMIT_CAST",
11061 #endif
11062 #ifdef SQLITE_OMIT_CHECK
11063   "OMIT_CHECK",
11064 #endif
11065 #ifdef SQLITE_OMIT_COMPILEOPTION_DIAGS
11066   "OMIT_COMPILEOPTION_DIAGS",
11067 #endif
11068 #ifdef SQLITE_OMIT_COMPLETE
11069   "OMIT_COMPLETE",
11070 #endif
11071 #ifdef SQLITE_OMIT_COMPOUND_SELECT
11072   "OMIT_COMPOUND_SELECT",
11073 #endif
11074 #ifdef SQLITE_OMIT_DATETIME_FUNCS
11075   "OMIT_DATETIME_FUNCS",
11076 #endif
11077 #ifdef SQLITE_OMIT_DECLTYPE
11078   "OMIT_DECLTYPE",
11079 #endif
11080 #ifdef SQLITE_OMIT_DEPRECATED
11081   "OMIT_DEPRECATED",
11082 #endif
11083 #ifdef SQLITE_OMIT_DISKIO
11084   "OMIT_DISKIO",
11085 #endif
11086 #ifdef SQLITE_OMIT_EXPLAIN
11087   "OMIT_EXPLAIN",
11088 #endif
11089 #ifdef SQLITE_OMIT_FLAG_PRAGMAS
11090   "OMIT_FLAG_PRAGMAS",
11091 #endif
11092 #ifdef SQLITE_OMIT_FLOATING_POINT
11093   "OMIT_FLOATING_POINT",
11094 #endif
11095 #ifdef SQLITE_OMIT_FOREIGN_KEY
11096   "OMIT_FOREIGN_KEY",
11097 #endif
11098 #ifdef SQLITE_OMIT_GET_TABLE
11099   "OMIT_GET_TABLE",
11100 #endif
11101 #ifdef SQLITE_OMIT_GLOBALRECOVER
11102   "OMIT_GLOBALRECOVER",
11103 #endif
11104 #ifdef SQLITE_OMIT_INCRBLOB
11105   "OMIT_INCRBLOB",
11106 #endif
11107 #ifdef SQLITE_OMIT_INTEGRITY_CHECK
11108   "OMIT_INTEGRITY_CHECK",
11109 #endif
11110 #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
11111   "OMIT_LIKE_OPTIMIZATION",
11112 #endif
11113 #ifdef SQLITE_OMIT_LOAD_EXTENSION
11114   "OMIT_LOAD_EXTENSION",
11115 #endif
11116 #ifdef SQLITE_OMIT_LOCALTIME
11117   "OMIT_LOCALTIME",
11118 #endif
11119 #ifdef SQLITE_OMIT_LOOKASIDE
11120   "OMIT_LOOKASIDE",
11121 #endif
11122 #ifdef SQLITE_OMIT_MEMORYDB
11123   "OMIT_MEMORYDB",
11124 #endif
11125 #ifdef SQLITE_OMIT_OR_OPTIMIZATION
11126   "OMIT_OR_OPTIMIZATION",
11127 #endif
11128 #ifdef SQLITE_OMIT_PAGER_PRAGMAS
11129   "OMIT_PAGER_PRAGMAS",
11130 #endif
11131 #ifdef SQLITE_OMIT_PRAGMA
11132   "OMIT_PRAGMA",
11133 #endif
11134 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
11135   "OMIT_PROGRESS_CALLBACK",
11136 #endif
11137 #ifdef SQLITE_OMIT_QUICKBALANCE
11138   "OMIT_QUICKBALANCE",
11139 #endif
11140 #ifdef SQLITE_OMIT_REINDEX
11141   "OMIT_REINDEX",
11142 #endif
11143 #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
11144   "OMIT_SCHEMA_PRAGMAS",
11145 #endif
11146 #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
11147   "OMIT_SCHEMA_VERSION_PRAGMAS",
11148 #endif
11149 #ifdef SQLITE_OMIT_SHARED_CACHE
11150   "OMIT_SHARED_CACHE",
11151 #endif
11152 #ifdef SQLITE_OMIT_SUBQUERY
11153   "OMIT_SUBQUERY",
11154 #endif
11155 #ifdef SQLITE_OMIT_TCL_VARIABLE
11156   "OMIT_TCL_VARIABLE",
11157 #endif
11158 #ifdef SQLITE_OMIT_TEMPDB
11159   "OMIT_TEMPDB",
11160 #endif
11161 #ifdef SQLITE_OMIT_TRACE
11162   "OMIT_TRACE",
11163 #endif
11164 #ifdef SQLITE_OMIT_TRIGGER
11165   "OMIT_TRIGGER",
11166 #endif
11167 #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
11168   "OMIT_TRUNCATE_OPTIMIZATION",
11169 #endif
11170 #ifdef SQLITE_OMIT_UTF16
11171   "OMIT_UTF16",
11172 #endif
11173 #ifdef SQLITE_OMIT_VACUUM
11174   "OMIT_VACUUM",
11175 #endif
11176 #ifdef SQLITE_OMIT_VIEW
11177   "OMIT_VIEW",
11178 #endif
11179 #ifdef SQLITE_OMIT_VIRTUALTABLE
11180   "OMIT_VIRTUALTABLE",
11181 #endif
11182 #ifdef SQLITE_OMIT_WSD
11183   "OMIT_WSD",
11184 #endif
11185 #ifdef SQLITE_OMIT_XFER_OPT
11186   "OMIT_XFER_OPT",
11187 #endif
11188 #ifdef SQLITE_PERFORMANCE_TRACE
11189   "PERFORMANCE_TRACE",
11190 #endif
11191 #ifdef SQLITE_PROXY_DEBUG
11192   "PROXY_DEBUG",
11193 #endif
11194 #ifdef SQLITE_SECURE_DELETE
11195   "SECURE_DELETE",
11196 #endif
11197 #ifdef SQLITE_SMALL_STACK
11198   "SMALL_STACK",
11199 #endif
11200 #ifdef SQLITE_SOUNDEX
11201   "SOUNDEX",
11202 #endif
11203 #ifdef SQLITE_TCL
11204   "TCL",
11205 #endif
11206 #ifdef SQLITE_TEMP_STORE
11207   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
11208 #endif
11209 #ifdef SQLITE_TEST
11210   "TEST",
11211 #endif
11212 #ifdef SQLITE_THREADSAFE
11213   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
11214 #endif
11215 #ifdef SQLITE_USE_ALLOCA
11216   "USE_ALLOCA",
11217 #endif
11218 #ifdef SQLITE_ZERO_MALLOC
11219   "ZERO_MALLOC"
11220 #endif
11221 };
11222
11223 /*
11224 ** Given the name of a compile-time option, return true if that option
11225 ** was used and false if not.
11226 **
11227 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
11228 ** is not required for a match.
11229 */
11230 SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
11231   int i, n;
11232   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
11233   n = sqlite3Strlen30(zOptName);
11234
11235   /* Since ArraySize(azCompileOpt) is normally in single digits, a
11236   ** linear search is adequate.  No need for a binary search. */
11237   for(i=0; i<ArraySize(azCompileOpt); i++){
11238     if(   (sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0)
11239        && ( (azCompileOpt[i][n]==0) || (azCompileOpt[i][n]=='=') ) ) return 1;
11240   }
11241   return 0;
11242 }
11243
11244 /*
11245 ** Return the N-th compile-time option string.  If N is out of range,
11246 ** return a NULL pointer.
11247 */
11248 SQLITE_API const char *sqlite3_compileoption_get(int N){
11249   if( N>=0 && N<ArraySize(azCompileOpt) ){
11250     return azCompileOpt[N];
11251   }
11252   return 0;
11253 }
11254
11255 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
11256
11257 /************** End of ctime.c ***********************************************/
11258 /************** Begin file status.c ******************************************/
11259 /*
11260 ** 2008 June 18
11261 **
11262 ** The author disclaims copyright to this source code.  In place of
11263 ** a legal notice, here is a blessing:
11264 **
11265 **    May you do good and not evil.
11266 **    May you find forgiveness for yourself and forgive others.
11267 **    May you share freely, never taking more than you give.
11268 **
11269 *************************************************************************
11270 **
11271 ** This module implements the sqlite3_status() interface and related
11272 ** functionality.
11273 */
11274
11275 /*
11276 ** Variables in which to record status information.
11277 */
11278 typedef struct sqlite3StatType sqlite3StatType;
11279 static SQLITE_WSD struct sqlite3StatType {
11280   int nowValue[9];         /* Current value */
11281   int mxValue[9];          /* Maximum value */
11282 } sqlite3Stat = { {0,}, {0,} };
11283
11284
11285 /* The "wsdStat" macro will resolve to the status information
11286 ** state vector.  If writable static data is unsupported on the target,
11287 ** we have to locate the state vector at run-time.  In the more common
11288 ** case where writable static data is supported, wsdStat can refer directly
11289 ** to the "sqlite3Stat" state vector declared above.
11290 */
11291 #ifdef SQLITE_OMIT_WSD
11292 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
11293 # define wsdStat x[0]
11294 #else
11295 # define wsdStatInit
11296 # define wsdStat sqlite3Stat
11297 #endif
11298
11299 /*
11300 ** Return the current value of a status parameter.
11301 */
11302 SQLITE_PRIVATE int sqlite3StatusValue(int op){
11303   wsdStatInit;
11304   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
11305   return wsdStat.nowValue[op];
11306 }
11307
11308 /*
11309 ** Add N to the value of a status record.  It is assumed that the
11310 ** caller holds appropriate locks.
11311 */
11312 SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
11313   wsdStatInit;
11314   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
11315   wsdStat.nowValue[op] += N;
11316   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
11317     wsdStat.mxValue[op] = wsdStat.nowValue[op];
11318   }
11319 }
11320
11321 /*
11322 ** Set the value of a status to X.
11323 */
11324 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
11325   wsdStatInit;
11326   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
11327   wsdStat.nowValue[op] = X;
11328   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
11329     wsdStat.mxValue[op] = wsdStat.nowValue[op];
11330   }
11331 }
11332
11333 /*
11334 ** Query status information.
11335 **
11336 ** This implementation assumes that reading or writing an aligned
11337 ** 32-bit integer is an atomic operation.  If that assumption is not true,
11338 ** then this routine is not threadsafe.
11339 */
11340 SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
11341   wsdStatInit;
11342   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
11343     return SQLITE_MISUSE_BKPT;
11344   }
11345   *pCurrent = wsdStat.nowValue[op];
11346   *pHighwater = wsdStat.mxValue[op];
11347   if( resetFlag ){
11348     wsdStat.mxValue[op] = wsdStat.nowValue[op];
11349   }
11350   return SQLITE_OK;
11351 }
11352
11353 /*
11354 ** Query status information for a single database connection
11355 */
11356 SQLITE_API int sqlite3_db_status(
11357   sqlite3 *db,          /* The database connection whose status is desired */
11358   int op,               /* Status verb */
11359   int *pCurrent,        /* Write current value here */
11360   int *pHighwater,      /* Write high-water mark here */
11361   int resetFlag         /* Reset high-water mark if true */
11362 ){
11363   switch( op ){
11364     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
11365       *pCurrent = db->lookaside.nOut;
11366       *pHighwater = db->lookaside.mxOut;
11367       if( resetFlag ){
11368         db->lookaside.mxOut = db->lookaside.nOut;
11369       }
11370       break;
11371     }
11372     default: {
11373       return SQLITE_ERROR;
11374     }
11375   }
11376   return SQLITE_OK;
11377 }
11378
11379 /************** End of status.c **********************************************/
11380 /************** Begin file date.c ********************************************/
11381 /*
11382 ** 2003 October 31
11383 **
11384 ** The author disclaims copyright to this source code.  In place of
11385 ** a legal notice, here is a blessing:
11386 **
11387 **    May you do good and not evil.
11388 **    May you find forgiveness for yourself and forgive others.
11389 **    May you share freely, never taking more than you give.
11390 **
11391 *************************************************************************
11392 ** This file contains the C functions that implement date and time
11393 ** functions for SQLite.  
11394 **
11395 ** There is only one exported symbol in this file - the function
11396 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
11397 ** All other code has file scope.
11398 **
11399 ** SQLite processes all times and dates as Julian Day numbers.  The
11400 ** dates and times are stored as the number of days since noon
11401 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
11402 ** calendar system. 
11403 **
11404 ** 1970-01-01 00:00:00 is JD 2440587.5
11405 ** 2000-01-01 00:00:00 is JD 2451544.5
11406 **
11407 ** This implemention requires years to be expressed as a 4-digit number
11408 ** which means that only dates between 0000-01-01 and 9999-12-31 can
11409 ** be represented, even though julian day numbers allow a much wider
11410 ** range of dates.
11411 **
11412 ** The Gregorian calendar system is used for all dates and times,
11413 ** even those that predate the Gregorian calendar.  Historians usually
11414 ** use the Julian calendar for dates prior to 1582-10-15 and for some
11415 ** dates afterwards, depending on locale.  Beware of this difference.
11416 **
11417 ** The conversion algorithms are implemented based on descriptions
11418 ** in the following text:
11419 **
11420 **      Jean Meeus
11421 **      Astronomical Algorithms, 2nd Edition, 1998
11422 **      ISBM 0-943396-61-1
11423 **      Willmann-Bell, Inc
11424 **      Richmond, Virginia (USA)
11425 */
11426 #include <time.h>
11427
11428 #ifndef SQLITE_OMIT_DATETIME_FUNCS
11429
11430 /*
11431 ** On recent Windows platforms, the localtime_s() function is available
11432 ** as part of the "Secure CRT". It is essentially equivalent to 
11433 ** localtime_r() available under most POSIX platforms, except that the 
11434 ** order of the parameters is reversed.
11435 **
11436 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
11437 **
11438 ** If the user has not indicated to use localtime_r() or localtime_s()
11439 ** already, check for an MSVC build environment that provides 
11440 ** localtime_s().
11441 */
11442 #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
11443      defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
11444 #define HAVE_LOCALTIME_S 1
11445 #endif
11446
11447 /*
11448 ** A structure for holding a single date and time.
11449 */
11450 typedef struct DateTime DateTime;
11451 struct DateTime {
11452   sqlite3_int64 iJD; /* The julian day number times 86400000 */
11453   int Y, M, D;       /* Year, month, and day */
11454   int h, m;          /* Hour and minutes */
11455   int tz;            /* Timezone offset in minutes */
11456   double s;          /* Seconds */
11457   char validYMD;     /* True (1) if Y,M,D are valid */
11458   char validHMS;     /* True (1) if h,m,s are valid */
11459   char validJD;      /* True (1) if iJD is valid */
11460   char validTZ;      /* True (1) if tz is valid */
11461 };
11462
11463
11464 /*
11465 ** Convert zDate into one or more integers.  Additional arguments
11466 ** come in groups of 5 as follows:
11467 **
11468 **       N       number of digits in the integer
11469 **       min     minimum allowed value of the integer
11470 **       max     maximum allowed value of the integer
11471 **       nextC   first character after the integer
11472 **       pVal    where to write the integers value.
11473 **
11474 ** Conversions continue until one with nextC==0 is encountered.
11475 ** The function returns the number of successful conversions.
11476 */
11477 static int getDigits(const char *zDate, ...){
11478   va_list ap;
11479   int val;
11480   int N;
11481   int min;
11482   int max;
11483   int nextC;
11484   int *pVal;
11485   int cnt = 0;
11486   va_start(ap, zDate);
11487   do{
11488     N = va_arg(ap, int);
11489     min = va_arg(ap, int);
11490     max = va_arg(ap, int);
11491     nextC = va_arg(ap, int);
11492     pVal = va_arg(ap, int*);
11493     val = 0;
11494     while( N-- ){
11495       if( !sqlite3Isdigit(*zDate) ){
11496         goto end_getDigits;
11497       }
11498       val = val*10 + *zDate - '0';
11499       zDate++;
11500     }
11501     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
11502       goto end_getDigits;
11503     }
11504     *pVal = val;
11505     zDate++;
11506     cnt++;
11507   }while( nextC );
11508 end_getDigits:
11509   va_end(ap);
11510   return cnt;
11511 }
11512
11513 /*
11514 ** Read text from z[] and convert into a floating point number.  Return
11515 ** the number of digits converted.
11516 */
11517 #define getValue sqlite3AtoF
11518
11519 /*
11520 ** Parse a timezone extension on the end of a date-time.
11521 ** The extension is of the form:
11522 **
11523 **        (+/-)HH:MM
11524 **
11525 ** Or the "zulu" notation:
11526 **
11527 **        Z
11528 **
11529 ** If the parse is successful, write the number of minutes
11530 ** of change in p->tz and return 0.  If a parser error occurs,
11531 ** return non-zero.
11532 **
11533 ** A missing specifier is not considered an error.
11534 */
11535 static int parseTimezone(const char *zDate, DateTime *p){
11536   int sgn = 0;
11537   int nHr, nMn;
11538   int c;
11539   while( sqlite3Isspace(*zDate) ){ zDate++; }
11540   p->tz = 0;
11541   c = *zDate;
11542   if( c=='-' ){
11543     sgn = -1;
11544   }else if( c=='+' ){
11545     sgn = +1;
11546   }else if( c=='Z' || c=='z' ){
11547     zDate++;
11548     goto zulu_time;
11549   }else{
11550     return c!=0;
11551   }
11552   zDate++;
11553   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
11554     return 1;
11555   }
11556   zDate += 5;
11557   p->tz = sgn*(nMn + nHr*60);
11558 zulu_time:
11559   while( sqlite3Isspace(*zDate) ){ zDate++; }
11560   return *zDate!=0;
11561 }
11562
11563 /*
11564 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
11565 ** The HH, MM, and SS must each be exactly 2 digits.  The
11566 ** fractional seconds FFFF can be one or more digits.
11567 **
11568 ** Return 1 if there is a parsing error and 0 on success.
11569 */
11570 static int parseHhMmSs(const char *zDate, DateTime *p){
11571   int h, m, s;
11572   double ms = 0.0;
11573   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
11574     return 1;
11575   }
11576   zDate += 5;
11577   if( *zDate==':' ){
11578     zDate++;
11579     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
11580       return 1;
11581     }
11582     zDate += 2;
11583     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
11584       double rScale = 1.0;
11585       zDate++;
11586       while( sqlite3Isdigit(*zDate) ){
11587         ms = ms*10.0 + *zDate - '0';
11588         rScale *= 10.0;
11589         zDate++;
11590       }
11591       ms /= rScale;
11592     }
11593   }else{
11594     s = 0;
11595   }
11596   p->validJD = 0;
11597   p->validHMS = 1;
11598   p->h = h;
11599   p->m = m;
11600   p->s = s + ms;
11601   if( parseTimezone(zDate, p) ) return 1;
11602   p->validTZ = (p->tz!=0)?1:0;
11603   return 0;
11604 }
11605
11606 /*
11607 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
11608 ** that the YYYY-MM-DD is according to the Gregorian calendar.
11609 **
11610 ** Reference:  Meeus page 61
11611 */
11612 static void computeJD(DateTime *p){
11613   int Y, M, D, A, B, X1, X2;
11614
11615   if( p->validJD ) return;
11616   if( p->validYMD ){
11617     Y = p->Y;
11618     M = p->M;
11619     D = p->D;
11620   }else{
11621     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
11622     M = 1;
11623     D = 1;
11624   }
11625   if( M<=2 ){
11626     Y--;
11627     M += 12;
11628   }
11629   A = Y/100;
11630   B = 2 - A + (A/4);
11631   X1 = 36525*(Y+4716)/100;
11632   X2 = 306001*(M+1)/10000;
11633   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
11634   p->validJD = 1;
11635   if( p->validHMS ){
11636     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
11637     if( p->validTZ ){
11638       p->iJD -= p->tz*60000;
11639       p->validYMD = 0;
11640       p->validHMS = 0;
11641       p->validTZ = 0;
11642     }
11643   }
11644 }
11645
11646 /*
11647 ** Parse dates of the form
11648 **
11649 **     YYYY-MM-DD HH:MM:SS.FFF
11650 **     YYYY-MM-DD HH:MM:SS
11651 **     YYYY-MM-DD HH:MM
11652 **     YYYY-MM-DD
11653 **
11654 ** Write the result into the DateTime structure and return 0
11655 ** on success and 1 if the input string is not a well-formed
11656 ** date.
11657 */
11658 static int parseYyyyMmDd(const char *zDate, DateTime *p){
11659   int Y, M, D, neg;
11660
11661   if( zDate[0]=='-' ){
11662     zDate++;
11663     neg = 1;
11664   }else{
11665     neg = 0;
11666   }
11667   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
11668     return 1;
11669   }
11670   zDate += 10;
11671   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
11672   if( parseHhMmSs(zDate, p)==0 ){
11673     /* We got the time */
11674   }else if( *zDate==0 ){
11675     p->validHMS = 0;
11676   }else{
11677     return 1;
11678   }
11679   p->validJD = 0;
11680   p->validYMD = 1;
11681   p->Y = neg ? -Y : Y;
11682   p->M = M;
11683   p->D = D;
11684   if( p->validTZ ){
11685     computeJD(p);
11686   }
11687   return 0;
11688 }
11689
11690 /*
11691 ** Set the time to the current time reported by the VFS
11692 */
11693 static void setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
11694   double r;
11695   sqlite3 *db = sqlite3_context_db_handle(context);
11696   sqlite3OsCurrentTime(db->pVfs, &r);
11697   p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
11698   p->validJD = 1;
11699 }
11700
11701 /*
11702 ** Attempt to parse the given string into a Julian Day Number.  Return
11703 ** the number of errors.
11704 **
11705 ** The following are acceptable forms for the input string:
11706 **
11707 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
11708 **      DDDD.DD 
11709 **      now
11710 **
11711 ** In the first form, the +/-HH:MM is always optional.  The fractional
11712 ** seconds extension (the ".FFF") is optional.  The seconds portion
11713 ** (":SS.FFF") is option.  The year and date can be omitted as long
11714 ** as there is a time string.  The time string can be omitted as long
11715 ** as there is a year and date.
11716 */
11717 static int parseDateOrTime(
11718   sqlite3_context *context, 
11719   const char *zDate, 
11720   DateTime *p
11721 ){
11722   int isRealNum;    /* Return from sqlite3IsNumber().  Not used */
11723   if( parseYyyyMmDd(zDate,p)==0 ){
11724     return 0;
11725   }else if( parseHhMmSs(zDate, p)==0 ){
11726     return 0;
11727   }else if( sqlite3StrICmp(zDate,"now")==0){
11728     setDateTimeToCurrent(context, p);
11729     return 0;
11730   }else if( sqlite3IsNumber(zDate, &isRealNum, SQLITE_UTF8) ){
11731     double r;
11732     getValue(zDate, &r);
11733     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
11734     p->validJD = 1;
11735     return 0;
11736   }
11737   return 1;
11738 }
11739
11740 /*
11741 ** Compute the Year, Month, and Day from the julian day number.
11742 */
11743 static void computeYMD(DateTime *p){
11744   int Z, A, B, C, D, E, X1;
11745   if( p->validYMD ) return;
11746   if( !p->validJD ){
11747     p->Y = 2000;
11748     p->M = 1;
11749     p->D = 1;
11750   }else{
11751     Z = (int)((p->iJD + 43200000)/86400000);
11752     A = (int)((Z - 1867216.25)/36524.25);
11753     A = Z + 1 + A - (A/4);
11754     B = A + 1524;
11755     C = (int)((B - 122.1)/365.25);
11756     D = (36525*C)/100;
11757     E = (int)((B-D)/30.6001);
11758     X1 = (int)(30.6001*E);
11759     p->D = B - D - X1;
11760     p->M = E<14 ? E-1 : E-13;
11761     p->Y = p->M>2 ? C - 4716 : C - 4715;
11762   }
11763   p->validYMD = 1;
11764 }
11765
11766 /*
11767 ** Compute the Hour, Minute, and Seconds from the julian day number.
11768 */
11769 static void computeHMS(DateTime *p){
11770   int s;
11771   if( p->validHMS ) return;
11772   computeJD(p);
11773   s = (int)((p->iJD + 43200000) % 86400000);
11774   p->s = s/1000.0;
11775   s = (int)p->s;
11776   p->s -= s;
11777   p->h = s/3600;
11778   s -= p->h*3600;
11779   p->m = s/60;
11780   p->s += s - p->m*60;
11781   p->validHMS = 1;
11782 }
11783
11784 /*
11785 ** Compute both YMD and HMS
11786 */
11787 static void computeYMD_HMS(DateTime *p){
11788   computeYMD(p);
11789   computeHMS(p);
11790 }
11791
11792 /*
11793 ** Clear the YMD and HMS and the TZ
11794 */
11795 static void clearYMD_HMS_TZ(DateTime *p){
11796   p->validYMD = 0;
11797   p->validHMS = 0;
11798   p->validTZ = 0;
11799 }
11800
11801 #ifndef SQLITE_OMIT_LOCALTIME
11802 /*
11803 ** Compute the difference (in milliseconds)
11804 ** between localtime and UTC (a.k.a. GMT)
11805 ** for the time value p where p is in UTC.
11806 */
11807 static sqlite3_int64 localtimeOffset(DateTime *p){
11808   DateTime x, y;
11809   time_t t;
11810   x = *p;
11811   computeYMD_HMS(&x);
11812   if( x.Y<1971 || x.Y>=2038 ){
11813     x.Y = 2000;
11814     x.M = 1;
11815     x.D = 1;
11816     x.h = 0;
11817     x.m = 0;
11818     x.s = 0.0;
11819   } else {
11820     int s = (int)(x.s + 0.5);
11821     x.s = s;
11822   }
11823   x.tz = 0;
11824   x.validJD = 0;
11825   computeJD(&x);
11826   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
11827 #ifdef HAVE_LOCALTIME_R
11828   {
11829     struct tm sLocal;
11830     localtime_r(&t, &sLocal);
11831     y.Y = sLocal.tm_year + 1900;
11832     y.M = sLocal.tm_mon + 1;
11833     y.D = sLocal.tm_mday;
11834     y.h = sLocal.tm_hour;
11835     y.m = sLocal.tm_min;
11836     y.s = sLocal.tm_sec;
11837   }
11838 #elif defined(HAVE_LOCALTIME_S) && HAVE_LOCALTIME_S
11839   {
11840     struct tm sLocal;
11841     localtime_s(&sLocal, &t);
11842     y.Y = sLocal.tm_year + 1900;
11843     y.M = sLocal.tm_mon + 1;
11844     y.D = sLocal.tm_mday;
11845     y.h = sLocal.tm_hour;
11846     y.m = sLocal.tm_min;
11847     y.s = sLocal.tm_sec;
11848   }
11849 #else
11850   {
11851     struct tm *pTm;
11852     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11853     pTm = localtime(&t);
11854     y.Y = pTm->tm_year + 1900;
11855     y.M = pTm->tm_mon + 1;
11856     y.D = pTm->tm_mday;
11857     y.h = pTm->tm_hour;
11858     y.m = pTm->tm_min;
11859     y.s = pTm->tm_sec;
11860     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
11861   }
11862 #endif
11863   y.validYMD = 1;
11864   y.validHMS = 1;
11865   y.validJD = 0;
11866   y.validTZ = 0;
11867   computeJD(&y);
11868   return y.iJD - x.iJD;
11869 }
11870 #endif /* SQLITE_OMIT_LOCALTIME */
11871
11872 /*
11873 ** Process a modifier to a date-time stamp.  The modifiers are
11874 ** as follows:
11875 **
11876 **     NNN days
11877 **     NNN hours
11878 **     NNN minutes
11879 **     NNN.NNNN seconds
11880 **     NNN months
11881 **     NNN years
11882 **     start of month
11883 **     start of year
11884 **     start of week
11885 **     start of day
11886 **     weekday N
11887 **     unixepoch
11888 **     localtime
11889 **     utc
11890 **
11891 ** Return 0 on success and 1 if there is any kind of error.
11892 */
11893 static int parseModifier(const char *zMod, DateTime *p){
11894   int rc = 1;
11895   int n;
11896   double r;
11897   char *z, zBuf[30];
11898   z = zBuf;
11899   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
11900     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
11901   }
11902   z[n] = 0;
11903   switch( z[0] ){
11904 #ifndef SQLITE_OMIT_LOCALTIME
11905     case 'l': {
11906       /*    localtime
11907       **
11908       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
11909       ** show local time.
11910       */
11911       if( strcmp(z, "localtime")==0 ){
11912         computeJD(p);
11913         p->iJD += localtimeOffset(p);
11914         clearYMD_HMS_TZ(p);
11915         rc = 0;
11916       }
11917       break;
11918     }
11919 #endif
11920     case 'u': {
11921       /*
11922       **    unixepoch
11923       **
11924       ** Treat the current value of p->iJD as the number of
11925       ** seconds since 1970.  Convert to a real julian day number.
11926       */
11927       if( strcmp(z, "unixepoch")==0 && p->validJD ){
11928         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
11929         clearYMD_HMS_TZ(p);
11930         rc = 0;
11931       }
11932 #ifndef SQLITE_OMIT_LOCALTIME
11933       else if( strcmp(z, "utc")==0 ){
11934         sqlite3_int64 c1;
11935         computeJD(p);
11936         c1 = localtimeOffset(p);
11937         p->iJD -= c1;
11938         clearYMD_HMS_TZ(p);
11939         p->iJD += c1 - localtimeOffset(p);
11940         rc = 0;
11941       }
11942 #endif
11943       break;
11944     }
11945     case 'w': {
11946       /*
11947       **    weekday N
11948       **
11949       ** Move the date to the same time on the next occurrence of
11950       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
11951       ** date is already on the appropriate weekday, this is a no-op.
11952       */
11953       if( strncmp(z, "weekday ", 8)==0 && getValue(&z[8],&r)>0
11954                  && (n=(int)r)==r && n>=0 && r<7 ){
11955         sqlite3_int64 Z;
11956         computeYMD_HMS(p);
11957         p->validTZ = 0;
11958         p->validJD = 0;
11959         computeJD(p);
11960         Z = ((p->iJD + 129600000)/86400000) % 7;
11961         if( Z>n ) Z -= 7;
11962         p->iJD += (n - Z)*86400000;
11963         clearYMD_HMS_TZ(p);
11964         rc = 0;
11965       }
11966       break;
11967     }
11968     case 's': {
11969       /*
11970       **    start of TTTTT
11971       **
11972       ** Move the date backwards to the beginning of the current day,
11973       ** or month or year.
11974       */
11975       if( strncmp(z, "start of ", 9)!=0 ) break;
11976       z += 9;
11977       computeYMD(p);
11978       p->validHMS = 1;
11979       p->h = p->m = 0;
11980       p->s = 0.0;
11981       p->validTZ = 0;
11982       p->validJD = 0;
11983       if( strcmp(z,"month")==0 ){
11984         p->D = 1;
11985         rc = 0;
11986       }else if( strcmp(z,"year")==0 ){
11987         computeYMD(p);
11988         p->M = 1;
11989         p->D = 1;
11990         rc = 0;
11991       }else if( strcmp(z,"day")==0 ){
11992         rc = 0;
11993       }
11994       break;
11995     }
11996     case '+':
11997     case '-':
11998     case '0':
11999     case '1':
12000     case '2':
12001     case '3':
12002     case '4':
12003     case '5':
12004     case '6':
12005     case '7':
12006     case '8':
12007     case '9': {
12008       double rRounder;
12009       n = getValue(z, &r);
12010       assert( n>=1 );
12011       if( z[n]==':' ){
12012         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
12013         ** specified number of hours, minutes, seconds, and fractional seconds
12014         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
12015         ** omitted.
12016         */
12017         const char *z2 = z;
12018         DateTime tx;
12019         sqlite3_int64 day;
12020         if( !sqlite3Isdigit(*z2) ) z2++;
12021         memset(&tx, 0, sizeof(tx));
12022         if( parseHhMmSs(z2, &tx) ) break;
12023         computeJD(&tx);
12024         tx.iJD -= 43200000;
12025         day = tx.iJD/86400000;
12026         tx.iJD -= day*86400000;
12027         if( z[0]=='-' ) tx.iJD = -tx.iJD;
12028         computeJD(p);
12029         clearYMD_HMS_TZ(p);
12030         p->iJD += tx.iJD;
12031         rc = 0;
12032         break;
12033       }
12034       z += n;
12035       while( sqlite3Isspace(*z) ) z++;
12036       n = sqlite3Strlen30(z);
12037       if( n>10 || n<3 ) break;
12038       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
12039       computeJD(p);
12040       rc = 0;
12041       rRounder = r<0 ? -0.5 : +0.5;
12042       if( n==3 && strcmp(z,"day")==0 ){
12043         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
12044       }else if( n==4 && strcmp(z,"hour")==0 ){
12045         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
12046       }else if( n==6 && strcmp(z,"minute")==0 ){
12047         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
12048       }else if( n==6 && strcmp(z,"second")==0 ){
12049         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
12050       }else if( n==5 && strcmp(z,"month")==0 ){
12051         int x, y;
12052         computeYMD_HMS(p);
12053         p->M += (int)r;
12054         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
12055         p->Y += x;
12056         p->M -= x*12;
12057         p->validJD = 0;
12058         computeJD(p);
12059         y = (int)r;
12060         if( y!=r ){
12061           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
12062         }
12063       }else if( n==4 && strcmp(z,"year")==0 ){
12064         int y = (int)r;
12065         computeYMD_HMS(p);
12066         p->Y += y;
12067         p->validJD = 0;
12068         computeJD(p);
12069         if( y!=r ){
12070           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
12071         }
12072       }else{
12073         rc = 1;
12074       }
12075       clearYMD_HMS_TZ(p);
12076       break;
12077     }
12078     default: {
12079       break;
12080     }
12081   }
12082   return rc;
12083 }
12084
12085 /*
12086 ** Process time function arguments.  argv[0] is a date-time stamp.
12087 ** argv[1] and following are modifiers.  Parse them all and write
12088 ** the resulting time into the DateTime structure p.  Return 0
12089 ** on success and 1 if there are any errors.
12090 **
12091 ** If there are zero parameters (if even argv[0] is undefined)
12092 ** then assume a default value of "now" for argv[0].
12093 */
12094 static int isDate(
12095   sqlite3_context *context, 
12096   int argc, 
12097   sqlite3_value **argv, 
12098   DateTime *p
12099 ){
12100   int i;
12101   const unsigned char *z;
12102   int eType;
12103   memset(p, 0, sizeof(*p));
12104   if( argc==0 ){
12105     setDateTimeToCurrent(context, p);
12106   }else if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
12107                    || eType==SQLITE_INTEGER ){
12108     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
12109     p->validJD = 1;
12110   }else{
12111     z = sqlite3_value_text(argv[0]);
12112     if( !z || parseDateOrTime(context, (char*)z, p) ){
12113       return 1;
12114     }
12115   }
12116   for(i=1; i<argc; i++){
12117     if( (z = sqlite3_value_text(argv[i]))==0 || parseModifier((char*)z, p) ){
12118       return 1;
12119     }
12120   }
12121   return 0;
12122 }
12123
12124
12125 /*
12126 ** The following routines implement the various date and time functions
12127 ** of SQLite.
12128 */
12129
12130 /*
12131 **    julianday( TIMESTRING, MOD, MOD, ...)
12132 **
12133 ** Return the julian day number of the date specified in the arguments
12134 */
12135 static void juliandayFunc(
12136   sqlite3_context *context,
12137   int argc,
12138   sqlite3_value **argv
12139 ){
12140   DateTime x;
12141   if( isDate(context, argc, argv, &x)==0 ){
12142     computeJD(&x);
12143     sqlite3_result_double(context, x.iJD/86400000.0);
12144   }
12145 }
12146
12147 /*
12148 **    datetime( TIMESTRING, MOD, MOD, ...)
12149 **
12150 ** Return YYYY-MM-DD HH:MM:SS
12151 */
12152 static void datetimeFunc(
12153   sqlite3_context *context,
12154   int argc,
12155   sqlite3_value **argv
12156 ){
12157   DateTime x;
12158   if( isDate(context, argc, argv, &x)==0 ){
12159     char zBuf[100];
12160     computeYMD_HMS(&x);
12161     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
12162                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
12163     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12164   }
12165 }
12166
12167 /*
12168 **    time( TIMESTRING, MOD, MOD, ...)
12169 **
12170 ** Return HH:MM:SS
12171 */
12172 static void timeFunc(
12173   sqlite3_context *context,
12174   int argc,
12175   sqlite3_value **argv
12176 ){
12177   DateTime x;
12178   if( isDate(context, argc, argv, &x)==0 ){
12179     char zBuf[100];
12180     computeHMS(&x);
12181     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
12182     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12183   }
12184 }
12185
12186 /*
12187 **    date( TIMESTRING, MOD, MOD, ...)
12188 **
12189 ** Return YYYY-MM-DD
12190 */
12191 static void dateFunc(
12192   sqlite3_context *context,
12193   int argc,
12194   sqlite3_value **argv
12195 ){
12196   DateTime x;
12197   if( isDate(context, argc, argv, &x)==0 ){
12198     char zBuf[100];
12199     computeYMD(&x);
12200     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
12201     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12202   }
12203 }
12204
12205 /*
12206 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
12207 **
12208 ** Return a string described by FORMAT.  Conversions as follows:
12209 **
12210 **   %d  day of month
12211 **   %f  ** fractional seconds  SS.SSS
12212 **   %H  hour 00-24
12213 **   %j  day of year 000-366
12214 **   %J  ** Julian day number
12215 **   %m  month 01-12
12216 **   %M  minute 00-59
12217 **   %s  seconds since 1970-01-01
12218 **   %S  seconds 00-59
12219 **   %w  day of week 0-6  sunday==0
12220 **   %W  week of year 00-53
12221 **   %Y  year 0000-9999
12222 **   %%  %
12223 */
12224 static void strftimeFunc(
12225   sqlite3_context *context,
12226   int argc,
12227   sqlite3_value **argv
12228 ){
12229   DateTime x;
12230   u64 n;
12231   size_t i,j;
12232   char *z;
12233   sqlite3 *db;
12234   const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
12235   char zBuf[100];
12236   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
12237   db = sqlite3_context_db_handle(context);
12238   for(i=0, n=1; zFmt[i]; i++, n++){
12239     if( zFmt[i]=='%' ){
12240       switch( zFmt[i+1] ){
12241         case 'd':
12242         case 'H':
12243         case 'm':
12244         case 'M':
12245         case 'S':
12246         case 'W':
12247           n++;
12248           /* fall thru */
12249         case 'w':
12250         case '%':
12251           break;
12252         case 'f':
12253           n += 8;
12254           break;
12255         case 'j':
12256           n += 3;
12257           break;
12258         case 'Y':
12259           n += 8;
12260           break;
12261         case 's':
12262         case 'J':
12263           n += 50;
12264           break;
12265         default:
12266           return;  /* ERROR.  return a NULL */
12267       }
12268       i++;
12269     }
12270   }
12271   testcase( n==sizeof(zBuf)-1 );
12272   testcase( n==sizeof(zBuf) );
12273   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
12274   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
12275   if( n<sizeof(zBuf) ){
12276     z = zBuf;
12277   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
12278     sqlite3_result_error_toobig(context);
12279     return;
12280   }else{
12281     z = sqlite3DbMallocRaw(db, (int)n);
12282     if( z==0 ){
12283       sqlite3_result_error_nomem(context);
12284       return;
12285     }
12286   }
12287   computeJD(&x);
12288   computeYMD_HMS(&x);
12289   for(i=j=0; zFmt[i]; i++){
12290     if( zFmt[i]!='%' ){
12291       z[j++] = zFmt[i];
12292     }else{
12293       i++;
12294       switch( zFmt[i] ){
12295         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
12296         case 'f': {
12297           double s = x.s;
12298           if( s>59.999 ) s = 59.999;
12299           sqlite3_snprintf(7, &z[j],"%06.3f", s);
12300           j += sqlite3Strlen30(&z[j]);
12301           break;
12302         }
12303         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
12304         case 'W': /* Fall thru */
12305         case 'j': {
12306           int nDay;             /* Number of days since 1st day of year */
12307           DateTime y = x;
12308           y.validJD = 0;
12309           y.M = 1;
12310           y.D = 1;
12311           computeJD(&y);
12312           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
12313           if( zFmt[i]=='W' ){
12314             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
12315             wd = (int)(((x.iJD+43200000)/86400000)%7);
12316             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
12317             j += 2;
12318           }else{
12319             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
12320             j += 3;
12321           }
12322           break;
12323         }
12324         case 'J': {
12325           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
12326           j+=sqlite3Strlen30(&z[j]);
12327           break;
12328         }
12329         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
12330         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
12331         case 's': {
12332           sqlite3_snprintf(30,&z[j],"%lld",
12333                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
12334           j += sqlite3Strlen30(&z[j]);
12335           break;
12336         }
12337         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
12338         case 'w': {
12339           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
12340           break;
12341         }
12342         case 'Y': {
12343           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
12344           break;
12345         }
12346         default:   z[j++] = '%'; break;
12347       }
12348     }
12349   }
12350   z[j] = 0;
12351   sqlite3_result_text(context, z, -1,
12352                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
12353 }
12354
12355 /*
12356 ** current_time()
12357 **
12358 ** This function returns the same value as time('now').
12359 */
12360 static void ctimeFunc(
12361   sqlite3_context *context,
12362   int NotUsed,
12363   sqlite3_value **NotUsed2
12364 ){
12365   UNUSED_PARAMETER2(NotUsed, NotUsed2);
12366   timeFunc(context, 0, 0);
12367 }
12368
12369 /*
12370 ** current_date()
12371 **
12372 ** This function returns the same value as date('now').
12373 */
12374 static void cdateFunc(
12375   sqlite3_context *context,
12376   int NotUsed,
12377   sqlite3_value **NotUsed2
12378 ){
12379   UNUSED_PARAMETER2(NotUsed, NotUsed2);
12380   dateFunc(context, 0, 0);
12381 }
12382
12383 /*
12384 ** current_timestamp()
12385 **
12386 ** This function returns the same value as datetime('now').
12387 */
12388 static void ctimestampFunc(
12389   sqlite3_context *context,
12390   int NotUsed,
12391   sqlite3_value **NotUsed2
12392 ){
12393   UNUSED_PARAMETER2(NotUsed, NotUsed2);
12394   datetimeFunc(context, 0, 0);
12395 }
12396 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
12397
12398 #ifdef SQLITE_OMIT_DATETIME_FUNCS
12399 /*
12400 ** If the library is compiled to omit the full-scale date and time
12401 ** handling (to get a smaller binary), the following minimal version
12402 ** of the functions current_time(), current_date() and current_timestamp()
12403 ** are included instead. This is to support column declarations that
12404 ** include "DEFAULT CURRENT_TIME" etc.
12405 **
12406 ** This function uses the C-library functions time(), gmtime()
12407 ** and strftime(). The format string to pass to strftime() is supplied
12408 ** as the user-data for the function.
12409 */
12410 static void currentTimeFunc(
12411   sqlite3_context *context,
12412   int argc,
12413   sqlite3_value **argv
12414 ){
12415   time_t t;
12416   char *zFormat = (char *)sqlite3_user_data(context);
12417   sqlite3 *db;
12418   double rT;
12419   char zBuf[20];
12420
12421   UNUSED_PARAMETER(argc);
12422   UNUSED_PARAMETER(argv);
12423
12424   db = sqlite3_context_db_handle(context);
12425   sqlite3OsCurrentTime(db->pVfs, &rT);
12426 #ifndef SQLITE_OMIT_FLOATING_POINT
12427   t = 86400.0*(rT - 2440587.5) + 0.5;
12428 #else
12429   /* without floating point support, rT will have
12430   ** already lost fractional day precision.
12431   */
12432   t = 86400 * (rT - 2440587) - 43200;
12433 #endif
12434 #ifdef HAVE_GMTIME_R
12435   {
12436     struct tm sNow;
12437     gmtime_r(&t, &sNow);
12438     strftime(zBuf, 20, zFormat, &sNow);
12439   }
12440 #else
12441   {
12442     struct tm *pTm;
12443     sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12444     pTm = gmtime(&t);
12445     strftime(zBuf, 20, zFormat, pTm);
12446     sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
12447   }
12448 #endif
12449
12450   sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
12451 }
12452 #endif
12453
12454 /*
12455 ** This function registered all of the above C functions as SQL
12456 ** functions.  This should be the only routine in this file with
12457 ** external linkage.
12458 */
12459 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
12460   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
12461 #ifndef SQLITE_OMIT_DATETIME_FUNCS
12462     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
12463     FUNCTION(date,             -1, 0, 0, dateFunc      ),
12464     FUNCTION(time,             -1, 0, 0, timeFunc      ),
12465     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
12466     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
12467     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
12468     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
12469     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
12470 #else
12471     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
12472     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
12473     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
12474 #endif
12475   };
12476   int i;
12477   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
12478   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
12479
12480   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
12481     sqlite3FuncDefInsert(pHash, &aFunc[i]);
12482   }
12483 }
12484
12485 /************** End of date.c ************************************************/
12486 /************** Begin file os.c **********************************************/
12487 /*
12488 ** 2005 November 29
12489 **
12490 ** The author disclaims copyright to this source code.  In place of
12491 ** a legal notice, here is a blessing:
12492 **
12493 **    May you do good and not evil.
12494 **    May you find forgiveness for yourself and forgive others.
12495 **    May you share freely, never taking more than you give.
12496 **
12497 ******************************************************************************
12498 **
12499 ** This file contains OS interface code that is common to all
12500 ** architectures.
12501 */
12502 #define _SQLITE_OS_C_ 1
12503 #undef _SQLITE_OS_C_
12504
12505 /*
12506 ** The default SQLite sqlite3_vfs implementations do not allocate
12507 ** memory (actually, os_unix.c allocates a small amount of memory
12508 ** from within OsOpen()), but some third-party implementations may.
12509 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
12510 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
12511 **
12512 ** The following functions are instrumented for malloc() failure 
12513 ** testing:
12514 **
12515 **     sqlite3OsOpen()
12516 **     sqlite3OsRead()
12517 **     sqlite3OsWrite()
12518 **     sqlite3OsSync()
12519 **     sqlite3OsLock()
12520 **
12521 */
12522 #if defined(SQLITE_TEST) && (SQLITE_OS_WIN==0)
12523   #define DO_OS_MALLOC_TEST(x) if (!x || !sqlite3IsMemJournal(x)) {     \
12524     void *pTstAlloc = sqlite3Malloc(10);                             \
12525     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
12526     sqlite3_free(pTstAlloc);                                         \
12527   }
12528 #else
12529   #define DO_OS_MALLOC_TEST(x)
12530 #endif
12531
12532 /*
12533 ** The following routines are convenience wrappers around methods
12534 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
12535 ** of this would be completely automatic if SQLite were coded using
12536 ** C++ instead of plain old C.
12537 */
12538 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
12539   int rc = SQLITE_OK;
12540   if( pId->pMethods ){
12541     rc = pId->pMethods->xClose(pId);
12542     pId->pMethods = 0;
12543   }
12544   return rc;
12545 }
12546 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
12547   DO_OS_MALLOC_TEST(id);
12548   return id->pMethods->xRead(id, pBuf, amt, offset);
12549 }
12550 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
12551   DO_OS_MALLOC_TEST(id);
12552   return id->pMethods->xWrite(id, pBuf, amt, offset);
12553 }
12554 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
12555   return id->pMethods->xTruncate(id, size);
12556 }
12557 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
12558   DO_OS_MALLOC_TEST(id);
12559   return id->pMethods->xSync(id, flags);
12560 }
12561 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
12562   DO_OS_MALLOC_TEST(id);
12563   return id->pMethods->xFileSize(id, pSize);
12564 }
12565 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
12566   DO_OS_MALLOC_TEST(id);
12567   return id->pMethods->xLock(id, lockType);
12568 }
12569 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
12570   return id->pMethods->xUnlock(id, lockType);
12571 }
12572 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
12573   DO_OS_MALLOC_TEST(id);
12574   return id->pMethods->xCheckReservedLock(id, pResOut);
12575 }
12576 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
12577   return id->pMethods->xFileControl(id, op, pArg);
12578 }
12579 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
12580   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
12581   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
12582 }
12583 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
12584   return id->pMethods->xDeviceCharacteristics(id);
12585 }
12586
12587 /*
12588 ** The next group of routines are convenience wrappers around the
12589 ** VFS methods.
12590 */
12591 SQLITE_PRIVATE int sqlite3OsOpen(
12592   sqlite3_vfs *pVfs, 
12593   const char *zPath, 
12594   sqlite3_file *pFile, 
12595   int flags, 
12596   int *pFlagsOut
12597 ){
12598   int rc;
12599   DO_OS_MALLOC_TEST(0);
12600   /* 0x7f3f is a mask of SQLITE_OPEN_ flags that are valid to be passed
12601   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
12602   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
12603   ** reaching the VFS. */
12604   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x7f3f, pFlagsOut);
12605   assert( rc==SQLITE_OK || pFile->pMethods==0 );
12606   return rc;
12607 }
12608 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
12609   return pVfs->xDelete(pVfs, zPath, dirSync);
12610 }
12611 SQLITE_PRIVATE int sqlite3OsAccess(
12612   sqlite3_vfs *pVfs, 
12613   const char *zPath, 
12614   int flags, 
12615   int *pResOut
12616 ){
12617   DO_OS_MALLOC_TEST(0);
12618   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
12619 }
12620 SQLITE_PRIVATE int sqlite3OsFullPathname(
12621   sqlite3_vfs *pVfs, 
12622   const char *zPath, 
12623   int nPathOut, 
12624   char *zPathOut
12625 ){
12626   zPathOut[0] = 0;
12627   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
12628 }
12629 #ifndef SQLITE_OMIT_LOAD_EXTENSION
12630 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
12631   return pVfs->xDlOpen(pVfs, zPath);
12632 }
12633 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12634   pVfs->xDlError(pVfs, nByte, zBufOut);
12635 }
12636 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
12637   return pVfs->xDlSym(pVfs, pHdle, zSym);
12638 }
12639 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
12640   pVfs->xDlClose(pVfs, pHandle);
12641 }
12642 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
12643 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
12644   return pVfs->xRandomness(pVfs, nByte, zBufOut);
12645 }
12646 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
12647   return pVfs->xSleep(pVfs, nMicro);
12648 }
12649 SQLITE_PRIVATE int sqlite3OsCurrentTime(sqlite3_vfs *pVfs, double *pTimeOut){
12650   return pVfs->xCurrentTime(pVfs, pTimeOut);
12651 }
12652
12653 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
12654   sqlite3_vfs *pVfs, 
12655   const char *zFile, 
12656   sqlite3_file **ppFile, 
12657   int flags,
12658   int *pOutFlags
12659 ){
12660   int rc = SQLITE_NOMEM;
12661   sqlite3_file *pFile;
12662   pFile = (sqlite3_file *)sqlite3Malloc(pVfs->szOsFile);
12663   if( pFile ){
12664     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
12665     if( rc!=SQLITE_OK ){
12666       sqlite3_free(pFile);
12667     }else{
12668       *ppFile = pFile;
12669     }
12670   }
12671   return rc;
12672 }
12673 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
12674   int rc = SQLITE_OK;
12675   assert( pFile );
12676   rc = sqlite3OsClose(pFile);
12677   sqlite3_free(pFile);
12678   return rc;
12679 }
12680
12681 /*
12682 ** This function is a wrapper around the OS specific implementation of
12683 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
12684 ** ability to simulate a malloc failure, so that the handling of an
12685 ** error in sqlite3_os_init() by the upper layers can be tested.
12686 */
12687 SQLITE_PRIVATE int sqlite3OsInit(void){
12688   void *p = sqlite3_malloc(10);
12689   if( p==0 ) return SQLITE_NOMEM;
12690   sqlite3_free(p);
12691   return sqlite3_os_init();
12692 }
12693
12694 /*
12695 ** The list of all registered VFS implementations.
12696 */
12697 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
12698 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
12699
12700 /*
12701 ** Locate a VFS by name.  If no name is given, simply return the
12702 ** first VFS on the list.
12703 */
12704 SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
12705   sqlite3_vfs *pVfs = 0;
12706 #if SQLITE_THREADSAFE
12707   sqlite3_mutex *mutex;
12708 #endif
12709 #ifndef SQLITE_OMIT_AUTOINIT
12710   int rc = sqlite3_initialize();
12711   if( rc ) return 0;
12712 #endif
12713 #if SQLITE_THREADSAFE
12714   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12715 #endif
12716   sqlite3_mutex_enter(mutex);
12717   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
12718     if( zVfs==0 ) break;
12719     if( strcmp(zVfs, pVfs->zName)==0 ) break;
12720   }
12721   sqlite3_mutex_leave(mutex);
12722   return pVfs;
12723 }
12724
12725 /*
12726 ** Unlink a VFS from the linked list
12727 */
12728 static void vfsUnlink(sqlite3_vfs *pVfs){
12729   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
12730   if( pVfs==0 ){
12731     /* No-op */
12732   }else if( vfsList==pVfs ){
12733     vfsList = pVfs->pNext;
12734   }else if( vfsList ){
12735     sqlite3_vfs *p = vfsList;
12736     while( p->pNext && p->pNext!=pVfs ){
12737       p = p->pNext;
12738     }
12739     if( p->pNext==pVfs ){
12740       p->pNext = pVfs->pNext;
12741     }
12742   }
12743 }
12744
12745 /*
12746 ** Register a VFS with the system.  It is harmless to register the same
12747 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
12748 ** true.
12749 */
12750 SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
12751   sqlite3_mutex *mutex = 0;
12752 #ifndef SQLITE_OMIT_AUTOINIT
12753   int rc = sqlite3_initialize();
12754   if( rc ) return rc;
12755 #endif
12756   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12757   sqlite3_mutex_enter(mutex);
12758   vfsUnlink(pVfs);
12759   if( makeDflt || vfsList==0 ){
12760     pVfs->pNext = vfsList;
12761     vfsList = pVfs;
12762   }else{
12763     pVfs->pNext = vfsList->pNext;
12764     vfsList->pNext = pVfs;
12765   }
12766   assert(vfsList);
12767   sqlite3_mutex_leave(mutex);
12768   return SQLITE_OK;
12769 }
12770
12771 /*
12772 ** Unregister a VFS so that it is no longer accessible.
12773 */
12774 SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
12775 #if SQLITE_THREADSAFE
12776   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
12777 #endif
12778   sqlite3_mutex_enter(mutex);
12779   vfsUnlink(pVfs);
12780   sqlite3_mutex_leave(mutex);
12781   return SQLITE_OK;
12782 }
12783
12784 /************** End of os.c **************************************************/
12785 /************** Begin file fault.c *******************************************/
12786 /*
12787 ** 2008 Jan 22
12788 **
12789 ** The author disclaims copyright to this source code.  In place of
12790 ** a legal notice, here is a blessing:
12791 **
12792 **    May you do good and not evil.
12793 **    May you find forgiveness for yourself and forgive others.
12794 **    May you share freely, never taking more than you give.
12795 **
12796 *************************************************************************
12797 **
12798 ** This file contains code to support the concept of "benign" 
12799 ** malloc failures (when the xMalloc() or xRealloc() method of the
12800 ** sqlite3_mem_methods structure fails to allocate a block of memory
12801 ** and returns 0). 
12802 **
12803 ** Most malloc failures are non-benign. After they occur, SQLite
12804 ** abandons the current operation and returns an error code (usually
12805 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
12806 ** fatal. For example, if a malloc fails while resizing a hash table, this 
12807 ** is completely recoverable simply by not carrying out the resize. The 
12808 ** hash table will continue to function normally.  So a malloc failure 
12809 ** during a hash table resize is a benign fault.
12810 */
12811
12812
12813 #ifndef SQLITE_OMIT_BUILTIN_TEST
12814
12815 /*
12816 ** Global variables.
12817 */
12818 typedef struct BenignMallocHooks BenignMallocHooks;
12819 static SQLITE_WSD struct BenignMallocHooks {
12820   void (*xBenignBegin)(void);
12821   void (*xBenignEnd)(void);
12822 } sqlite3Hooks = { 0, 0 };
12823
12824 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
12825 ** structure.  If writable static data is unsupported on the target,
12826 ** we have to locate the state vector at run-time.  In the more common
12827 ** case where writable static data is supported, wsdHooks can refer directly
12828 ** to the "sqlite3Hooks" state vector declared above.
12829 */
12830 #ifdef SQLITE_OMIT_WSD
12831 # define wsdHooksInit \
12832   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
12833 # define wsdHooks x[0]
12834 #else
12835 # define wsdHooksInit
12836 # define wsdHooks sqlite3Hooks
12837 #endif
12838
12839
12840 /*
12841 ** Register hooks to call when sqlite3BeginBenignMalloc() and
12842 ** sqlite3EndBenignMalloc() are called, respectively.
12843 */
12844 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
12845   void (*xBenignBegin)(void),
12846   void (*xBenignEnd)(void)
12847 ){
12848   wsdHooksInit;
12849   wsdHooks.xBenignBegin = xBenignBegin;
12850   wsdHooks.xBenignEnd = xBenignEnd;
12851 }
12852
12853 /*
12854 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
12855 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
12856 ** indicates that subsequent malloc failures are non-benign.
12857 */
12858 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
12859   wsdHooksInit;
12860   if( wsdHooks.xBenignBegin ){
12861     wsdHooks.xBenignBegin();
12862   }
12863 }
12864 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
12865   wsdHooksInit;
12866   if( wsdHooks.xBenignEnd ){
12867     wsdHooks.xBenignEnd();
12868   }
12869 }
12870
12871 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
12872
12873 /************** End of fault.c ***********************************************/
12874 /************** Begin file mem0.c ********************************************/
12875 /*
12876 ** 2008 October 28
12877 **
12878 ** The author disclaims copyright to this source code.  In place of
12879 ** a legal notice, here is a blessing:
12880 **
12881 **    May you do good and not evil.
12882 **    May you find forgiveness for yourself and forgive others.
12883 **    May you share freely, never taking more than you give.
12884 **
12885 *************************************************************************
12886 **
12887 ** This file contains a no-op memory allocation drivers for use when
12888 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
12889 ** here always fail.  SQLite will not operate with these drivers.  These
12890 ** are merely placeholders.  Real drivers must be substituted using
12891 ** sqlite3_config() before SQLite will operate.
12892 */
12893
12894 /*
12895 ** This version of the memory allocator is the default.  It is
12896 ** used when no other memory allocator is specified using compile-time
12897 ** macros.
12898 */
12899 #ifdef SQLITE_ZERO_MALLOC
12900
12901 /*
12902 ** No-op versions of all memory allocation routines
12903 */
12904 static void *sqlite3MemMalloc(int nByte){ return 0; }
12905 static void sqlite3MemFree(void *pPrior){ return; }
12906 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
12907 static int sqlite3MemSize(void *pPrior){ return 0; }
12908 static int sqlite3MemRoundup(int n){ return n; }
12909 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
12910 static void sqlite3MemShutdown(void *NotUsed){ return; }
12911
12912 /*
12913 ** This routine is the only routine in this file with external linkage.
12914 **
12915 ** Populate the low-level memory allocation function pointers in
12916 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
12917 */
12918 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
12919   static const sqlite3_mem_methods defaultMethods = {
12920      sqlite3MemMalloc,
12921      sqlite3MemFree,
12922      sqlite3MemRealloc,
12923      sqlite3MemSize,
12924      sqlite3MemRoundup,
12925      sqlite3MemInit,
12926      sqlite3MemShutdown,
12927      0
12928   };
12929   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
12930 }
12931
12932 #endif /* SQLITE_ZERO_MALLOC */
12933
12934 /************** End of mem0.c ************************************************/
12935 /************** Begin file mem1.c ********************************************/
12936 /*
12937 ** 2007 August 14
12938 **
12939 ** The author disclaims copyright to this source code.  In place of
12940 ** a legal notice, here is a blessing:
12941 **
12942 **    May you do good and not evil.
12943 **    May you find forgiveness for yourself and forgive others.
12944 **    May you share freely, never taking more than you give.
12945 **
12946 *************************************************************************
12947 **
12948 ** This file contains low-level memory allocation drivers for when
12949 ** SQLite will use the standard C-library malloc/realloc/free interface
12950 ** to obtain the memory it needs.
12951 **
12952 ** This file contains implementations of the low-level memory allocation
12953 ** routines specified in the sqlite3_mem_methods object.
12954 */
12955
12956 /*
12957 ** This version of the memory allocator is the default.  It is
12958 ** used when no other memory allocator is specified using compile-time
12959 ** macros.
12960 */
12961 #ifdef SQLITE_SYSTEM_MALLOC
12962
12963 /*
12964 ** Like malloc(), but remember the size of the allocation
12965 ** so that we can find it later using sqlite3MemSize().
12966 **
12967 ** For this low-level routine, we are guaranteed that nByte>0 because
12968 ** cases of nByte<=0 will be intercepted and dealt with by higher level
12969 ** routines.
12970 */
12971 static void *sqlite3MemMalloc(int nByte){
12972   sqlite3_int64 *p;
12973   assert( nByte>0 );
12974   nByte = ROUND8(nByte);
12975   p = malloc( nByte+8 );
12976   if( p ){
12977     p[0] = nByte;
12978     p++;
12979   }else{
12980     testcase( sqlite3GlobalConfig.xLog!=0 );
12981     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
12982   }
12983   return (void *)p;
12984 }
12985
12986 /*
12987 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
12988 ** or sqlite3MemRealloc().
12989 **
12990 ** For this low-level routine, we already know that pPrior!=0 since
12991 ** cases where pPrior==0 will have been intecepted and dealt with
12992 ** by higher-level routines.
12993 */
12994 static void sqlite3MemFree(void *pPrior){
12995   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
12996   assert( pPrior!=0 );
12997   p--;
12998   free(p);
12999 }
13000
13001 /*
13002 ** Report the allocated size of a prior return from xMalloc()
13003 ** or xRealloc().
13004 */
13005 static int sqlite3MemSize(void *pPrior){
13006   sqlite3_int64 *p;
13007   if( pPrior==0 ) return 0;
13008   p = (sqlite3_int64*)pPrior;
13009   p--;
13010   return (int)p[0];
13011 }
13012
13013 /*
13014 ** Like realloc().  Resize an allocation previously obtained from
13015 ** sqlite3MemMalloc().
13016 **
13017 ** For this low-level interface, we know that pPrior!=0.  Cases where
13018 ** pPrior==0 while have been intercepted by higher-level routine and
13019 ** redirected to xMalloc.  Similarly, we know that nByte>0 becauses
13020 ** cases where nByte<=0 will have been intercepted by higher-level
13021 ** routines and redirected to xFree.
13022 */
13023 static void *sqlite3MemRealloc(void *pPrior, int nByte){
13024   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
13025   assert( pPrior!=0 && nByte>0 );
13026   nByte = ROUND8(nByte);
13027   p--;
13028   p = realloc(p, nByte+8 );
13029   if( p ){
13030     p[0] = nByte;
13031     p++;
13032   }else{
13033     testcase( sqlite3GlobalConfig.xLog!=0 );
13034     sqlite3_log(SQLITE_NOMEM,
13035       "failed memory resize %u to %u bytes",
13036       sqlite3MemSize(pPrior), nByte);
13037   }
13038   return (void*)p;
13039 }
13040
13041 /*
13042 ** Round up a request size to the next valid allocation size.
13043 */
13044 static int sqlite3MemRoundup(int n){
13045   return ROUND8(n);
13046 }
13047
13048 /*
13049 ** Initialize this module.
13050 */
13051 static int sqlite3MemInit(void *NotUsed){
13052   UNUSED_PARAMETER(NotUsed);
13053   return SQLITE_OK;
13054 }
13055
13056 /*
13057 ** Deinitialize this module.
13058 */
13059 static void sqlite3MemShutdown(void *NotUsed){
13060   UNUSED_PARAMETER(NotUsed);
13061   return;
13062 }
13063
13064 /*
13065 ** This routine is the only routine in this file with external linkage.
13066 **
13067 ** Populate the low-level memory allocation function pointers in
13068 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
13069 */
13070 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13071   static const sqlite3_mem_methods defaultMethods = {
13072      sqlite3MemMalloc,
13073      sqlite3MemFree,
13074      sqlite3MemRealloc,
13075      sqlite3MemSize,
13076      sqlite3MemRoundup,
13077      sqlite3MemInit,
13078      sqlite3MemShutdown,
13079      0
13080   };
13081   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13082 }
13083
13084 #endif /* SQLITE_SYSTEM_MALLOC */
13085
13086 /************** End of mem1.c ************************************************/
13087 /************** Begin file mem2.c ********************************************/
13088 /*
13089 ** 2007 August 15
13090 **
13091 ** The author disclaims copyright to this source code.  In place of
13092 ** a legal notice, here is a blessing:
13093 **
13094 **    May you do good and not evil.
13095 **    May you find forgiveness for yourself and forgive others.
13096 **    May you share freely, never taking more than you give.
13097 **
13098 *************************************************************************
13099 **
13100 ** This file contains low-level memory allocation drivers for when
13101 ** SQLite will use the standard C-library malloc/realloc/free interface
13102 ** to obtain the memory it needs while adding lots of additional debugging
13103 ** information to each allocation in order to help detect and fix memory
13104 ** leaks and memory usage errors.
13105 **
13106 ** This file contains implementations of the low-level memory allocation
13107 ** routines specified in the sqlite3_mem_methods object.
13108 */
13109
13110 /*
13111 ** This version of the memory allocator is used only if the
13112 ** SQLITE_MEMDEBUG macro is defined
13113 */
13114 #ifdef SQLITE_MEMDEBUG
13115
13116 /*
13117 ** The backtrace functionality is only available with GLIBC
13118 */
13119 #ifdef __GLIBC__
13120   extern int backtrace(void**,int);
13121   extern void backtrace_symbols_fd(void*const*,int,int);
13122 #else
13123 # define backtrace(A,B) 1
13124 # define backtrace_symbols_fd(A,B,C)
13125 #endif
13126
13127 /*
13128 ** Each memory allocation looks like this:
13129 **
13130 **  ------------------------------------------------------------------------
13131 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
13132 **  ------------------------------------------------------------------------
13133 **
13134 ** The application code sees only a pointer to the allocation.  We have
13135 ** to back up from the allocation pointer to find the MemBlockHdr.  The
13136 ** MemBlockHdr tells us the size of the allocation and the number of
13137 ** backtrace pointers.  There is also a guard word at the end of the
13138 ** MemBlockHdr.
13139 */
13140 struct MemBlockHdr {
13141   i64 iSize;                          /* Size of this allocation */
13142   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
13143   char nBacktrace;                    /* Number of backtraces on this alloc */
13144   char nBacktraceSlots;               /* Available backtrace slots */
13145   short nTitle;                       /* Bytes of title; includes '\0' */
13146   int iForeGuard;                     /* Guard word for sanity */
13147 };
13148
13149 /*
13150 ** Guard words
13151 */
13152 #define FOREGUARD 0x80F5E153
13153 #define REARGUARD 0xE4676B53
13154
13155 /*
13156 ** Number of malloc size increments to track.
13157 */
13158 #define NCSIZE  1000
13159
13160 /*
13161 ** All of the static variables used by this module are collected
13162 ** into a single structure named "mem".  This is to keep the
13163 ** static variables organized and to reduce namespace pollution
13164 ** when this module is combined with other in the amalgamation.
13165 */
13166 static struct {
13167   
13168   /*
13169   ** Mutex to control access to the memory allocation subsystem.
13170   */
13171   sqlite3_mutex *mutex;
13172
13173   /*
13174   ** Head and tail of a linked list of all outstanding allocations
13175   */
13176   struct MemBlockHdr *pFirst;
13177   struct MemBlockHdr *pLast;
13178   
13179   /*
13180   ** The number of levels of backtrace to save in new allocations.
13181   */
13182   int nBacktrace;
13183   void (*xBacktrace)(int, int, void **);
13184
13185   /*
13186   ** Title text to insert in front of each block
13187   */
13188   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
13189   char zTitle[100];  /* The title text */
13190
13191   /* 
13192   ** sqlite3MallocDisallow() increments the following counter.
13193   ** sqlite3MallocAllow() decrements it.
13194   */
13195   int disallow; /* Do not allow memory allocation */
13196
13197   /*
13198   ** Gather statistics on the sizes of memory allocations.
13199   ** nAlloc[i] is the number of allocation attempts of i*8
13200   ** bytes.  i==NCSIZE is the number of allocation attempts for
13201   ** sizes more than NCSIZE*8 bytes.
13202   */
13203   int nAlloc[NCSIZE];      /* Total number of allocations */
13204   int nCurrent[NCSIZE];    /* Current number of allocations */
13205   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
13206
13207 } mem;
13208
13209
13210 /*
13211 ** Adjust memory usage statistics
13212 */
13213 static void adjustStats(int iSize, int increment){
13214   int i = ROUND8(iSize)/8;
13215   if( i>NCSIZE-1 ){
13216     i = NCSIZE - 1;
13217   }
13218   if( increment>0 ){
13219     mem.nAlloc[i]++;
13220     mem.nCurrent[i]++;
13221     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
13222       mem.mxCurrent[i] = mem.nCurrent[i];
13223     }
13224   }else{
13225     mem.nCurrent[i]--;
13226     assert( mem.nCurrent[i]>=0 );
13227   }
13228 }
13229
13230 /*
13231 ** Given an allocation, find the MemBlockHdr for that allocation.
13232 **
13233 ** This routine checks the guards at either end of the allocation and
13234 ** if they are incorrect it asserts.
13235 */
13236 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
13237   struct MemBlockHdr *p;
13238   int *pInt;
13239   u8 *pU8;
13240   int nReserve;
13241
13242   p = (struct MemBlockHdr*)pAllocation;
13243   p--;
13244   assert( p->iForeGuard==(int)FOREGUARD );
13245   nReserve = ROUND8(p->iSize);
13246   pInt = (int*)pAllocation;
13247   pU8 = (u8*)pAllocation;
13248   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
13249   /* This checks any of the "extra" bytes allocated due
13250   ** to rounding up to an 8 byte boundary to ensure 
13251   ** they haven't been overwritten.
13252   */
13253   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
13254   return p;
13255 }
13256
13257 /*
13258 ** Return the number of bytes currently allocated at address p.
13259 */
13260 static int sqlite3MemSize(void *p){
13261   struct MemBlockHdr *pHdr;
13262   if( !p ){
13263     return 0;
13264   }
13265   pHdr = sqlite3MemsysGetHeader(p);
13266   return pHdr->iSize;
13267 }
13268
13269 /*
13270 ** Initialize the memory allocation subsystem.
13271 */
13272 static int sqlite3MemInit(void *NotUsed){
13273   UNUSED_PARAMETER(NotUsed);
13274   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
13275   if( !sqlite3GlobalConfig.bMemstat ){
13276     /* If memory status is enabled, then the malloc.c wrapper will already
13277     ** hold the STATIC_MEM mutex when the routines here are invoked. */
13278     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
13279   }
13280   return SQLITE_OK;
13281 }
13282
13283 /*
13284 ** Deinitialize the memory allocation subsystem.
13285 */
13286 static void sqlite3MemShutdown(void *NotUsed){
13287   UNUSED_PARAMETER(NotUsed);
13288   mem.mutex = 0;
13289 }
13290
13291 /*
13292 ** Round up a request size to the next valid allocation size.
13293 */
13294 static int sqlite3MemRoundup(int n){
13295   return ROUND8(n);
13296 }
13297
13298 /*
13299 ** Fill a buffer with pseudo-random bytes.  This is used to preset
13300 ** the content of a new memory allocation to unpredictable values and
13301 ** to clear the content of a freed allocation to unpredictable values.
13302 */
13303 static void randomFill(char *pBuf, int nByte){
13304   unsigned int x, y, r;
13305   x = SQLITE_PTR_TO_INT(pBuf);
13306   y = nByte | 1;
13307   while( nByte >= 4 ){
13308     x = (x>>1) ^ (-(x&1) & 0xd0000001);
13309     y = y*1103515245 + 12345;
13310     r = x ^ y;
13311     *(int*)pBuf = r;
13312     pBuf += 4;
13313     nByte -= 4;
13314   }
13315   while( nByte-- > 0 ){
13316     x = (x>>1) ^ (-(x&1) & 0xd0000001);
13317     y = y*1103515245 + 12345;
13318     r = x ^ y;
13319     *(pBuf++) = r & 0xff;
13320   }
13321 }
13322
13323 /*
13324 ** Allocate nByte bytes of memory.
13325 */
13326 static void *sqlite3MemMalloc(int nByte){
13327   struct MemBlockHdr *pHdr;
13328   void **pBt;
13329   char *z;
13330   int *pInt;
13331   void *p = 0;
13332   int totalSize;
13333   int nReserve;
13334   sqlite3_mutex_enter(mem.mutex);
13335   assert( mem.disallow==0 );
13336   nReserve = ROUND8(nByte);
13337   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
13338                mem.nBacktrace*sizeof(void*) + mem.nTitle;
13339   p = malloc(totalSize);
13340   if( p ){
13341     z = p;
13342     pBt = (void**)&z[mem.nTitle];
13343     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
13344     pHdr->pNext = 0;
13345     pHdr->pPrev = mem.pLast;
13346     if( mem.pLast ){
13347       mem.pLast->pNext = pHdr;
13348     }else{
13349       mem.pFirst = pHdr;
13350     }
13351     mem.pLast = pHdr;
13352     pHdr->iForeGuard = FOREGUARD;
13353     pHdr->nBacktraceSlots = mem.nBacktrace;
13354     pHdr->nTitle = mem.nTitle;
13355     if( mem.nBacktrace ){
13356       void *aAddr[40];
13357       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
13358       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
13359       assert(pBt[0]);
13360       if( mem.xBacktrace ){
13361         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
13362       }
13363     }else{
13364       pHdr->nBacktrace = 0;
13365     }
13366     if( mem.nTitle ){
13367       memcpy(z, mem.zTitle, mem.nTitle);
13368     }
13369     pHdr->iSize = nByte;
13370     adjustStats(nByte, +1);
13371     pInt = (int*)&pHdr[1];
13372     pInt[nReserve/sizeof(int)] = REARGUARD;
13373     randomFill((char*)pInt, nByte);
13374     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
13375     p = (void*)pInt;
13376   }
13377   sqlite3_mutex_leave(mem.mutex);
13378   return p; 
13379 }
13380
13381 /*
13382 ** Free memory.
13383 */
13384 static void sqlite3MemFree(void *pPrior){
13385   struct MemBlockHdr *pHdr;
13386   void **pBt;
13387   char *z;
13388   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
13389        || mem.mutex!=0 );
13390   pHdr = sqlite3MemsysGetHeader(pPrior);
13391   pBt = (void**)pHdr;
13392   pBt -= pHdr->nBacktraceSlots;
13393   sqlite3_mutex_enter(mem.mutex);
13394   if( pHdr->pPrev ){
13395     assert( pHdr->pPrev->pNext==pHdr );
13396     pHdr->pPrev->pNext = pHdr->pNext;
13397   }else{
13398     assert( mem.pFirst==pHdr );
13399     mem.pFirst = pHdr->pNext;
13400   }
13401   if( pHdr->pNext ){
13402     assert( pHdr->pNext->pPrev==pHdr );
13403     pHdr->pNext->pPrev = pHdr->pPrev;
13404   }else{
13405     assert( mem.pLast==pHdr );
13406     mem.pLast = pHdr->pPrev;
13407   }
13408   z = (char*)pBt;
13409   z -= pHdr->nTitle;
13410   adjustStats(pHdr->iSize, -1);
13411   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
13412                 pHdr->iSize + sizeof(int) + pHdr->nTitle);
13413   free(z);
13414   sqlite3_mutex_leave(mem.mutex);  
13415 }
13416
13417 /*
13418 ** Change the size of an existing memory allocation.
13419 **
13420 ** For this debugging implementation, we *always* make a copy of the
13421 ** allocation into a new place in memory.  In this way, if the 
13422 ** higher level code is using pointer to the old allocation, it is 
13423 ** much more likely to break and we are much more liking to find
13424 ** the error.
13425 */
13426 static void *sqlite3MemRealloc(void *pPrior, int nByte){
13427   struct MemBlockHdr *pOldHdr;
13428   void *pNew;
13429   assert( mem.disallow==0 );
13430   pOldHdr = sqlite3MemsysGetHeader(pPrior);
13431   pNew = sqlite3MemMalloc(nByte);
13432   if( pNew ){
13433     memcpy(pNew, pPrior, nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize);
13434     if( nByte>pOldHdr->iSize ){
13435       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - pOldHdr->iSize);
13436     }
13437     sqlite3MemFree(pPrior);
13438   }
13439   return pNew;
13440 }
13441
13442 /*
13443 ** Populate the low-level memory allocation function pointers in
13444 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
13445 */
13446 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
13447   static const sqlite3_mem_methods defaultMethods = {
13448      sqlite3MemMalloc,
13449      sqlite3MemFree,
13450      sqlite3MemRealloc,
13451      sqlite3MemSize,
13452      sqlite3MemRoundup,
13453      sqlite3MemInit,
13454      sqlite3MemShutdown,
13455      0
13456   };
13457   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
13458 }
13459
13460 /*
13461 ** Set the number of backtrace levels kept for each allocation.
13462 ** A value of zero turns off backtracing.  The number is always rounded
13463 ** up to a multiple of 2.
13464 */
13465 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
13466   if( depth<0 ){ depth = 0; }
13467   if( depth>20 ){ depth = 20; }
13468   depth = (depth+1)&0xfe;
13469   mem.nBacktrace = depth;
13470 }
13471
13472 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
13473   mem.xBacktrace = xBacktrace;
13474 }
13475
13476 /*
13477 ** Set the title string for subsequent allocations.
13478 */
13479 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
13480   unsigned int n = sqlite3Strlen30(zTitle) + 1;
13481   sqlite3_mutex_enter(mem.mutex);
13482   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
13483   memcpy(mem.zTitle, zTitle, n);
13484   mem.zTitle[n] = 0;
13485   mem.nTitle = ROUND8(n);
13486   sqlite3_mutex_leave(mem.mutex);
13487 }
13488
13489 SQLITE_PRIVATE void sqlite3MemdebugSync(){
13490   struct MemBlockHdr *pHdr;
13491   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13492     void **pBt = (void**)pHdr;
13493     pBt -= pHdr->nBacktraceSlots;
13494     mem.xBacktrace(pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
13495   }
13496 }
13497
13498 /*
13499 ** Open the file indicated and write a log of all unfreed memory 
13500 ** allocations into that log.
13501 */
13502 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
13503   FILE *out;
13504   struct MemBlockHdr *pHdr;
13505   void **pBt;
13506   int i;
13507   out = fopen(zFilename, "w");
13508   if( out==0 ){
13509     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
13510                     zFilename);
13511     return;
13512   }
13513   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
13514     char *z = (char*)pHdr;
13515     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
13516     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
13517             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
13518     if( pHdr->nBacktrace ){
13519       fflush(out);
13520       pBt = (void**)pHdr;
13521       pBt -= pHdr->nBacktraceSlots;
13522       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
13523       fprintf(out, "\n");
13524     }
13525   }
13526   fprintf(out, "COUNTS:\n");
13527   for(i=0; i<NCSIZE-1; i++){
13528     if( mem.nAlloc[i] ){
13529       fprintf(out, "   %5d: %10d %10d %10d\n", 
13530             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
13531     }
13532   }
13533   if( mem.nAlloc[NCSIZE-1] ){
13534     fprintf(out, "   %5d: %10d %10d %10d\n",
13535              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
13536              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
13537   }
13538   fclose(out);
13539 }
13540
13541 /*
13542 ** Return the number of times sqlite3MemMalloc() has been called.
13543 */
13544 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
13545   int i;
13546   int nTotal = 0;
13547   for(i=0; i<NCSIZE; i++){
13548     nTotal += mem.nAlloc[i];
13549   }
13550   return nTotal;
13551 }
13552
13553
13554 #endif /* SQLITE_MEMDEBUG */
13555
13556 /************** End of mem2.c ************************************************/
13557 /************** Begin file mem3.c ********************************************/
13558 /*
13559 ** 2007 October 14
13560 **
13561 ** The author disclaims copyright to this source code.  In place of
13562 ** a legal notice, here is a blessing:
13563 **
13564 **    May you do good and not evil.
13565 **    May you find forgiveness for yourself and forgive others.
13566 **    May you share freely, never taking more than you give.
13567 **
13568 *************************************************************************
13569 ** This file contains the C functions that implement a memory
13570 ** allocation subsystem for use by SQLite. 
13571 **
13572 ** This version of the memory allocation subsystem omits all
13573 ** use of malloc(). The SQLite user supplies a block of memory
13574 ** before calling sqlite3_initialize() from which allocations
13575 ** are made and returned by the xMalloc() and xRealloc() 
13576 ** implementations. Once sqlite3_initialize() has been called,
13577 ** the amount of memory available to SQLite is fixed and cannot
13578 ** be changed.
13579 **
13580 ** This version of the memory allocation subsystem is included
13581 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
13582 */
13583
13584 /*
13585 ** This version of the memory allocator is only built into the library
13586 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
13587 ** mean that the library will use a memory-pool by default, just that
13588 ** it is available. The mempool allocator is activated by calling
13589 ** sqlite3_config().
13590 */
13591 #ifdef SQLITE_ENABLE_MEMSYS3
13592
13593 /*
13594 ** Maximum size (in Mem3Blocks) of a "small" chunk.
13595 */
13596 #define MX_SMALL 10
13597
13598
13599 /*
13600 ** Number of freelist hash slots
13601 */
13602 #define N_HASH  61
13603
13604 /*
13605 ** A memory allocation (also called a "chunk") consists of two or 
13606 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
13607 ** a header that is not returned to the user.
13608 **
13609 ** A chunk is two or more blocks that is either checked out or
13610 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
13611 ** size of the allocation in blocks if the allocation is free.
13612 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
13613 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
13614 ** is true if the previous chunk is checked out and false if the
13615 ** previous chunk is free.  The u.hdr.prevSize field is the size of
13616 ** the previous chunk in blocks if the previous chunk is on the
13617 ** freelist. If the previous chunk is checked out, then
13618 ** u.hdr.prevSize can be part of the data for that chunk and should
13619 ** not be read or written.
13620 **
13621 ** We often identify a chunk by its index in mem3.aPool[].  When
13622 ** this is done, the chunk index refers to the second block of
13623 ** the chunk.  In this way, the first chunk has an index of 1.
13624 ** A chunk index of 0 means "no such chunk" and is the equivalent
13625 ** of a NULL pointer.
13626 **
13627 ** The second block of free chunks is of the form u.list.  The
13628 ** two fields form a double-linked list of chunks of related sizes.
13629 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
13630 ** for smaller chunks and mem3.aiHash[] for larger chunks.
13631 **
13632 ** The second block of a chunk is user data if the chunk is checked 
13633 ** out.  If a chunk is checked out, the user data may extend into
13634 ** the u.hdr.prevSize value of the following chunk.
13635 */
13636 typedef struct Mem3Block Mem3Block;
13637 struct Mem3Block {
13638   union {
13639     struct {
13640       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
13641       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
13642     } hdr;
13643     struct {
13644       u32 next;       /* Index in mem3.aPool[] of next free chunk */
13645       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
13646     } list;
13647   } u;
13648 };
13649
13650 /*
13651 ** All of the static variables used by this module are collected
13652 ** into a single structure named "mem3".  This is to keep the
13653 ** static variables organized and to reduce namespace pollution
13654 ** when this module is combined with other in the amalgamation.
13655 */
13656 static SQLITE_WSD struct Mem3Global {
13657   /*
13658   ** Memory available for allocation. nPool is the size of the array
13659   ** (in Mem3Blocks) pointed to by aPool less 2.
13660   */
13661   u32 nPool;
13662   Mem3Block *aPool;
13663
13664   /*
13665   ** True if we are evaluating an out-of-memory callback.
13666   */
13667   int alarmBusy;
13668   
13669   /*
13670   ** Mutex to control access to the memory allocation subsystem.
13671   */
13672   sqlite3_mutex *mutex;
13673   
13674   /*
13675   ** The minimum amount of free space that we have seen.
13676   */
13677   u32 mnMaster;
13678
13679   /*
13680   ** iMaster is the index of the master chunk.  Most new allocations
13681   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
13682   ** of the current master.  iMaster is 0 if there is not master chunk.
13683   ** The master chunk is not in either the aiHash[] or aiSmall[].
13684   */
13685   u32 iMaster;
13686   u32 szMaster;
13687
13688   /*
13689   ** Array of lists of free blocks according to the block size 
13690   ** for smaller chunks, or a hash on the block size for larger
13691   ** chunks.
13692   */
13693   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
13694   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
13695 } mem3 = { 97535575 };
13696
13697 #define mem3 GLOBAL(struct Mem3Global, mem3)
13698
13699 /*
13700 ** Unlink the chunk at mem3.aPool[i] from list it is currently
13701 ** on.  *pRoot is the list that i is a member of.
13702 */
13703 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
13704   u32 next = mem3.aPool[i].u.list.next;
13705   u32 prev = mem3.aPool[i].u.list.prev;
13706   assert( sqlite3_mutex_held(mem3.mutex) );
13707   if( prev==0 ){
13708     *pRoot = next;
13709   }else{
13710     mem3.aPool[prev].u.list.next = next;
13711   }
13712   if( next ){
13713     mem3.aPool[next].u.list.prev = prev;
13714   }
13715   mem3.aPool[i].u.list.next = 0;
13716   mem3.aPool[i].u.list.prev = 0;
13717 }
13718
13719 /*
13720 ** Unlink the chunk at index i from 
13721 ** whatever list is currently a member of.
13722 */
13723 static void memsys3Unlink(u32 i){
13724   u32 size, hash;
13725   assert( sqlite3_mutex_held(mem3.mutex) );
13726   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
13727   assert( i>=1 );
13728   size = mem3.aPool[i-1].u.hdr.size4x/4;
13729   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
13730   assert( size>=2 );
13731   if( size <= MX_SMALL ){
13732     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
13733   }else{
13734     hash = size % N_HASH;
13735     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
13736   }
13737 }
13738
13739 /*
13740 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
13741 ** at *pRoot.
13742 */
13743 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
13744   assert( sqlite3_mutex_held(mem3.mutex) );
13745   mem3.aPool[i].u.list.next = *pRoot;
13746   mem3.aPool[i].u.list.prev = 0;
13747   if( *pRoot ){
13748     mem3.aPool[*pRoot].u.list.prev = i;
13749   }
13750   *pRoot = i;
13751 }
13752
13753 /*
13754 ** Link the chunk at index i into either the appropriate
13755 ** small chunk list, or into the large chunk hash table.
13756 */
13757 static void memsys3Link(u32 i){
13758   u32 size, hash;
13759   assert( sqlite3_mutex_held(mem3.mutex) );
13760   assert( i>=1 );
13761   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
13762   size = mem3.aPool[i-1].u.hdr.size4x/4;
13763   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
13764   assert( size>=2 );
13765   if( size <= MX_SMALL ){
13766     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
13767   }else{
13768     hash = size % N_HASH;
13769     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
13770   }
13771 }
13772
13773 /*
13774 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
13775 ** will already be held (obtained by code in malloc.c) if
13776 ** sqlite3GlobalConfig.bMemStat is true.
13777 */
13778 static void memsys3Enter(void){
13779   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
13780     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
13781   }
13782   sqlite3_mutex_enter(mem3.mutex);
13783 }
13784 static void memsys3Leave(void){
13785   sqlite3_mutex_leave(mem3.mutex);
13786 }
13787
13788 /*
13789 ** Called when we are unable to satisfy an allocation of nBytes.
13790 */
13791 static void memsys3OutOfMemory(int nByte){
13792   if( !mem3.alarmBusy ){
13793     mem3.alarmBusy = 1;
13794     assert( sqlite3_mutex_held(mem3.mutex) );
13795     sqlite3_mutex_leave(mem3.mutex);
13796     sqlite3_release_memory(nByte);
13797     sqlite3_mutex_enter(mem3.mutex);
13798     mem3.alarmBusy = 0;
13799   }
13800 }
13801
13802
13803 /*
13804 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
13805 ** size parameters for check-out and return a pointer to the 
13806 ** user portion of the chunk.
13807 */
13808 static void *memsys3Checkout(u32 i, u32 nBlock){
13809   u32 x;
13810   assert( sqlite3_mutex_held(mem3.mutex) );
13811   assert( i>=1 );
13812   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
13813   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
13814   x = mem3.aPool[i-1].u.hdr.size4x;
13815   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
13816   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
13817   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
13818   return &mem3.aPool[i];
13819 }
13820
13821 /*
13822 ** Carve a piece off of the end of the mem3.iMaster free chunk.
13823 ** Return a pointer to the new allocation.  Or, if the master chunk
13824 ** is not large enough, return 0.
13825 */
13826 static void *memsys3FromMaster(u32 nBlock){
13827   assert( sqlite3_mutex_held(mem3.mutex) );
13828   assert( mem3.szMaster>=nBlock );
13829   if( nBlock>=mem3.szMaster-1 ){
13830     /* Use the entire master */
13831     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
13832     mem3.iMaster = 0;
13833     mem3.szMaster = 0;
13834     mem3.mnMaster = 0;
13835     return p;
13836   }else{
13837     /* Split the master block.  Return the tail. */
13838     u32 newi, x;
13839     newi = mem3.iMaster + mem3.szMaster - nBlock;
13840     assert( newi > mem3.iMaster+1 );
13841     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
13842     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
13843     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
13844     mem3.szMaster -= nBlock;
13845     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
13846     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
13847     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
13848     if( mem3.szMaster < mem3.mnMaster ){
13849       mem3.mnMaster = mem3.szMaster;
13850     }
13851     return (void*)&mem3.aPool[newi];
13852   }
13853 }
13854
13855 /*
13856 ** *pRoot is the head of a list of free chunks of the same size
13857 ** or same size hash.  In other words, *pRoot is an entry in either
13858 ** mem3.aiSmall[] or mem3.aiHash[].  
13859 **
13860 ** This routine examines all entries on the given list and tries
13861 ** to coalesce each entries with adjacent free chunks.  
13862 **
13863 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
13864 ** the current mem3.iMaster with the new larger chunk.  In order for
13865 ** this mem3.iMaster replacement to work, the master chunk must be
13866 ** linked into the hash tables.  That is not the normal state of
13867 ** affairs, of course.  The calling routine must link the master
13868 ** chunk before invoking this routine, then must unlink the (possibly
13869 ** changed) master chunk once this routine has finished.
13870 */
13871 static void memsys3Merge(u32 *pRoot){
13872   u32 iNext, prev, size, i, x;
13873
13874   assert( sqlite3_mutex_held(mem3.mutex) );
13875   for(i=*pRoot; i>0; i=iNext){
13876     iNext = mem3.aPool[i].u.list.next;
13877     size = mem3.aPool[i-1].u.hdr.size4x;
13878     assert( (size&1)==0 );
13879     if( (size&2)==0 ){
13880       memsys3UnlinkFromList(i, pRoot);
13881       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
13882       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
13883       if( prev==iNext ){
13884         iNext = mem3.aPool[prev].u.list.next;
13885       }
13886       memsys3Unlink(prev);
13887       size = i + size/4 - prev;
13888       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
13889       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
13890       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
13891       memsys3Link(prev);
13892       i = prev;
13893     }else{
13894       size /= 4;
13895     }
13896     if( size>mem3.szMaster ){
13897       mem3.iMaster = i;
13898       mem3.szMaster = size;
13899     }
13900   }
13901 }
13902
13903 /*
13904 ** Return a block of memory of at least nBytes in size.
13905 ** Return NULL if unable.
13906 **
13907 ** This function assumes that the necessary mutexes, if any, are
13908 ** already held by the caller. Hence "Unsafe".
13909 */
13910 static void *memsys3MallocUnsafe(int nByte){
13911   u32 i;
13912   u32 nBlock;
13913   u32 toFree;
13914
13915   assert( sqlite3_mutex_held(mem3.mutex) );
13916   assert( sizeof(Mem3Block)==8 );
13917   if( nByte<=12 ){
13918     nBlock = 2;
13919   }else{
13920     nBlock = (nByte + 11)/8;
13921   }
13922   assert( nBlock>=2 );
13923
13924   /* STEP 1:
13925   ** Look for an entry of the correct size in either the small
13926   ** chunk table or in the large chunk hash table.  This is
13927   ** successful most of the time (about 9 times out of 10).
13928   */
13929   if( nBlock <= MX_SMALL ){
13930     i = mem3.aiSmall[nBlock-2];
13931     if( i>0 ){
13932       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
13933       return memsys3Checkout(i, nBlock);
13934     }
13935   }else{
13936     int hash = nBlock % N_HASH;
13937     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
13938       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
13939         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
13940         return memsys3Checkout(i, nBlock);
13941       }
13942     }
13943   }
13944
13945   /* STEP 2:
13946   ** Try to satisfy the allocation by carving a piece off of the end
13947   ** of the master chunk.  This step usually works if step 1 fails.
13948   */
13949   if( mem3.szMaster>=nBlock ){
13950     return memsys3FromMaster(nBlock);
13951   }
13952
13953
13954   /* STEP 3:  
13955   ** Loop through the entire memory pool.  Coalesce adjacent free
13956   ** chunks.  Recompute the master chunk as the largest free chunk.
13957   ** Then try again to satisfy the allocation by carving a piece off
13958   ** of the end of the master chunk.  This step happens very
13959   ** rarely (we hope!)
13960   */
13961   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
13962     memsys3OutOfMemory(toFree);
13963     if( mem3.iMaster ){
13964       memsys3Link(mem3.iMaster);
13965       mem3.iMaster = 0;
13966       mem3.szMaster = 0;
13967     }
13968     for(i=0; i<N_HASH; i++){
13969       memsys3Merge(&mem3.aiHash[i]);
13970     }
13971     for(i=0; i<MX_SMALL-1; i++){
13972       memsys3Merge(&mem3.aiSmall[i]);
13973     }
13974     if( mem3.szMaster ){
13975       memsys3Unlink(mem3.iMaster);
13976       if( mem3.szMaster>=nBlock ){
13977         return memsys3FromMaster(nBlock);
13978       }
13979     }
13980   }
13981
13982   /* If none of the above worked, then we fail. */
13983   return 0;
13984 }
13985
13986 /*
13987 ** Free an outstanding memory allocation.
13988 **
13989 ** This function assumes that the necessary mutexes, if any, are
13990 ** already held by the caller. Hence "Unsafe".
13991 */
13992 void memsys3FreeUnsafe(void *pOld){
13993   Mem3Block *p = (Mem3Block*)pOld;
13994   int i;
13995   u32 size, x;
13996   assert( sqlite3_mutex_held(mem3.mutex) );
13997   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
13998   i = p - mem3.aPool;
13999   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
14000   size = mem3.aPool[i-1].u.hdr.size4x/4;
14001   assert( i+size<=mem3.nPool+1 );
14002   mem3.aPool[i-1].u.hdr.size4x &= ~1;
14003   mem3.aPool[i+size-1].u.hdr.prevSize = size;
14004   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
14005   memsys3Link(i);
14006
14007   /* Try to expand the master using the newly freed chunk */
14008   if( mem3.iMaster ){
14009     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
14010       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
14011       mem3.iMaster -= size;
14012       mem3.szMaster += size;
14013       memsys3Unlink(mem3.iMaster);
14014       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
14015       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
14016       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
14017     }
14018     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
14019     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
14020       memsys3Unlink(mem3.iMaster+mem3.szMaster);
14021       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
14022       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
14023       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
14024     }
14025   }
14026 }
14027
14028 /*
14029 ** Return the size of an outstanding allocation, in bytes.  The
14030 ** size returned omits the 8-byte header overhead.  This only
14031 ** works for chunks that are currently checked out.
14032 */
14033 static int memsys3Size(void *p){
14034   Mem3Block *pBlock;
14035   if( p==0 ) return 0;
14036   pBlock = (Mem3Block*)p;
14037   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
14038   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
14039 }
14040
14041 /*
14042 ** Round up a request size to the next valid allocation size.
14043 */
14044 static int memsys3Roundup(int n){
14045   if( n<=12 ){
14046     return 12;
14047   }else{
14048     return ((n+11)&~7) - 4;
14049   }
14050 }
14051
14052 /*
14053 ** Allocate nBytes of memory.
14054 */
14055 static void *memsys3Malloc(int nBytes){
14056   sqlite3_int64 *p;
14057   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
14058   memsys3Enter();
14059   p = memsys3MallocUnsafe(nBytes);
14060   memsys3Leave();
14061   return (void*)p; 
14062 }
14063
14064 /*
14065 ** Free memory.
14066 */
14067 void memsys3Free(void *pPrior){
14068   assert( pPrior );
14069   memsys3Enter();
14070   memsys3FreeUnsafe(pPrior);
14071   memsys3Leave();
14072 }
14073
14074 /*
14075 ** Change the size of an existing memory allocation
14076 */
14077 void *memsys3Realloc(void *pPrior, int nBytes){
14078   int nOld;
14079   void *p;
14080   if( pPrior==0 ){
14081     return sqlite3_malloc(nBytes);
14082   }
14083   if( nBytes<=0 ){
14084     sqlite3_free(pPrior);
14085     return 0;
14086   }
14087   nOld = memsys3Size(pPrior);
14088   if( nBytes<=nOld && nBytes>=nOld-128 ){
14089     return pPrior;
14090   }
14091   memsys3Enter();
14092   p = memsys3MallocUnsafe(nBytes);
14093   if( p ){
14094     if( nOld<nBytes ){
14095       memcpy(p, pPrior, nOld);
14096     }else{
14097       memcpy(p, pPrior, nBytes);
14098     }
14099     memsys3FreeUnsafe(pPrior);
14100   }
14101   memsys3Leave();
14102   return p;
14103 }
14104
14105 /*
14106 ** Initialize this module.
14107 */
14108 static int memsys3Init(void *NotUsed){
14109   UNUSED_PARAMETER(NotUsed);
14110   if( !sqlite3GlobalConfig.pHeap ){
14111     return SQLITE_ERROR;
14112   }
14113
14114   /* Store a pointer to the memory block in global structure mem3. */
14115   assert( sizeof(Mem3Block)==8 );
14116   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
14117   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
14118
14119   /* Initialize the master block. */
14120   mem3.szMaster = mem3.nPool;
14121   mem3.mnMaster = mem3.szMaster;
14122   mem3.iMaster = 1;
14123   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
14124   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
14125   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
14126
14127   return SQLITE_OK;
14128 }
14129
14130 /*
14131 ** Deinitialize this module.
14132 */
14133 static void memsys3Shutdown(void *NotUsed){
14134   UNUSED_PARAMETER(NotUsed);
14135   mem3.mutex = 0;
14136   return;
14137 }
14138
14139
14140
14141 /*
14142 ** Open the file indicated and write a log of all unfreed memory 
14143 ** allocations into that log.
14144 */
14145 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
14146 #ifdef SQLITE_DEBUG
14147   FILE *out;
14148   u32 i, j;
14149   u32 size;
14150   if( zFilename==0 || zFilename[0]==0 ){
14151     out = stdout;
14152   }else{
14153     out = fopen(zFilename, "w");
14154     if( out==0 ){
14155       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
14156                       zFilename);
14157       return;
14158     }
14159   }
14160   memsys3Enter();
14161   fprintf(out, "CHUNKS:\n");
14162   for(i=1; i<=mem3.nPool; i+=size/4){
14163     size = mem3.aPool[i-1].u.hdr.size4x;
14164     if( size/4<=1 ){
14165       fprintf(out, "%p size error\n", &mem3.aPool[i]);
14166       assert( 0 );
14167       break;
14168     }
14169     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
14170       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
14171       assert( 0 );
14172       break;
14173     }
14174     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
14175       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
14176       assert( 0 );
14177       break;
14178     }
14179     if( size&1 ){
14180       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
14181     }else{
14182       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
14183                   i==mem3.iMaster ? " **master**" : "");
14184     }
14185   }
14186   for(i=0; i<MX_SMALL-1; i++){
14187     if( mem3.aiSmall[i]==0 ) continue;
14188     fprintf(out, "small(%2d):", i);
14189     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
14190       fprintf(out, " %p(%d)", &mem3.aPool[j],
14191               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
14192     }
14193     fprintf(out, "\n"); 
14194   }
14195   for(i=0; i<N_HASH; i++){
14196     if( mem3.aiHash[i]==0 ) continue;
14197     fprintf(out, "hash(%2d):", i);
14198     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
14199       fprintf(out, " %p(%d)", &mem3.aPool[j],
14200               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
14201     }
14202     fprintf(out, "\n"); 
14203   }
14204   fprintf(out, "master=%d\n", mem3.iMaster);
14205   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
14206   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
14207   sqlite3_mutex_leave(mem3.mutex);
14208   if( out==stdout ){
14209     fflush(stdout);
14210   }else{
14211     fclose(out);
14212   }
14213 #else
14214   UNUSED_PARAMETER(zFilename);
14215 #endif
14216 }
14217
14218 /*
14219 ** This routine is the only routine in this file with external 
14220 ** linkage.
14221 **
14222 ** Populate the low-level memory allocation function pointers in
14223 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
14224 ** arguments specify the block of memory to manage.
14225 **
14226 ** This routine is only called by sqlite3_config(), and therefore
14227 ** is not required to be threadsafe (it is not).
14228 */
14229 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
14230   static const sqlite3_mem_methods mempoolMethods = {
14231      memsys3Malloc,
14232      memsys3Free,
14233      memsys3Realloc,
14234      memsys3Size,
14235      memsys3Roundup,
14236      memsys3Init,
14237      memsys3Shutdown,
14238      0
14239   };
14240   return &mempoolMethods;
14241 }
14242
14243 #endif /* SQLITE_ENABLE_MEMSYS3 */
14244
14245 /************** End of mem3.c ************************************************/
14246 /************** Begin file mem5.c ********************************************/
14247 /*
14248 ** 2007 October 14
14249 **
14250 ** The author disclaims copyright to this source code.  In place of
14251 ** a legal notice, here is a blessing:
14252 **
14253 **    May you do good and not evil.
14254 **    May you find forgiveness for yourself and forgive others.
14255 **    May you share freely, never taking more than you give.
14256 **
14257 *************************************************************************
14258 ** This file contains the C functions that implement a memory
14259 ** allocation subsystem for use by SQLite. 
14260 **
14261 ** This version of the memory allocation subsystem omits all
14262 ** use of malloc(). The application gives SQLite a block of memory
14263 ** before calling sqlite3_initialize() from which allocations
14264 ** are made and returned by the xMalloc() and xRealloc() 
14265 ** implementations. Once sqlite3_initialize() has been called,
14266 ** the amount of memory available to SQLite is fixed and cannot
14267 ** be changed.
14268 **
14269 ** This version of the memory allocation subsystem is included
14270 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
14271 **
14272 ** This memory allocator uses the following algorithm:
14273 **
14274 **   1.  All memory allocations sizes are rounded up to a power of 2.
14275 **
14276 **   2.  If two adjacent free blocks are the halves of a larger block,
14277 **       then the two blocks are coalesed into the single larger block.
14278 **
14279 **   3.  New memory is allocated from the first available free block.
14280 **
14281 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
14282 ** Concerning Dynamic Storage Allocation". Journal of the Association for
14283 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
14284 ** 
14285 ** Let n be the size of the largest allocation divided by the minimum
14286 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
14287 ** be the maximum amount of memory ever outstanding at one time.  Let
14288 ** N be the total amount of memory available for allocation.  Robson
14289 ** proved that this memory allocator will never breakdown due to 
14290 ** fragmentation as long as the following constraint holds:
14291 **
14292 **      N >=  M*(1 + log2(n)/2) - n + 1
14293 **
14294 ** The sqlite3_status() logic tracks the maximum values of n and M so
14295 ** that an application can, at any time, verify this constraint.
14296 */
14297
14298 /*
14299 ** This version of the memory allocator is used only when 
14300 ** SQLITE_ENABLE_MEMSYS5 is defined.
14301 */
14302 #ifdef SQLITE_ENABLE_MEMSYS5
14303
14304 /*
14305 ** A minimum allocation is an instance of the following structure.
14306 ** Larger allocations are an array of these structures where the
14307 ** size of the array is a power of 2.
14308 **
14309 ** The size of this object must be a power of two.  That fact is
14310 ** verified in memsys5Init().
14311 */
14312 typedef struct Mem5Link Mem5Link;
14313 struct Mem5Link {
14314   int next;       /* Index of next free chunk */
14315   int prev;       /* Index of previous free chunk */
14316 };
14317
14318 /*
14319 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
14320 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
14321 ** it is not actually possible to reach this limit.
14322 */
14323 #define LOGMAX 30
14324
14325 /*
14326 ** Masks used for mem5.aCtrl[] elements.
14327 */
14328 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
14329 #define CTRL_FREE     0x20    /* True if not checked out */
14330
14331 /*
14332 ** All of the static variables used by this module are collected
14333 ** into a single structure named "mem5".  This is to keep the
14334 ** static variables organized and to reduce namespace pollution
14335 ** when this module is combined with other in the amalgamation.
14336 */
14337 static SQLITE_WSD struct Mem5Global {
14338   /*
14339   ** Memory available for allocation
14340   */
14341   int szAtom;      /* Smallest possible allocation in bytes */
14342   int nBlock;      /* Number of szAtom sized blocks in zPool */
14343   u8 *zPool;       /* Memory available to be allocated */
14344   
14345   /*
14346   ** Mutex to control access to the memory allocation subsystem.
14347   */
14348   sqlite3_mutex *mutex;
14349
14350   /*
14351   ** Performance statistics
14352   */
14353   u64 nAlloc;         /* Total number of calls to malloc */
14354   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
14355   u64 totalExcess;    /* Total internal fragmentation */
14356   u32 currentOut;     /* Current checkout, including internal fragmentation */
14357   u32 currentCount;   /* Current number of distinct checkouts */
14358   u32 maxOut;         /* Maximum instantaneous currentOut */
14359   u32 maxCount;       /* Maximum instantaneous currentCount */
14360   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
14361   
14362   /*
14363   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
14364   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
14365   ** and so forth.
14366   */
14367   int aiFreelist[LOGMAX+1];
14368
14369   /*
14370   ** Space for tracking which blocks are checked out and the size
14371   ** of each block.  One byte per block.
14372   */
14373   u8 *aCtrl;
14374
14375 } mem5 = { 0 };
14376
14377 /*
14378 ** Access the static variable through a macro for SQLITE_OMIT_WSD
14379 */
14380 #define mem5 GLOBAL(struct Mem5Global, mem5)
14381
14382 /*
14383 ** Assuming mem5.zPool is divided up into an array of Mem5Link
14384 ** structures, return a pointer to the idx-th such lik.
14385 */
14386 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
14387
14388 /*
14389 ** Unlink the chunk at mem5.aPool[i] from list it is currently
14390 ** on.  It should be found on mem5.aiFreelist[iLogsize].
14391 */
14392 static void memsys5Unlink(int i, int iLogsize){
14393   int next, prev;
14394   assert( i>=0 && i<mem5.nBlock );
14395   assert( iLogsize>=0 && iLogsize<=LOGMAX );
14396   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
14397
14398   next = MEM5LINK(i)->next;
14399   prev = MEM5LINK(i)->prev;
14400   if( prev<0 ){
14401     mem5.aiFreelist[iLogsize] = next;
14402   }else{
14403     MEM5LINK(prev)->next = next;
14404   }
14405   if( next>=0 ){
14406     MEM5LINK(next)->prev = prev;
14407   }
14408 }
14409
14410 /*
14411 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
14412 ** free list.
14413 */
14414 static void memsys5Link(int i, int iLogsize){
14415   int x;
14416   assert( sqlite3_mutex_held(mem5.mutex) );
14417   assert( i>=0 && i<mem5.nBlock );
14418   assert( iLogsize>=0 && iLogsize<=LOGMAX );
14419   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
14420
14421   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
14422   MEM5LINK(i)->prev = -1;
14423   if( x>=0 ){
14424     assert( x<mem5.nBlock );
14425     MEM5LINK(x)->prev = i;
14426   }
14427   mem5.aiFreelist[iLogsize] = i;
14428 }
14429
14430 /*
14431 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
14432 ** will already be held (obtained by code in malloc.c) if
14433 ** sqlite3GlobalConfig.bMemStat is true.
14434 */
14435 static void memsys5Enter(void){
14436   sqlite3_mutex_enter(mem5.mutex);
14437 }
14438 static void memsys5Leave(void){
14439   sqlite3_mutex_leave(mem5.mutex);
14440 }
14441
14442 /*
14443 ** Return the size of an outstanding allocation, in bytes.  The
14444 ** size returned omits the 8-byte header overhead.  This only
14445 ** works for chunks that are currently checked out.
14446 */
14447 static int memsys5Size(void *p){
14448   int iSize = 0;
14449   if( p ){
14450     int i = ((u8 *)p-mem5.zPool)/mem5.szAtom;
14451     assert( i>=0 && i<mem5.nBlock );
14452     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
14453   }
14454   return iSize;
14455 }
14456
14457 /*
14458 ** Find the first entry on the freelist iLogsize.  Unlink that
14459 ** entry and return its index. 
14460 */
14461 static int memsys5UnlinkFirst(int iLogsize){
14462   int i;
14463   int iFirst;
14464
14465   assert( iLogsize>=0 && iLogsize<=LOGMAX );
14466   i = iFirst = mem5.aiFreelist[iLogsize];
14467   assert( iFirst>=0 );
14468   while( i>0 ){
14469     if( i<iFirst ) iFirst = i;
14470     i = MEM5LINK(i)->next;
14471   }
14472   memsys5Unlink(iFirst, iLogsize);
14473   return iFirst;
14474 }
14475
14476 /*
14477 ** Return a block of memory of at least nBytes in size.
14478 ** Return NULL if unable.  Return NULL if nBytes==0.
14479 **
14480 ** The caller guarantees that nByte positive.
14481 **
14482 ** The caller has obtained a mutex prior to invoking this
14483 ** routine so there is never any chance that two or more
14484 ** threads can be in this routine at the same time.
14485 */
14486 static void *memsys5MallocUnsafe(int nByte){
14487   int i;           /* Index of a mem5.aPool[] slot */
14488   int iBin;        /* Index into mem5.aiFreelist[] */
14489   int iFullSz;     /* Size of allocation rounded up to power of 2 */
14490   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
14491
14492   /* nByte must be a positive */
14493   assert( nByte>0 );
14494
14495   /* Keep track of the maximum allocation request.  Even unfulfilled
14496   ** requests are counted */
14497   if( (u32)nByte>mem5.maxRequest ){
14498     mem5.maxRequest = nByte;
14499   }
14500
14501   /* Abort if the requested allocation size is larger than the largest
14502   ** power of two that we can represent using 32-bit signed integers.
14503   */
14504   if( nByte > 0x40000000 ){
14505     return 0;
14506   }
14507
14508   /* Round nByte up to the next valid power of two */
14509   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
14510
14511   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
14512   ** block.  If not, then split a block of the next larger power of
14513   ** two in order to create a new free block of size iLogsize.
14514   */
14515   for(iBin=iLogsize; mem5.aiFreelist[iBin]<0 && iBin<=LOGMAX; iBin++){}
14516   if( iBin>LOGMAX ){
14517     testcase( sqlite3GlobalConfig.xLog!=0 );
14518     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
14519     return 0;
14520   }
14521   i = memsys5UnlinkFirst(iBin);
14522   while( iBin>iLogsize ){
14523     int newSize;
14524
14525     iBin--;
14526     newSize = 1 << iBin;
14527     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
14528     memsys5Link(i+newSize, iBin);
14529   }
14530   mem5.aCtrl[i] = iLogsize;
14531
14532   /* Update allocator performance statistics. */
14533   mem5.nAlloc++;
14534   mem5.totalAlloc += iFullSz;
14535   mem5.totalExcess += iFullSz - nByte;
14536   mem5.currentCount++;
14537   mem5.currentOut += iFullSz;
14538   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
14539   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
14540
14541   /* Return a pointer to the allocated memory. */
14542   return (void*)&mem5.zPool[i*mem5.szAtom];
14543 }
14544
14545 /*
14546 ** Free an outstanding memory allocation.
14547 */
14548 static void memsys5FreeUnsafe(void *pOld){
14549   u32 size, iLogsize;
14550   int iBlock;
14551
14552   /* Set iBlock to the index of the block pointed to by pOld in 
14553   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
14554   */
14555   iBlock = ((u8 *)pOld-mem5.zPool)/mem5.szAtom;
14556
14557   /* Check that the pointer pOld points to a valid, non-free block. */
14558   assert( iBlock>=0 && iBlock<mem5.nBlock );
14559   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
14560   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
14561
14562   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
14563   size = 1<<iLogsize;
14564   assert( iBlock+size-1<(u32)mem5.nBlock );
14565
14566   mem5.aCtrl[iBlock] |= CTRL_FREE;
14567   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
14568   assert( mem5.currentCount>0 );
14569   assert( mem5.currentOut>=(size*mem5.szAtom) );
14570   mem5.currentCount--;
14571   mem5.currentOut -= size*mem5.szAtom;
14572   assert( mem5.currentOut>0 || mem5.currentCount==0 );
14573   assert( mem5.currentCount>0 || mem5.currentOut==0 );
14574
14575   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14576   while( ALWAYS(iLogsize<LOGMAX) ){
14577     int iBuddy;
14578     if( (iBlock>>iLogsize) & 1 ){
14579       iBuddy = iBlock - size;
14580     }else{
14581       iBuddy = iBlock + size;
14582     }
14583     assert( iBuddy>=0 );
14584     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
14585     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
14586     memsys5Unlink(iBuddy, iLogsize);
14587     iLogsize++;
14588     if( iBuddy<iBlock ){
14589       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
14590       mem5.aCtrl[iBlock] = 0;
14591       iBlock = iBuddy;
14592     }else{
14593       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
14594       mem5.aCtrl[iBuddy] = 0;
14595     }
14596     size *= 2;
14597   }
14598   memsys5Link(iBlock, iLogsize);
14599 }
14600
14601 /*
14602 ** Allocate nBytes of memory
14603 */
14604 static void *memsys5Malloc(int nBytes){
14605   sqlite3_int64 *p = 0;
14606   if( nBytes>0 ){
14607     memsys5Enter();
14608     p = memsys5MallocUnsafe(nBytes);
14609     memsys5Leave();
14610   }
14611   return (void*)p; 
14612 }
14613
14614 /*
14615 ** Free memory.
14616 **
14617 ** The outer layer memory allocator prevents this routine from
14618 ** being called with pPrior==0.
14619 */
14620 static void memsys5Free(void *pPrior){
14621   assert( pPrior!=0 );
14622   memsys5Enter();
14623   memsys5FreeUnsafe(pPrior);
14624   memsys5Leave();  
14625 }
14626
14627 /*
14628 ** Change the size of an existing memory allocation.
14629 **
14630 ** The outer layer memory allocator prevents this routine from
14631 ** being called with pPrior==0.  
14632 **
14633 ** nBytes is always a value obtained from a prior call to
14634 ** memsys5Round().  Hence nBytes is always a non-negative power
14635 ** of two.  If nBytes==0 that means that an oversize allocation
14636 ** (an allocation larger than 0x40000000) was requested and this
14637 ** routine should return 0 without freeing pPrior.
14638 */
14639 static void *memsys5Realloc(void *pPrior, int nBytes){
14640   int nOld;
14641   void *p;
14642   assert( pPrior!=0 );
14643   assert( (nBytes&(nBytes-1))==0 );
14644   assert( nBytes>=0 );
14645   if( nBytes==0 ){
14646     return 0;
14647   }
14648   nOld = memsys5Size(pPrior);
14649   if( nBytes<=nOld ){
14650     return pPrior;
14651   }
14652   memsys5Enter();
14653   p = memsys5MallocUnsafe(nBytes);
14654   if( p ){
14655     memcpy(p, pPrior, nOld);
14656     memsys5FreeUnsafe(pPrior);
14657   }
14658   memsys5Leave();
14659   return p;
14660 }
14661
14662 /*
14663 ** Round up a request size to the next valid allocation size.  If
14664 ** the allocation is too large to be handled by this allocation system,
14665 ** return 0.
14666 **
14667 ** All allocations must be a power of two and must be expressed by a
14668 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
14669 ** or 1073741824 bytes.
14670 */
14671 static int memsys5Roundup(int n){
14672   int iFullSz;
14673   if( n > 0x40000000 ) return 0;
14674   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
14675   return iFullSz;
14676 }
14677
14678 /*
14679 ** Return the ceiling of the logarithm base 2 of iValue.
14680 **
14681 ** Examples:   memsys5Log(1) -> 0
14682 **             memsys5Log(2) -> 1
14683 **             memsys5Log(4) -> 2
14684 **             memsys5Log(5) -> 3
14685 **             memsys5Log(8) -> 3
14686 **             memsys5Log(9) -> 4
14687 */
14688 static int memsys5Log(int iValue){
14689   int iLog;
14690   for(iLog=0; (1<<iLog)<iValue; iLog++);
14691   return iLog;
14692 }
14693
14694 /*
14695 ** Initialize the memory allocator.
14696 **
14697 ** This routine is not threadsafe.  The caller must be holding a mutex
14698 ** to prevent multiple threads from entering at the same time.
14699 */
14700 static int memsys5Init(void *NotUsed){
14701   int ii;            /* Loop counter */
14702   int nByte;         /* Number of bytes of memory available to this allocator */
14703   u8 *zByte;         /* Memory usable by this allocator */
14704   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
14705   int iOffset;       /* An offset into mem5.aCtrl[] */
14706
14707   UNUSED_PARAMETER(NotUsed);
14708
14709   /* For the purposes of this routine, disable the mutex */
14710   mem5.mutex = 0;
14711
14712   /* The size of a Mem5Link object must be a power of two.  Verify that
14713   ** this is case.
14714   */
14715   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
14716
14717   nByte = sqlite3GlobalConfig.nHeap;
14718   zByte = (u8*)sqlite3GlobalConfig.pHeap;
14719   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
14720
14721   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
14722   mem5.szAtom = (1<<nMinLog);
14723   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
14724     mem5.szAtom = mem5.szAtom << 1;
14725   }
14726
14727   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
14728   mem5.zPool = zByte;
14729   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
14730
14731   for(ii=0; ii<=LOGMAX; ii++){
14732     mem5.aiFreelist[ii] = -1;
14733   }
14734
14735   iOffset = 0;
14736   for(ii=LOGMAX; ii>=0; ii--){
14737     int nAlloc = (1<<ii);
14738     if( (iOffset+nAlloc)<=mem5.nBlock ){
14739       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
14740       memsys5Link(iOffset, ii);
14741       iOffset += nAlloc;
14742     }
14743     assert((iOffset+nAlloc)>mem5.nBlock);
14744   }
14745
14746   /* If a mutex is required for normal operation, allocate one */
14747   if( sqlite3GlobalConfig.bMemstat==0 ){
14748     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
14749   }
14750
14751   return SQLITE_OK;
14752 }
14753
14754 /*
14755 ** Deinitialize this module.
14756 */
14757 static void memsys5Shutdown(void *NotUsed){
14758   UNUSED_PARAMETER(NotUsed);
14759   mem5.mutex = 0;
14760   return;
14761 }
14762
14763 #ifdef SQLITE_TEST
14764 /*
14765 ** Open the file indicated and write a log of all unfreed memory 
14766 ** allocations into that log.
14767 */
14768 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
14769   FILE *out;
14770   int i, j, n;
14771   int nMinLog;
14772
14773   if( zFilename==0 || zFilename[0]==0 ){
14774     out = stdout;
14775   }else{
14776     out = fopen(zFilename, "w");
14777     if( out==0 ){
14778       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
14779                       zFilename);
14780       return;
14781     }
14782   }
14783   memsys5Enter();
14784   nMinLog = memsys5Log(mem5.szAtom);
14785   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
14786     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
14787     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
14788   }
14789   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
14790   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
14791   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
14792   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
14793   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
14794   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
14795   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
14796   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
14797   memsys5Leave();
14798   if( out==stdout ){
14799     fflush(stdout);
14800   }else{
14801     fclose(out);
14802   }
14803 }
14804 #endif
14805
14806 /*
14807 ** This routine is the only routine in this file with external 
14808 ** linkage. It returns a pointer to a static sqlite3_mem_methods
14809 ** struct populated with the memsys5 methods.
14810 */
14811 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
14812   static const sqlite3_mem_methods memsys5Methods = {
14813      memsys5Malloc,
14814      memsys5Free,
14815      memsys5Realloc,
14816      memsys5Size,
14817      memsys5Roundup,
14818      memsys5Init,
14819      memsys5Shutdown,
14820      0
14821   };
14822   return &memsys5Methods;
14823 }
14824
14825 #endif /* SQLITE_ENABLE_MEMSYS5 */
14826
14827 /************** End of mem5.c ************************************************/
14828 /************** Begin file mutex.c *******************************************/
14829 /*
14830 ** 2007 August 14
14831 **
14832 ** The author disclaims copyright to this source code.  In place of
14833 ** a legal notice, here is a blessing:
14834 **
14835 **    May you do good and not evil.
14836 **    May you find forgiveness for yourself and forgive others.
14837 **    May you share freely, never taking more than you give.
14838 **
14839 *************************************************************************
14840 ** This file contains the C functions that implement mutexes.
14841 **
14842 ** This file contains code that is common across all mutex implementations.
14843 */
14844
14845 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
14846 /*
14847 ** For debugging purposes, record when the mutex subsystem is initialized
14848 ** and uninitialized so that we can assert() if there is an attempt to
14849 ** allocate a mutex while the system is uninitialized.
14850 */
14851 static SQLITE_WSD int mutexIsInit = 0;
14852 #endif /* SQLITE_DEBUG */
14853
14854
14855 #ifndef SQLITE_MUTEX_OMIT
14856 /*
14857 ** Initialize the mutex system.
14858 */
14859 SQLITE_PRIVATE int sqlite3MutexInit(void){ 
14860   int rc = SQLITE_OK;
14861   if( sqlite3GlobalConfig.bCoreMutex ){
14862     if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
14863       /* If the xMutexAlloc method has not been set, then the user did not
14864       ** install a mutex implementation via sqlite3_config() prior to 
14865       ** sqlite3_initialize() being called. This block copies pointers to
14866       ** the default implementation into the sqlite3GlobalConfig structure.
14867       */
14868       sqlite3_mutex_methods *pFrom = sqlite3DefaultMutex();
14869       sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
14870
14871       memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
14872       memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
14873              sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
14874       pTo->xMutexAlloc = pFrom->xMutexAlloc;
14875     }
14876     rc = sqlite3GlobalConfig.mutex.xMutexInit();
14877   }
14878
14879 #ifdef SQLITE_DEBUG
14880   GLOBAL(int, mutexIsInit) = 1;
14881 #endif
14882
14883   return rc;
14884 }
14885
14886 /*
14887 ** Shutdown the mutex system. This call frees resources allocated by
14888 ** sqlite3MutexInit().
14889 */
14890 SQLITE_PRIVATE int sqlite3MutexEnd(void){
14891   int rc = SQLITE_OK;
14892   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
14893     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
14894   }
14895
14896 #ifdef SQLITE_DEBUG
14897   GLOBAL(int, mutexIsInit) = 0;
14898 #endif
14899
14900   return rc;
14901 }
14902
14903 /*
14904 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
14905 */
14906 SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
14907 #ifndef SQLITE_OMIT_AUTOINIT
14908   if( sqlite3_initialize() ) return 0;
14909 #endif
14910   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
14911 }
14912
14913 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
14914   if( !sqlite3GlobalConfig.bCoreMutex ){
14915     return 0;
14916   }
14917   assert( GLOBAL(int, mutexIsInit) );
14918   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
14919 }
14920
14921 /*
14922 ** Free a dynamic mutex.
14923 */
14924 SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
14925   if( p ){
14926     sqlite3GlobalConfig.mutex.xMutexFree(p);
14927   }
14928 }
14929
14930 /*
14931 ** Obtain the mutex p. If some other thread already has the mutex, block
14932 ** until it can be obtained.
14933 */
14934 SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
14935   if( p ){
14936     sqlite3GlobalConfig.mutex.xMutexEnter(p);
14937   }
14938 }
14939
14940 /*
14941 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
14942 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
14943 */
14944 SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
14945   int rc = SQLITE_OK;
14946   if( p ){
14947     return sqlite3GlobalConfig.mutex.xMutexTry(p);
14948   }
14949   return rc;
14950 }
14951
14952 /*
14953 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
14954 ** entered by the same thread.  The behavior is undefined if the mutex 
14955 ** is not currently entered. If a NULL pointer is passed as an argument
14956 ** this function is a no-op.
14957 */
14958 SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
14959   if( p ){
14960     sqlite3GlobalConfig.mutex.xMutexLeave(p);
14961   }
14962 }
14963
14964 #ifndef NDEBUG
14965 /*
14966 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
14967 ** intended for use inside assert() statements.
14968 */
14969 SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
14970   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
14971 }
14972 SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
14973   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
14974 }
14975 #endif
14976
14977 #endif /* SQLITE_MUTEX_OMIT */
14978
14979 /************** End of mutex.c ***********************************************/
14980 /************** Begin file mutex_noop.c **************************************/
14981 /*
14982 ** 2008 October 07
14983 **
14984 ** The author disclaims copyright to this source code.  In place of
14985 ** a legal notice, here is a blessing:
14986 **
14987 **    May you do good and not evil.
14988 **    May you find forgiveness for yourself and forgive others.
14989 **    May you share freely, never taking more than you give.
14990 **
14991 *************************************************************************
14992 ** This file contains the C functions that implement mutexes.
14993 **
14994 ** This implementation in this file does not provide any mutual
14995 ** exclusion and is thus suitable for use only in applications
14996 ** that use SQLite in a single thread.  The routines defined
14997 ** here are place-holders.  Applications can substitute working
14998 ** mutex routines at start-time using the
14999 **
15000 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
15001 **
15002 ** interface.
15003 **
15004 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
15005 ** that does error checking on mutexes to make sure they are being
15006 ** called correctly.
15007 */
15008
15009
15010 #if defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG)
15011 /*
15012 ** Stub routines for all mutex methods.
15013 **
15014 ** This routines provide no mutual exclusion or error checking.
15015 */
15016 static int noopMutexHeld(sqlite3_mutex *p){ return 1; }
15017 static int noopMutexNotheld(sqlite3_mutex *p){ return 1; }
15018 static int noopMutexInit(void){ return SQLITE_OK; }
15019 static int noopMutexEnd(void){ return SQLITE_OK; }
15020 static sqlite3_mutex *noopMutexAlloc(int id){ return (sqlite3_mutex*)8; }
15021 static void noopMutexFree(sqlite3_mutex *p){ return; }
15022 static void noopMutexEnter(sqlite3_mutex *p){ return; }
15023 static int noopMutexTry(sqlite3_mutex *p){ return SQLITE_OK; }
15024 static void noopMutexLeave(sqlite3_mutex *p){ return; }
15025
15026 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15027   static sqlite3_mutex_methods sMutex = {
15028     noopMutexInit,
15029     noopMutexEnd,
15030     noopMutexAlloc,
15031     noopMutexFree,
15032     noopMutexEnter,
15033     noopMutexTry,
15034     noopMutexLeave,
15035
15036     noopMutexHeld,
15037     noopMutexNotheld
15038   };
15039
15040   return &sMutex;
15041 }
15042 #endif /* defined(SQLITE_MUTEX_NOOP) && !defined(SQLITE_DEBUG) */
15043
15044 #if defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG)
15045 /*
15046 ** In this implementation, error checking is provided for testing
15047 ** and debugging purposes.  The mutexes still do not provide any
15048 ** mutual exclusion.
15049 */
15050
15051 /*
15052 ** The mutex object
15053 */
15054 struct sqlite3_mutex {
15055   int id;     /* The mutex type */
15056   int cnt;    /* Number of entries without a matching leave */
15057 };
15058
15059 /*
15060 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15061 ** intended for use inside assert() statements.
15062 */
15063 static int debugMutexHeld(sqlite3_mutex *p){
15064   return p==0 || p->cnt>0;
15065 }
15066 static int debugMutexNotheld(sqlite3_mutex *p){
15067   return p==0 || p->cnt==0;
15068 }
15069
15070 /*
15071 ** Initialize and deinitialize the mutex subsystem.
15072 */
15073 static int debugMutexInit(void){ return SQLITE_OK; }
15074 static int debugMutexEnd(void){ return SQLITE_OK; }
15075
15076 /*
15077 ** The sqlite3_mutex_alloc() routine allocates a new
15078 ** mutex and returns a pointer to it.  If it returns NULL
15079 ** that means that a mutex could not be allocated. 
15080 */
15081 static sqlite3_mutex *debugMutexAlloc(int id){
15082   static sqlite3_mutex aStatic[6];
15083   sqlite3_mutex *pNew = 0;
15084   switch( id ){
15085     case SQLITE_MUTEX_FAST:
15086     case SQLITE_MUTEX_RECURSIVE: {
15087       pNew = sqlite3Malloc(sizeof(*pNew));
15088       if( pNew ){
15089         pNew->id = id;
15090         pNew->cnt = 0;
15091       }
15092       break;
15093     }
15094     default: {
15095       assert( id-2 >= 0 );
15096       assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
15097       pNew = &aStatic[id-2];
15098       pNew->id = id;
15099       break;
15100     }
15101   }
15102   return pNew;
15103 }
15104
15105 /*
15106 ** This routine deallocates a previously allocated mutex.
15107 */
15108 static void debugMutexFree(sqlite3_mutex *p){
15109   assert( p->cnt==0 );
15110   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15111   sqlite3_free(p);
15112 }
15113
15114 /*
15115 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15116 ** to enter a mutex.  If another thread is already within the mutex,
15117 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15118 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15119 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15120 ** be entered multiple times by the same thread.  In such cases the,
15121 ** mutex must be exited an equal number of times before another thread
15122 ** can enter.  If the same thread tries to enter any other kind of mutex
15123 ** more than once, the behavior is undefined.
15124 */
15125 static void debugMutexEnter(sqlite3_mutex *p){
15126   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
15127   p->cnt++;
15128 }
15129 static int debugMutexTry(sqlite3_mutex *p){
15130   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
15131   p->cnt++;
15132   return SQLITE_OK;
15133 }
15134
15135 /*
15136 ** The sqlite3_mutex_leave() routine exits a mutex that was
15137 ** previously entered by the same thread.  The behavior
15138 ** is undefined if the mutex is not currently entered or
15139 ** is not currently allocated.  SQLite will never do either.
15140 */
15141 static void debugMutexLeave(sqlite3_mutex *p){
15142   assert( debugMutexHeld(p) );
15143   p->cnt--;
15144   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(p) );
15145 }
15146
15147 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15148   static sqlite3_mutex_methods sMutex = {
15149     debugMutexInit,
15150     debugMutexEnd,
15151     debugMutexAlloc,
15152     debugMutexFree,
15153     debugMutexEnter,
15154     debugMutexTry,
15155     debugMutexLeave,
15156
15157     debugMutexHeld,
15158     debugMutexNotheld
15159   };
15160
15161   return &sMutex;
15162 }
15163 #endif /* defined(SQLITE_MUTEX_NOOP) && defined(SQLITE_DEBUG) */
15164
15165 /************** End of mutex_noop.c ******************************************/
15166 /************** Begin file mutex_os2.c ***************************************/
15167 /*
15168 ** 2007 August 28
15169 **
15170 ** The author disclaims copyright to this source code.  In place of
15171 ** a legal notice, here is a blessing:
15172 **
15173 **    May you do good and not evil.
15174 **    May you find forgiveness for yourself and forgive others.
15175 **    May you share freely, never taking more than you give.
15176 **
15177 *************************************************************************
15178 ** This file contains the C functions that implement mutexes for OS/2
15179 */
15180
15181 /*
15182 ** The code in this file is only used if SQLITE_MUTEX_OS2 is defined.
15183 ** See the mutex.h file for details.
15184 */
15185 #ifdef SQLITE_MUTEX_OS2
15186
15187 /********************** OS/2 Mutex Implementation **********************
15188 **
15189 ** This implementation of mutexes is built using the OS/2 API.
15190 */
15191
15192 /*
15193 ** The mutex object
15194 ** Each recursive mutex is an instance of the following structure.
15195 */
15196 struct sqlite3_mutex {
15197   HMTX mutex;       /* Mutex controlling the lock */
15198   int  id;          /* Mutex type */
15199   int  nRef;        /* Number of references */
15200   TID  owner;       /* Thread holding this mutex */
15201 };
15202
15203 #define OS2_MUTEX_INITIALIZER   0,0,0,0
15204
15205 /*
15206 ** Initialize and deinitialize the mutex subsystem.
15207 */
15208 static int os2MutexInit(void){ return SQLITE_OK; }
15209 static int os2MutexEnd(void){ return SQLITE_OK; }
15210
15211 /*
15212 ** The sqlite3_mutex_alloc() routine allocates a new
15213 ** mutex and returns a pointer to it.  If it returns NULL
15214 ** that means that a mutex could not be allocated. 
15215 ** SQLite will unwind its stack and return an error.  The argument
15216 ** to sqlite3_mutex_alloc() is one of these integer constants:
15217 **
15218 ** <ul>
15219 ** <li>  SQLITE_MUTEX_FAST               0
15220 ** <li>  SQLITE_MUTEX_RECURSIVE          1
15221 ** <li>  SQLITE_MUTEX_STATIC_MASTER      2
15222 ** <li>  SQLITE_MUTEX_STATIC_MEM         3
15223 ** <li>  SQLITE_MUTEX_STATIC_PRNG        4
15224 ** </ul>
15225 **
15226 ** The first two constants cause sqlite3_mutex_alloc() to create
15227 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15228 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15229 ** The mutex implementation does not need to make a distinction
15230 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15231 ** not want to.  But SQLite will only request a recursive mutex in
15232 ** cases where it really needs one.  If a faster non-recursive mutex
15233 ** implementation is available on the host platform, the mutex subsystem
15234 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
15235 **
15236 ** The other allowed parameters to sqlite3_mutex_alloc() each return
15237 ** a pointer to a static preexisting mutex.  Three static mutexes are
15238 ** used by the current version of SQLite.  Future versions of SQLite
15239 ** may add additional static mutexes.  Static mutexes are for internal
15240 ** use by SQLite only.  Applications that use SQLite mutexes should
15241 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15242 ** SQLITE_MUTEX_RECURSIVE.
15243 **
15244 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15245 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15246 ** returns a different mutex on every call.  But for the static
15247 ** mutex types, the same mutex is returned on every call that has
15248 ** the same type number.
15249 */
15250 static sqlite3_mutex *os2MutexAlloc(int iType){
15251   sqlite3_mutex *p = NULL;
15252   switch( iType ){
15253     case SQLITE_MUTEX_FAST:
15254     case SQLITE_MUTEX_RECURSIVE: {
15255       p = sqlite3MallocZero( sizeof(*p) );
15256       if( p ){
15257         p->id = iType;
15258         if( DosCreateMutexSem( 0, &p->mutex, 0, FALSE ) != NO_ERROR ){
15259           sqlite3_free( p );
15260           p = NULL;
15261         }
15262       }
15263       break;
15264     }
15265     default: {
15266       static volatile int isInit = 0;
15267       static sqlite3_mutex staticMutexes[] = {
15268         { OS2_MUTEX_INITIALIZER, },
15269         { OS2_MUTEX_INITIALIZER, },
15270         { OS2_MUTEX_INITIALIZER, },
15271         { OS2_MUTEX_INITIALIZER, },
15272         { OS2_MUTEX_INITIALIZER, },
15273         { OS2_MUTEX_INITIALIZER, },
15274       };
15275       if ( !isInit ){
15276         APIRET rc;
15277         PTIB ptib;
15278         PPIB ppib;
15279         HMTX mutex;
15280         char name[32];
15281         DosGetInfoBlocks( &ptib, &ppib );
15282         sqlite3_snprintf( sizeof(name), name, "\\SEM32\\SQLITE%04x",
15283                           ppib->pib_ulpid );
15284         while( !isInit ){
15285           mutex = 0;
15286           rc = DosCreateMutexSem( name, &mutex, 0, FALSE);
15287           if( rc == NO_ERROR ){
15288             unsigned int i;
15289             if( !isInit ){
15290               for( i = 0; i < sizeof(staticMutexes)/sizeof(staticMutexes[0]); i++ ){
15291                 DosCreateMutexSem( 0, &staticMutexes[i].mutex, 0, FALSE );
15292               }
15293               isInit = 1;
15294             }
15295             DosCloseMutexSem( mutex );
15296           }else if( rc == ERROR_DUPLICATE_NAME ){
15297             DosSleep( 1 );
15298           }else{
15299             return p;
15300           }
15301         }
15302       }
15303       assert( iType-2 >= 0 );
15304       assert( iType-2 < sizeof(staticMutexes)/sizeof(staticMutexes[0]) );
15305       p = &staticMutexes[iType-2];
15306       p->id = iType;
15307       break;
15308     }
15309   }
15310   return p;
15311 }
15312
15313
15314 /*
15315 ** This routine deallocates a previously allocated mutex.
15316 ** SQLite is careful to deallocate every mutex that it allocates.
15317 */
15318 static void os2MutexFree(sqlite3_mutex *p){
15319   if( p==0 ) return;
15320   assert( p->nRef==0 );
15321   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15322   DosCloseMutexSem( p->mutex );
15323   sqlite3_free( p );
15324 }
15325
15326 #ifdef SQLITE_DEBUG
15327 /*
15328 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15329 ** intended for use inside assert() statements.
15330 */
15331 static int os2MutexHeld(sqlite3_mutex *p){
15332   TID tid;
15333   PID pid;
15334   ULONG ulCount;
15335   PTIB ptib;
15336   if( p!=0 ) {
15337     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
15338   } else {
15339     DosGetInfoBlocks(&ptib, NULL);
15340     tid = ptib->tib_ptib2->tib2_ultid;
15341   }
15342   return p==0 || (p->nRef!=0 && p->owner==tid);
15343 }
15344 static int os2MutexNotheld(sqlite3_mutex *p){
15345   TID tid;
15346   PID pid;
15347   ULONG ulCount;
15348   PTIB ptib;
15349   if( p!= 0 ) {
15350     DosQueryMutexSem(p->mutex, &pid, &tid, &ulCount);
15351   } else {
15352     DosGetInfoBlocks(&ptib, NULL);
15353     tid = ptib->tib_ptib2->tib2_ultid;
15354   }
15355   return p==0 || p->nRef==0 || p->owner!=tid;
15356 }
15357 #endif
15358
15359 /*
15360 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15361 ** to enter a mutex.  If another thread is already within the mutex,
15362 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15363 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15364 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15365 ** be entered multiple times by the same thread.  In such cases the,
15366 ** mutex must be exited an equal number of times before another thread
15367 ** can enter.  If the same thread tries to enter any other kind of mutex
15368 ** more than once, the behavior is undefined.
15369 */
15370 static void os2MutexEnter(sqlite3_mutex *p){
15371   TID tid;
15372   PID holder1;
15373   ULONG holder2;
15374   if( p==0 ) return;
15375   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
15376   DosRequestMutexSem(p->mutex, SEM_INDEFINITE_WAIT);
15377   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15378   p->owner = tid;
15379   p->nRef++;
15380 }
15381 static int os2MutexTry(sqlite3_mutex *p){
15382   int rc;
15383   TID tid;
15384   PID holder1;
15385   ULONG holder2;
15386   if( p==0 ) return SQLITE_OK;
15387   assert( p->id==SQLITE_MUTEX_RECURSIVE || os2MutexNotheld(p) );
15388   if( DosRequestMutexSem(p->mutex, SEM_IMMEDIATE_RETURN) == NO_ERROR) {
15389     DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15390     p->owner = tid;
15391     p->nRef++;
15392     rc = SQLITE_OK;
15393   } else {
15394     rc = SQLITE_BUSY;
15395   }
15396
15397   return rc;
15398 }
15399
15400 /*
15401 ** The sqlite3_mutex_leave() routine exits a mutex that was
15402 ** previously entered by the same thread.  The behavior
15403 ** is undefined if the mutex is not currently entered or
15404 ** is not currently allocated.  SQLite will never do either.
15405 */
15406 static void os2MutexLeave(sqlite3_mutex *p){
15407   TID tid;
15408   PID holder1;
15409   ULONG holder2;
15410   if( p==0 ) return;
15411   assert( p->nRef>0 );
15412   DosQueryMutexSem(p->mutex, &holder1, &tid, &holder2);
15413   assert( p->owner==tid );
15414   p->nRef--;
15415   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15416   DosReleaseMutexSem(p->mutex);
15417 }
15418
15419 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15420   static sqlite3_mutex_methods sMutex = {
15421     os2MutexInit,
15422     os2MutexEnd,
15423     os2MutexAlloc,
15424     os2MutexFree,
15425     os2MutexEnter,
15426     os2MutexTry,
15427     os2MutexLeave,
15428 #ifdef SQLITE_DEBUG
15429     os2MutexHeld,
15430     os2MutexNotheld
15431 #endif
15432   };
15433
15434   return &sMutex;
15435 }
15436 #endif /* SQLITE_MUTEX_OS2 */
15437
15438 /************** End of mutex_os2.c *******************************************/
15439 /************** Begin file mutex_unix.c **************************************/
15440 /*
15441 ** 2007 August 28
15442 **
15443 ** The author disclaims copyright to this source code.  In place of
15444 ** a legal notice, here is a blessing:
15445 **
15446 **    May you do good and not evil.
15447 **    May you find forgiveness for yourself and forgive others.
15448 **    May you share freely, never taking more than you give.
15449 **
15450 *************************************************************************
15451 ** This file contains the C functions that implement mutexes for pthreads
15452 */
15453
15454 /*
15455 ** The code in this file is only used if we are compiling threadsafe
15456 ** under unix with pthreads.
15457 **
15458 ** Note that this implementation requires a version of pthreads that
15459 ** supports recursive mutexes.
15460 */
15461 #ifdef SQLITE_MUTEX_PTHREADS
15462
15463 #include <pthread.h>
15464
15465
15466 /*
15467 ** Each recursive mutex is an instance of the following structure.
15468 */
15469 struct sqlite3_mutex {
15470   pthread_mutex_t mutex;     /* Mutex controlling the lock */
15471   int id;                    /* Mutex type */
15472   int nRef;                  /* Number of entrances */
15473   pthread_t owner;           /* Thread that is within this mutex */
15474 #ifdef SQLITE_DEBUG
15475   int trace;                 /* True to trace changes */
15476 #endif
15477 };
15478 #ifdef SQLITE_DEBUG
15479 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
15480 #else
15481 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0 }
15482 #endif
15483
15484 /*
15485 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15486 ** intended for use only inside assert() statements.  On some platforms,
15487 ** there might be race conditions that can cause these routines to
15488 ** deliver incorrect results.  In particular, if pthread_equal() is
15489 ** not an atomic operation, then these routines might delivery
15490 ** incorrect results.  On most platforms, pthread_equal() is a 
15491 ** comparison of two integers and is therefore atomic.  But we are
15492 ** told that HPUX is not such a platform.  If so, then these routines
15493 ** will not always work correctly on HPUX.
15494 **
15495 ** On those platforms where pthread_equal() is not atomic, SQLite
15496 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
15497 ** make sure no assert() statements are evaluated and hence these
15498 ** routines are never called.
15499 */
15500 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
15501 static int pthreadMutexHeld(sqlite3_mutex *p){
15502   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
15503 }
15504 static int pthreadMutexNotheld(sqlite3_mutex *p){
15505   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
15506 }
15507 #endif
15508
15509 /*
15510 ** Initialize and deinitialize the mutex subsystem.
15511 */
15512 static int pthreadMutexInit(void){ return SQLITE_OK; }
15513 static int pthreadMutexEnd(void){ return SQLITE_OK; }
15514
15515 /*
15516 ** The sqlite3_mutex_alloc() routine allocates a new
15517 ** mutex and returns a pointer to it.  If it returns NULL
15518 ** that means that a mutex could not be allocated.  SQLite
15519 ** will unwind its stack and return an error.  The argument
15520 ** to sqlite3_mutex_alloc() is one of these integer constants:
15521 **
15522 ** <ul>
15523 ** <li>  SQLITE_MUTEX_FAST
15524 ** <li>  SQLITE_MUTEX_RECURSIVE
15525 ** <li>  SQLITE_MUTEX_STATIC_MASTER
15526 ** <li>  SQLITE_MUTEX_STATIC_MEM
15527 ** <li>  SQLITE_MUTEX_STATIC_MEM2
15528 ** <li>  SQLITE_MUTEX_STATIC_PRNG
15529 ** <li>  SQLITE_MUTEX_STATIC_LRU
15530 ** <li>  SQLITE_MUTEX_STATIC_LRU2
15531 ** </ul>
15532 **
15533 ** The first two constants cause sqlite3_mutex_alloc() to create
15534 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15535 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15536 ** The mutex implementation does not need to make a distinction
15537 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15538 ** not want to.  But SQLite will only request a recursive mutex in
15539 ** cases where it really needs one.  If a faster non-recursive mutex
15540 ** implementation is available on the host platform, the mutex subsystem
15541 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
15542 **
15543 ** The other allowed parameters to sqlite3_mutex_alloc() each return
15544 ** a pointer to a static preexisting mutex.  Six static mutexes are
15545 ** used by the current version of SQLite.  Future versions of SQLite
15546 ** may add additional static mutexes.  Static mutexes are for internal
15547 ** use by SQLite only.  Applications that use SQLite mutexes should
15548 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15549 ** SQLITE_MUTEX_RECURSIVE.
15550 **
15551 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15552 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15553 ** returns a different mutex on every call.  But for the static 
15554 ** mutex types, the same mutex is returned on every call that has
15555 ** the same type number.
15556 */
15557 static sqlite3_mutex *pthreadMutexAlloc(int iType){
15558   static sqlite3_mutex staticMutexes[] = {
15559     SQLITE3_MUTEX_INITIALIZER,
15560     SQLITE3_MUTEX_INITIALIZER,
15561     SQLITE3_MUTEX_INITIALIZER,
15562     SQLITE3_MUTEX_INITIALIZER,
15563     SQLITE3_MUTEX_INITIALIZER,
15564     SQLITE3_MUTEX_INITIALIZER
15565   };
15566   sqlite3_mutex *p;
15567   switch( iType ){
15568     case SQLITE_MUTEX_RECURSIVE: {
15569       p = sqlite3MallocZero( sizeof(*p) );
15570       if( p ){
15571 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15572         /* If recursive mutexes are not available, we will have to
15573         ** build our own.  See below. */
15574         pthread_mutex_init(&p->mutex, 0);
15575 #else
15576         /* Use a recursive mutex if it is available */
15577         pthread_mutexattr_t recursiveAttr;
15578         pthread_mutexattr_init(&recursiveAttr);
15579         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
15580         pthread_mutex_init(&p->mutex, &recursiveAttr);
15581         pthread_mutexattr_destroy(&recursiveAttr);
15582 #endif
15583         p->id = iType;
15584       }
15585       break;
15586     }
15587     case SQLITE_MUTEX_FAST: {
15588       p = sqlite3MallocZero( sizeof(*p) );
15589       if( p ){
15590         p->id = iType;
15591         pthread_mutex_init(&p->mutex, 0);
15592       }
15593       break;
15594     }
15595     default: {
15596       assert( iType-2 >= 0 );
15597       assert( iType-2 < ArraySize(staticMutexes) );
15598       p = &staticMutexes[iType-2];
15599       p->id = iType;
15600       break;
15601     }
15602   }
15603   return p;
15604 }
15605
15606
15607 /*
15608 ** This routine deallocates a previously
15609 ** allocated mutex.  SQLite is careful to deallocate every
15610 ** mutex that it allocates.
15611 */
15612 static void pthreadMutexFree(sqlite3_mutex *p){
15613   assert( p->nRef==0 );
15614   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15615   pthread_mutex_destroy(&p->mutex);
15616   sqlite3_free(p);
15617 }
15618
15619 /*
15620 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15621 ** to enter a mutex.  If another thread is already within the mutex,
15622 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15623 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15624 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15625 ** be entered multiple times by the same thread.  In such cases the,
15626 ** mutex must be exited an equal number of times before another thread
15627 ** can enter.  If the same thread tries to enter any other kind of mutex
15628 ** more than once, the behavior is undefined.
15629 */
15630 static void pthreadMutexEnter(sqlite3_mutex *p){
15631   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
15632
15633 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15634   /* If recursive mutexes are not available, then we have to grow
15635   ** our own.  This implementation assumes that pthread_equal()
15636   ** is atomic - that it cannot be deceived into thinking self
15637   ** and p->owner are equal if p->owner changes between two values
15638   ** that are not equal to self while the comparison is taking place.
15639   ** This implementation also assumes a coherent cache - that 
15640   ** separate processes cannot read different values from the same
15641   ** address at the same time.  If either of these two conditions
15642   ** are not met, then the mutexes will fail and problems will result.
15643   */
15644   {
15645     pthread_t self = pthread_self();
15646     if( p->nRef>0 && pthread_equal(p->owner, self) ){
15647       p->nRef++;
15648     }else{
15649       pthread_mutex_lock(&p->mutex);
15650       assert( p->nRef==0 );
15651       p->owner = self;
15652       p->nRef = 1;
15653     }
15654   }
15655 #else
15656   /* Use the built-in recursive mutexes if they are available.
15657   */
15658   pthread_mutex_lock(&p->mutex);
15659   p->owner = pthread_self();
15660   p->nRef++;
15661 #endif
15662
15663 #ifdef SQLITE_DEBUG
15664   if( p->trace ){
15665     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15666   }
15667 #endif
15668 }
15669 static int pthreadMutexTry(sqlite3_mutex *p){
15670   int rc;
15671   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
15672
15673 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15674   /* If recursive mutexes are not available, then we have to grow
15675   ** our own.  This implementation assumes that pthread_equal()
15676   ** is atomic - that it cannot be deceived into thinking self
15677   ** and p->owner are equal if p->owner changes between two values
15678   ** that are not equal to self while the comparison is taking place.
15679   ** This implementation also assumes a coherent cache - that 
15680   ** separate processes cannot read different values from the same
15681   ** address at the same time.  If either of these two conditions
15682   ** are not met, then the mutexes will fail and problems will result.
15683   */
15684   {
15685     pthread_t self = pthread_self();
15686     if( p->nRef>0 && pthread_equal(p->owner, self) ){
15687       p->nRef++;
15688       rc = SQLITE_OK;
15689     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
15690       assert( p->nRef==0 );
15691       p->owner = self;
15692       p->nRef = 1;
15693       rc = SQLITE_OK;
15694     }else{
15695       rc = SQLITE_BUSY;
15696     }
15697   }
15698 #else
15699   /* Use the built-in recursive mutexes if they are available.
15700   */
15701   if( pthread_mutex_trylock(&p->mutex)==0 ){
15702     p->owner = pthread_self();
15703     p->nRef++;
15704     rc = SQLITE_OK;
15705   }else{
15706     rc = SQLITE_BUSY;
15707   }
15708 #endif
15709
15710 #ifdef SQLITE_DEBUG
15711   if( rc==SQLITE_OK && p->trace ){
15712     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15713   }
15714 #endif
15715   return rc;
15716 }
15717
15718 /*
15719 ** The sqlite3_mutex_leave() routine exits a mutex that was
15720 ** previously entered by the same thread.  The behavior
15721 ** is undefined if the mutex is not currently entered or
15722 ** is not currently allocated.  SQLite will never do either.
15723 */
15724 static void pthreadMutexLeave(sqlite3_mutex *p){
15725   assert( pthreadMutexHeld(p) );
15726   p->nRef--;
15727   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
15728
15729 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
15730   if( p->nRef==0 ){
15731     pthread_mutex_unlock(&p->mutex);
15732   }
15733 #else
15734   pthread_mutex_unlock(&p->mutex);
15735 #endif
15736
15737 #ifdef SQLITE_DEBUG
15738   if( p->trace ){
15739     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
15740   }
15741 #endif
15742 }
15743
15744 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
15745   static sqlite3_mutex_methods sMutex = {
15746     pthreadMutexInit,
15747     pthreadMutexEnd,
15748     pthreadMutexAlloc,
15749     pthreadMutexFree,
15750     pthreadMutexEnter,
15751     pthreadMutexTry,
15752     pthreadMutexLeave,
15753 #ifdef SQLITE_DEBUG
15754     pthreadMutexHeld,
15755     pthreadMutexNotheld
15756 #else
15757     0,
15758     0
15759 #endif
15760   };
15761
15762   return &sMutex;
15763 }
15764
15765 #endif /* SQLITE_MUTEX_PTHREAD */
15766
15767 /************** End of mutex_unix.c ******************************************/
15768 /************** Begin file mutex_w32.c ***************************************/
15769 /*
15770 ** 2007 August 14
15771 **
15772 ** The author disclaims copyright to this source code.  In place of
15773 ** a legal notice, here is a blessing:
15774 **
15775 **    May you do good and not evil.
15776 **    May you find forgiveness for yourself and forgive others.
15777 **    May you share freely, never taking more than you give.
15778 **
15779 *************************************************************************
15780 ** This file contains the C functions that implement mutexes for win32
15781 */
15782
15783 /*
15784 ** The code in this file is only used if we are compiling multithreaded
15785 ** on a win32 system.
15786 */
15787 #ifdef SQLITE_MUTEX_W32
15788
15789 /*
15790 ** Each recursive mutex is an instance of the following structure.
15791 */
15792 struct sqlite3_mutex {
15793   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
15794   int id;                    /* Mutex type */
15795   int nRef;                  /* Number of enterances */
15796   DWORD owner;               /* Thread holding this mutex */
15797 #ifdef SQLITE_DEBUG
15798   int trace;                 /* True to trace changes */
15799 #endif
15800 };
15801 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
15802 #ifdef SQLITE_DEBUG
15803 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0, 0 }
15804 #else
15805 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, 0L, (DWORD)0 }
15806 #endif
15807
15808 /*
15809 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
15810 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
15811 **
15812 ** Here is an interesting observation:  Win95, Win98, and WinME lack
15813 ** the LockFileEx() API.  But we can still statically link against that
15814 ** API as long as we don't call it win running Win95/98/ME.  A call to
15815 ** this routine is used to determine if the host is Win95/98/ME or
15816 ** WinNT/2K/XP so that we will know whether or not we can safely call
15817 ** the LockFileEx() API.
15818 **
15819 ** mutexIsNT() is only used for the TryEnterCriticalSection() API call,
15820 ** which is only available if your application was compiled with 
15821 ** _WIN32_WINNT defined to a value >= 0x0400.  Currently, the only
15822 ** call to TryEnterCriticalSection() is #ifdef'ed out, so #ifdef 
15823 ** this out as well.
15824 */
15825 #if 0
15826 #if SQLITE_OS_WINCE
15827 # define mutexIsNT()  (1)
15828 #else
15829   static int mutexIsNT(void){
15830     static int osType = 0;
15831     if( osType==0 ){
15832       OSVERSIONINFO sInfo;
15833       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
15834       GetVersionEx(&sInfo);
15835       osType = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
15836     }
15837     return osType==2;
15838   }
15839 #endif /* SQLITE_OS_WINCE */
15840 #endif
15841
15842 #ifdef SQLITE_DEBUG
15843 /*
15844 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
15845 ** intended for use only inside assert() statements.
15846 */
15847 static int winMutexHeld(sqlite3_mutex *p){
15848   return p->nRef!=0 && p->owner==GetCurrentThreadId();
15849 }
15850 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
15851   return p->nRef==0 || p->owner!=tid;
15852 }
15853 static int winMutexNotheld(sqlite3_mutex *p){
15854   DWORD tid = GetCurrentThreadId(); 
15855   return winMutexNotheld2(p, tid);
15856 }
15857 #endif
15858
15859
15860 /*
15861 ** Initialize and deinitialize the mutex subsystem.
15862 */
15863 static sqlite3_mutex winMutex_staticMutexes[6] = {
15864   SQLITE3_MUTEX_INITIALIZER,
15865   SQLITE3_MUTEX_INITIALIZER,
15866   SQLITE3_MUTEX_INITIALIZER,
15867   SQLITE3_MUTEX_INITIALIZER,
15868   SQLITE3_MUTEX_INITIALIZER,
15869   SQLITE3_MUTEX_INITIALIZER
15870 };
15871 static int winMutex_isInit = 0;
15872 /* As winMutexInit() and winMutexEnd() are called as part
15873 ** of the sqlite3_initialize and sqlite3_shutdown()
15874 ** processing, the "interlocked" magic is probably not
15875 ** strictly necessary.
15876 */
15877 static long winMutex_lock = 0;
15878
15879 static int winMutexInit(void){ 
15880   /* The first to increment to 1 does actual initialization */
15881   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
15882     int i;
15883     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
15884       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
15885     }
15886     winMutex_isInit = 1;
15887   }else{
15888     /* Someone else is in the process of initing the static mutexes */
15889     while( !winMutex_isInit ){
15890       Sleep(1);
15891     }
15892   }
15893   return SQLITE_OK; 
15894 }
15895
15896 static int winMutexEnd(void){ 
15897   /* The first to decrement to 0 does actual shutdown 
15898   ** (which should be the last to shutdown.) */
15899   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
15900     if( winMutex_isInit==1 ){
15901       int i;
15902       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
15903         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
15904       }
15905       winMutex_isInit = 0;
15906     }
15907   }
15908   return SQLITE_OK; 
15909 }
15910
15911 /*
15912 ** The sqlite3_mutex_alloc() routine allocates a new
15913 ** mutex and returns a pointer to it.  If it returns NULL
15914 ** that means that a mutex could not be allocated.  SQLite
15915 ** will unwind its stack and return an error.  The argument
15916 ** to sqlite3_mutex_alloc() is one of these integer constants:
15917 **
15918 ** <ul>
15919 ** <li>  SQLITE_MUTEX_FAST
15920 ** <li>  SQLITE_MUTEX_RECURSIVE
15921 ** <li>  SQLITE_MUTEX_STATIC_MASTER
15922 ** <li>  SQLITE_MUTEX_STATIC_MEM
15923 ** <li>  SQLITE_MUTEX_STATIC_MEM2
15924 ** <li>  SQLITE_MUTEX_STATIC_PRNG
15925 ** <li>  SQLITE_MUTEX_STATIC_LRU
15926 ** <li>  SQLITE_MUTEX_STATIC_LRU2
15927 ** </ul>
15928 **
15929 ** The first two constants cause sqlite3_mutex_alloc() to create
15930 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
15931 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
15932 ** The mutex implementation does not need to make a distinction
15933 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
15934 ** not want to.  But SQLite will only request a recursive mutex in
15935 ** cases where it really needs one.  If a faster non-recursive mutex
15936 ** implementation is available on the host platform, the mutex subsystem
15937 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
15938 **
15939 ** The other allowed parameters to sqlite3_mutex_alloc() each return
15940 ** a pointer to a static preexisting mutex.  Six static mutexes are
15941 ** used by the current version of SQLite.  Future versions of SQLite
15942 ** may add additional static mutexes.  Static mutexes are for internal
15943 ** use by SQLite only.  Applications that use SQLite mutexes should
15944 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
15945 ** SQLITE_MUTEX_RECURSIVE.
15946 **
15947 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
15948 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
15949 ** returns a different mutex on every call.  But for the static 
15950 ** mutex types, the same mutex is returned on every call that has
15951 ** the same type number.
15952 */
15953 static sqlite3_mutex *winMutexAlloc(int iType){
15954   sqlite3_mutex *p;
15955
15956   switch( iType ){
15957     case SQLITE_MUTEX_FAST:
15958     case SQLITE_MUTEX_RECURSIVE: {
15959       p = sqlite3MallocZero( sizeof(*p) );
15960       if( p ){  
15961         p->id = iType;
15962         InitializeCriticalSection(&p->mutex);
15963       }
15964       break;
15965     }
15966     default: {
15967       assert( winMutex_isInit==1 );
15968       assert( iType-2 >= 0 );
15969       assert( iType-2 < ArraySize(winMutex_staticMutexes) );
15970       p = &winMutex_staticMutexes[iType-2];
15971       p->id = iType;
15972       break;
15973     }
15974   }
15975   return p;
15976 }
15977
15978
15979 /*
15980 ** This routine deallocates a previously
15981 ** allocated mutex.  SQLite is careful to deallocate every
15982 ** mutex that it allocates.
15983 */
15984 static void winMutexFree(sqlite3_mutex *p){
15985   assert( p );
15986   assert( p->nRef==0 );
15987   assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
15988   DeleteCriticalSection(&p->mutex);
15989   sqlite3_free(p);
15990 }
15991
15992 /*
15993 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
15994 ** to enter a mutex.  If another thread is already within the mutex,
15995 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
15996 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
15997 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
15998 ** be entered multiple times by the same thread.  In such cases the,
15999 ** mutex must be exited an equal number of times before another thread
16000 ** can enter.  If the same thread tries to enter any other kind of mutex
16001 ** more than once, the behavior is undefined.
16002 */
16003 static void winMutexEnter(sqlite3_mutex *p){
16004   DWORD tid = GetCurrentThreadId(); 
16005   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
16006   EnterCriticalSection(&p->mutex);
16007   p->owner = tid; 
16008   p->nRef++;
16009 #ifdef SQLITE_DEBUG
16010   if( p->trace ){
16011     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16012   }
16013 #endif
16014 }
16015 static int winMutexTry(sqlite3_mutex *p){
16016 #ifndef NDEBUG
16017   DWORD tid = GetCurrentThreadId(); 
16018 #endif
16019   int rc = SQLITE_BUSY;
16020   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
16021   /*
16022   ** The sqlite3_mutex_try() routine is very rarely used, and when it
16023   ** is used it is merely an optimization.  So it is OK for it to always
16024   ** fail.  
16025   **
16026   ** The TryEnterCriticalSection() interface is only available on WinNT.
16027   ** And some windows compilers complain if you try to use it without
16028   ** first doing some #defines that prevent SQLite from building on Win98.
16029   ** For that reason, we will omit this optimization for now.  See
16030   ** ticket #2685.
16031   */
16032 #if 0
16033   if( mutexIsNT() && TryEnterCriticalSection(&p->mutex) ){
16034     p->owner = tid;
16035     p->nRef++;
16036     rc = SQLITE_OK;
16037   }
16038 #else
16039   UNUSED_PARAMETER(p);
16040 #endif
16041 #ifdef SQLITE_DEBUG
16042   if( rc==SQLITE_OK && p->trace ){
16043     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16044   }
16045 #endif
16046   return rc;
16047 }
16048
16049 /*
16050 ** The sqlite3_mutex_leave() routine exits a mutex that was
16051 ** previously entered by the same thread.  The behavior
16052 ** is undefined if the mutex is not currently entered or
16053 ** is not currently allocated.  SQLite will never do either.
16054 */
16055 static void winMutexLeave(sqlite3_mutex *p){
16056 #ifndef NDEBUG
16057   DWORD tid = GetCurrentThreadId();
16058 #endif
16059   assert( p->nRef>0 );
16060   assert( p->owner==tid );
16061   p->nRef--;
16062   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
16063   LeaveCriticalSection(&p->mutex);
16064 #ifdef SQLITE_DEBUG
16065   if( p->trace ){
16066     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
16067   }
16068 #endif
16069 }
16070
16071 SQLITE_PRIVATE sqlite3_mutex_methods *sqlite3DefaultMutex(void){
16072   static sqlite3_mutex_methods sMutex = {
16073     winMutexInit,
16074     winMutexEnd,
16075     winMutexAlloc,
16076     winMutexFree,
16077     winMutexEnter,
16078     winMutexTry,
16079     winMutexLeave,
16080 #ifdef SQLITE_DEBUG
16081     winMutexHeld,
16082     winMutexNotheld
16083 #else
16084     0,
16085     0
16086 #endif
16087   };
16088
16089   return &sMutex;
16090 }
16091 #endif /* SQLITE_MUTEX_W32 */
16092
16093 /************** End of mutex_w32.c *******************************************/
16094 /************** Begin file malloc.c ******************************************/
16095 /*
16096 ** 2001 September 15
16097 **
16098 ** The author disclaims copyright to this source code.  In place of
16099 ** a legal notice, here is a blessing:
16100 **
16101 **    May you do good and not evil.
16102 **    May you find forgiveness for yourself and forgive others.
16103 **    May you share freely, never taking more than you give.
16104 **
16105 *************************************************************************
16106 **
16107 ** Memory allocation functions used throughout sqlite.
16108 */
16109
16110 /*
16111 ** This routine runs when the memory allocator sees that the
16112 ** total memory allocation is about to exceed the soft heap
16113 ** limit.
16114 */
16115 static void softHeapLimitEnforcer(
16116   void *NotUsed, 
16117   sqlite3_int64 NotUsed2,
16118   int allocSize
16119 ){
16120   UNUSED_PARAMETER2(NotUsed, NotUsed2);
16121   sqlite3_release_memory(allocSize);
16122 }
16123
16124 /*
16125 ** Set the soft heap-size limit for the library. Passing a zero or 
16126 ** negative value indicates no limit.
16127 */
16128 SQLITE_API void sqlite3_soft_heap_limit(int n){
16129   sqlite3_uint64 iLimit;
16130   int overage;
16131   if( n<0 ){
16132     iLimit = 0;
16133   }else{
16134     iLimit = n;
16135   }
16136 #ifndef SQLITE_OMIT_AUTOINIT
16137   sqlite3_initialize();
16138 #endif
16139   if( iLimit>0 ){
16140     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, iLimit);
16141   }else{
16142     sqlite3MemoryAlarm(0, 0, 0);
16143   }
16144   overage = (int)(sqlite3_memory_used() - (i64)n);
16145   if( overage>0 ){
16146     sqlite3_release_memory(overage);
16147   }
16148 }
16149
16150 /*
16151 ** Attempt to release up to n bytes of non-essential memory currently
16152 ** held by SQLite. An example of non-essential memory is memory used to
16153 ** cache database pages that are not currently in use.
16154 */
16155 SQLITE_API int sqlite3_release_memory(int n){
16156 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
16157   int nRet = 0;
16158   nRet += sqlite3PcacheReleaseMemory(n-nRet);
16159   return nRet;
16160 #else
16161   UNUSED_PARAMETER(n);
16162   return SQLITE_OK;
16163 #endif
16164 }
16165
16166 /*
16167 ** State information local to the memory allocation subsystem.
16168 */
16169 static SQLITE_WSD struct Mem0Global {
16170   /* Number of free pages for scratch and page-cache memory */
16171   u32 nScratchFree;
16172   u32 nPageFree;
16173
16174   sqlite3_mutex *mutex;         /* Mutex to serialize access */
16175
16176   /*
16177   ** The alarm callback and its arguments.  The mem0.mutex lock will
16178   ** be held while the callback is running.  Recursive calls into
16179   ** the memory subsystem are allowed, but no new callbacks will be
16180   ** issued.
16181   */
16182   sqlite3_int64 alarmThreshold;
16183   void (*alarmCallback)(void*, sqlite3_int64,int);
16184   void *alarmArg;
16185
16186   /*
16187   ** Pointers to the end of sqlite3GlobalConfig.pScratch and
16188   ** sqlite3GlobalConfig.pPage to a block of memory that records
16189   ** which pages are available.
16190   */
16191   u32 *aScratchFree;
16192   u32 *aPageFree;
16193 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
16194
16195 #define mem0 GLOBAL(struct Mem0Global, mem0)
16196
16197 /*
16198 ** Initialize the memory allocation subsystem.
16199 */
16200 SQLITE_PRIVATE int sqlite3MallocInit(void){
16201   if( sqlite3GlobalConfig.m.xMalloc==0 ){
16202     sqlite3MemSetDefault();
16203   }
16204   memset(&mem0, 0, sizeof(mem0));
16205   if( sqlite3GlobalConfig.bCoreMutex ){
16206     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
16207   }
16208   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
16209       && sqlite3GlobalConfig.nScratch>=0 ){
16210     int i;
16211     sqlite3GlobalConfig.szScratch = ROUNDDOWN8(sqlite3GlobalConfig.szScratch-4);
16212     mem0.aScratchFree = (u32*)&((char*)sqlite3GlobalConfig.pScratch)
16213                   [sqlite3GlobalConfig.szScratch*sqlite3GlobalConfig.nScratch];
16214     for(i=0; i<sqlite3GlobalConfig.nScratch; i++){ mem0.aScratchFree[i] = i; }
16215     mem0.nScratchFree = sqlite3GlobalConfig.nScratch;
16216   }else{
16217     sqlite3GlobalConfig.pScratch = 0;
16218     sqlite3GlobalConfig.szScratch = 0;
16219   }
16220   if( sqlite3GlobalConfig.pPage && sqlite3GlobalConfig.szPage>=512
16221       && sqlite3GlobalConfig.nPage>=1 ){
16222     int i;
16223     int overhead;
16224     int sz = ROUNDDOWN8(sqlite3GlobalConfig.szPage);
16225     int n = sqlite3GlobalConfig.nPage;
16226     overhead = (4*n + sz - 1)/sz;
16227     sqlite3GlobalConfig.nPage -= overhead;
16228     mem0.aPageFree = (u32*)&((char*)sqlite3GlobalConfig.pPage)
16229                   [sqlite3GlobalConfig.szPage*sqlite3GlobalConfig.nPage];
16230     for(i=0; i<sqlite3GlobalConfig.nPage; i++){ mem0.aPageFree[i] = i; }
16231     mem0.nPageFree = sqlite3GlobalConfig.nPage;
16232   }else{
16233     sqlite3GlobalConfig.pPage = 0;
16234     sqlite3GlobalConfig.szPage = 0;
16235   }
16236   return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
16237 }
16238
16239 /*
16240 ** Deinitialize the memory allocation subsystem.
16241 */
16242 SQLITE_PRIVATE void sqlite3MallocEnd(void){
16243   if( sqlite3GlobalConfig.m.xShutdown ){
16244     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
16245   }
16246   memset(&mem0, 0, sizeof(mem0));
16247 }
16248
16249 /*
16250 ** Return the amount of memory currently checked out.
16251 */
16252 SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
16253   int n, mx;
16254   sqlite3_int64 res;
16255   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
16256   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
16257   return res;
16258 }
16259
16260 /*
16261 ** Return the maximum amount of memory that has ever been
16262 ** checked out since either the beginning of this process
16263 ** or since the most recent reset.
16264 */
16265 SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
16266   int n, mx;
16267   sqlite3_int64 res;
16268   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
16269   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
16270   return res;
16271 }
16272
16273 /*
16274 ** Change the alarm callback
16275 */
16276 SQLITE_PRIVATE int sqlite3MemoryAlarm(
16277   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
16278   void *pArg,
16279   sqlite3_int64 iThreshold
16280 ){
16281   sqlite3_mutex_enter(mem0.mutex);
16282   mem0.alarmCallback = xCallback;
16283   mem0.alarmArg = pArg;
16284   mem0.alarmThreshold = iThreshold;
16285   sqlite3_mutex_leave(mem0.mutex);
16286   return SQLITE_OK;
16287 }
16288
16289 #ifndef SQLITE_OMIT_DEPRECATED
16290 /*
16291 ** Deprecated external interface.  Internal/core SQLite code
16292 ** should call sqlite3MemoryAlarm.
16293 */
16294 SQLITE_API int sqlite3_memory_alarm(
16295   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
16296   void *pArg,
16297   sqlite3_int64 iThreshold
16298 ){
16299   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
16300 }
16301 #endif
16302
16303 /*
16304 ** Trigger the alarm 
16305 */
16306 static void sqlite3MallocAlarm(int nByte){
16307   void (*xCallback)(void*,sqlite3_int64,int);
16308   sqlite3_int64 nowUsed;
16309   void *pArg;
16310   if( mem0.alarmCallback==0 ) return;
16311   xCallback = mem0.alarmCallback;
16312   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
16313   pArg = mem0.alarmArg;
16314   mem0.alarmCallback = 0;
16315   sqlite3_mutex_leave(mem0.mutex);
16316   xCallback(pArg, nowUsed, nByte);
16317   sqlite3_mutex_enter(mem0.mutex);
16318   mem0.alarmCallback = xCallback;
16319   mem0.alarmArg = pArg;
16320 }
16321
16322 /*
16323 ** Do a memory allocation with statistics and alarms.  Assume the
16324 ** lock is already held.
16325 */
16326 static int mallocWithAlarm(int n, void **pp){
16327   int nFull;
16328   void *p;
16329   assert( sqlite3_mutex_held(mem0.mutex) );
16330   nFull = sqlite3GlobalConfig.m.xRoundup(n);
16331   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
16332   if( mem0.alarmCallback!=0 ){
16333     int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
16334     if( nUsed+nFull >= mem0.alarmThreshold ){
16335       sqlite3MallocAlarm(nFull);
16336     }
16337   }
16338   p = sqlite3GlobalConfig.m.xMalloc(nFull);
16339   if( p==0 && mem0.alarmCallback ){
16340     sqlite3MallocAlarm(nFull);
16341     p = sqlite3GlobalConfig.m.xMalloc(nFull);
16342   }
16343   if( p ){
16344     nFull = sqlite3MallocSize(p);
16345     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
16346   }
16347   *pp = p;
16348   return nFull;
16349 }
16350
16351 /*
16352 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
16353 ** assumes the memory subsystem has already been initialized.
16354 */
16355 SQLITE_PRIVATE void *sqlite3Malloc(int n){
16356   void *p;
16357   if( n<=0 || n>=0x7fffff00 ){
16358     /* A memory allocation of a number of bytes which is near the maximum
16359     ** signed integer value might cause an integer overflow inside of the
16360     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
16361     ** 255 bytes of overhead.  SQLite itself will never use anything near
16362     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
16363     p = 0;
16364   }else if( sqlite3GlobalConfig.bMemstat ){
16365     sqlite3_mutex_enter(mem0.mutex);
16366     mallocWithAlarm(n, &p);
16367     sqlite3_mutex_leave(mem0.mutex);
16368   }else{
16369     p = sqlite3GlobalConfig.m.xMalloc(n);
16370   }
16371   return p;
16372 }
16373
16374 /*
16375 ** This version of the memory allocation is for use by the application.
16376 ** First make sure the memory subsystem is initialized, then do the
16377 ** allocation.
16378 */
16379 SQLITE_API void *sqlite3_malloc(int n){
16380 #ifndef SQLITE_OMIT_AUTOINIT
16381   if( sqlite3_initialize() ) return 0;
16382 #endif
16383   return sqlite3Malloc(n);
16384 }
16385
16386 /*
16387 ** Each thread may only have a single outstanding allocation from
16388 ** xScratchMalloc().  We verify this constraint in the single-threaded
16389 ** case by setting scratchAllocOut to 1 when an allocation
16390 ** is outstanding clearing it when the allocation is freed.
16391 */
16392 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16393 static int scratchAllocOut = 0;
16394 #endif
16395
16396
16397 /*
16398 ** Allocate memory that is to be used and released right away.
16399 ** This routine is similar to alloca() in that it is not intended
16400 ** for situations where the memory might be held long-term.  This
16401 ** routine is intended to get memory to old large transient data
16402 ** structures that would not normally fit on the stack of an
16403 ** embedded processor.
16404 */
16405 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
16406   void *p;
16407   assert( n>0 );
16408
16409 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16410   /* Verify that no more than one scratch allocation per thread
16411   ** is outstanding at one time.  (This is only checked in the
16412   ** single-threaded case since checking in the multi-threaded case
16413   ** would be much more complicated.) */
16414   assert( scratchAllocOut==0 );
16415 #endif
16416
16417   if( sqlite3GlobalConfig.szScratch<n ){
16418     goto scratch_overflow;
16419   }else{  
16420     sqlite3_mutex_enter(mem0.mutex);
16421     if( mem0.nScratchFree==0 ){
16422       sqlite3_mutex_leave(mem0.mutex);
16423       goto scratch_overflow;
16424     }else{
16425       int i;
16426       i = mem0.aScratchFree[--mem0.nScratchFree];
16427       i *= sqlite3GlobalConfig.szScratch;
16428       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
16429       sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
16430       sqlite3_mutex_leave(mem0.mutex);
16431       p = (void*)&((char*)sqlite3GlobalConfig.pScratch)[i];
16432       assert(  (((u8*)p - (u8*)0) & 7)==0 );
16433     }
16434   }
16435 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16436   scratchAllocOut = p!=0;
16437 #endif
16438
16439   return p;
16440
16441 scratch_overflow:
16442   if( sqlite3GlobalConfig.bMemstat ){
16443     sqlite3_mutex_enter(mem0.mutex);
16444     sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
16445     n = mallocWithAlarm(n, &p);
16446     if( p ) sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, n);
16447     sqlite3_mutex_leave(mem0.mutex);
16448   }else{
16449     p = sqlite3GlobalConfig.m.xMalloc(n);
16450   }
16451 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16452   scratchAllocOut = p!=0;
16453 #endif
16454   return p;    
16455 }
16456 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
16457   if( p ){
16458
16459 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
16460     /* Verify that no more than one scratch allocation per thread
16461     ** is outstanding at one time.  (This is only checked in the
16462     ** single-threaded case since checking in the multi-threaded case
16463     ** would be much more complicated.) */
16464     assert( scratchAllocOut==1 );
16465     scratchAllocOut = 0;
16466 #endif
16467
16468     if( sqlite3GlobalConfig.pScratch==0
16469            || p<sqlite3GlobalConfig.pScratch
16470            || p>=(void*)mem0.aScratchFree ){
16471       if( sqlite3GlobalConfig.bMemstat ){
16472         int iSize = sqlite3MallocSize(p);
16473         sqlite3_mutex_enter(mem0.mutex);
16474         sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
16475         sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
16476         sqlite3GlobalConfig.m.xFree(p);
16477         sqlite3_mutex_leave(mem0.mutex);
16478       }else{
16479         sqlite3GlobalConfig.m.xFree(p);
16480       }
16481     }else{
16482       int i;
16483       i = (int)((u8*)p - (u8*)sqlite3GlobalConfig.pScratch);
16484       i /= sqlite3GlobalConfig.szScratch;
16485       assert( i>=0 && i<sqlite3GlobalConfig.nScratch );
16486       sqlite3_mutex_enter(mem0.mutex);
16487       assert( mem0.nScratchFree<(u32)sqlite3GlobalConfig.nScratch );
16488       mem0.aScratchFree[mem0.nScratchFree++] = i;
16489       sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
16490       sqlite3_mutex_leave(mem0.mutex);
16491     }
16492   }
16493 }
16494
16495 /*
16496 ** TRUE if p is a lookaside memory allocation from db
16497 */
16498 #ifndef SQLITE_OMIT_LOOKASIDE
16499 static int isLookaside(sqlite3 *db, void *p){
16500   return db && p && p>=db->lookaside.pStart && p<db->lookaside.pEnd;
16501 }
16502 #else
16503 #define isLookaside(A,B) 0
16504 #endif
16505
16506 /*
16507 ** Return the size of a memory allocation previously obtained from
16508 ** sqlite3Malloc() or sqlite3_malloc().
16509 */
16510 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
16511   return sqlite3GlobalConfig.m.xSize(p);
16512 }
16513 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
16514   assert( db==0 || sqlite3_mutex_held(db->mutex) );
16515   if( isLookaside(db, p) ){
16516     return db->lookaside.sz;
16517   }else{
16518     return sqlite3GlobalConfig.m.xSize(p);
16519   }
16520 }
16521
16522 /*
16523 ** Free memory previously obtained from sqlite3Malloc().
16524 */
16525 SQLITE_API void sqlite3_free(void *p){
16526   if( p==0 ) return;
16527   if( sqlite3GlobalConfig.bMemstat ){
16528     sqlite3_mutex_enter(mem0.mutex);
16529     sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
16530     sqlite3GlobalConfig.m.xFree(p);
16531     sqlite3_mutex_leave(mem0.mutex);
16532   }else{
16533     sqlite3GlobalConfig.m.xFree(p);
16534   }
16535 }
16536
16537 /*
16538 ** Free memory that might be associated with a particular database
16539 ** connection.
16540 */
16541 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
16542   assert( db==0 || sqlite3_mutex_held(db->mutex) );
16543   if( isLookaside(db, p) ){
16544     LookasideSlot *pBuf = (LookasideSlot*)p;
16545     pBuf->pNext = db->lookaside.pFree;
16546     db->lookaside.pFree = pBuf;
16547     db->lookaside.nOut--;
16548   }else{
16549     sqlite3_free(p);
16550   }
16551 }
16552
16553 /*
16554 ** Change the size of an existing memory allocation
16555 */
16556 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, int nBytes){
16557   int nOld, nNew;
16558   void *pNew;
16559   if( pOld==0 ){
16560     return sqlite3Malloc(nBytes);
16561   }
16562   if( nBytes<=0 ){
16563     sqlite3_free(pOld);
16564     return 0;
16565   }
16566   if( nBytes>=0x7fffff00 ){
16567     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
16568     return 0;
16569   }
16570   nOld = sqlite3MallocSize(pOld);
16571   nNew = sqlite3GlobalConfig.m.xRoundup(nBytes);
16572   if( nOld==nNew ){
16573     pNew = pOld;
16574   }else if( sqlite3GlobalConfig.bMemstat ){
16575     sqlite3_mutex_enter(mem0.mutex);
16576     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, nBytes);
16577     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED)+nNew-nOld >= 
16578           mem0.alarmThreshold ){
16579       sqlite3MallocAlarm(nNew-nOld);
16580     }
16581     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16582     if( pNew==0 && mem0.alarmCallback ){
16583       sqlite3MallocAlarm(nBytes);
16584       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16585     }
16586     if( pNew ){
16587       nNew = sqlite3MallocSize(pNew);
16588       sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
16589     }
16590     sqlite3_mutex_leave(mem0.mutex);
16591   }else{
16592     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
16593   }
16594   return pNew;
16595 }
16596
16597 /*
16598 ** The public interface to sqlite3Realloc.  Make sure that the memory
16599 ** subsystem is initialized prior to invoking sqliteRealloc.
16600 */
16601 SQLITE_API void *sqlite3_realloc(void *pOld, int n){
16602 #ifndef SQLITE_OMIT_AUTOINIT
16603   if( sqlite3_initialize() ) return 0;
16604 #endif
16605   return sqlite3Realloc(pOld, n);
16606 }
16607
16608
16609 /*
16610 ** Allocate and zero memory.
16611 */ 
16612 SQLITE_PRIVATE void *sqlite3MallocZero(int n){
16613   void *p = sqlite3Malloc(n);
16614   if( p ){
16615     memset(p, 0, n);
16616   }
16617   return p;
16618 }
16619
16620 /*
16621 ** Allocate and zero memory.  If the allocation fails, make
16622 ** the mallocFailed flag in the connection pointer.
16623 */
16624 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, int n){
16625   void *p = sqlite3DbMallocRaw(db, n);
16626   if( p ){
16627     memset(p, 0, n);
16628   }
16629   return p;
16630 }
16631
16632 /*
16633 ** Allocate and zero memory.  If the allocation fails, make
16634 ** the mallocFailed flag in the connection pointer.
16635 **
16636 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
16637 ** failure on the same database connection) then always return 0.
16638 ** Hence for a particular database connection, once malloc starts
16639 ** failing, it fails consistently until mallocFailed is reset.
16640 ** This is an important assumption.  There are many places in the
16641 ** code that do things like this:
16642 **
16643 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
16644 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
16645 **         if( b ) a[10] = 9;
16646 **
16647 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
16648 ** that all prior mallocs (ex: "a") worked too.
16649 */
16650 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, int n){
16651   void *p;
16652   assert( db==0 || sqlite3_mutex_held(db->mutex) );
16653 #ifndef SQLITE_OMIT_LOOKASIDE
16654   if( db ){
16655     LookasideSlot *pBuf;
16656     if( db->mallocFailed ){
16657       return 0;
16658     }
16659     if( db->lookaside.bEnabled && n<=db->lookaside.sz
16660          && (pBuf = db->lookaside.pFree)!=0 ){
16661       db->lookaside.pFree = pBuf->pNext;
16662       db->lookaside.nOut++;
16663       if( db->lookaside.nOut>db->lookaside.mxOut ){
16664         db->lookaside.mxOut = db->lookaside.nOut;
16665       }
16666       return (void*)pBuf;
16667     }
16668   }
16669 #else
16670   if( db && db->mallocFailed ){
16671     return 0;
16672   }
16673 #endif
16674   p = sqlite3Malloc(n);
16675   if( !p && db ){
16676     db->mallocFailed = 1;
16677   }
16678   return p;
16679 }
16680
16681 /*
16682 ** Resize the block of memory pointed to by p to n bytes. If the
16683 ** resize fails, set the mallocFailed flag in the connection object.
16684 */
16685 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, int n){
16686   void *pNew = 0;
16687   assert( db!=0 );
16688   assert( sqlite3_mutex_held(db->mutex) );
16689   if( db->mallocFailed==0 ){
16690     if( p==0 ){
16691       return sqlite3DbMallocRaw(db, n);
16692     }
16693     if( isLookaside(db, p) ){
16694       if( n<=db->lookaside.sz ){
16695         return p;
16696       }
16697       pNew = sqlite3DbMallocRaw(db, n);
16698       if( pNew ){
16699         memcpy(pNew, p, db->lookaside.sz);
16700         sqlite3DbFree(db, p);
16701       }
16702     }else{
16703       pNew = sqlite3_realloc(p, n);
16704       if( !pNew ){
16705         db->mallocFailed = 1;
16706       }
16707     }
16708   }
16709   return pNew;
16710 }
16711
16712 /*
16713 ** Attempt to reallocate p.  If the reallocation fails, then free p
16714 ** and set the mallocFailed flag in the database connection.
16715 */
16716 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, int n){
16717   void *pNew;
16718   pNew = sqlite3DbRealloc(db, p, n);
16719   if( !pNew ){
16720     sqlite3DbFree(db, p);
16721   }
16722   return pNew;
16723 }
16724
16725 /*
16726 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
16727 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
16728 ** is because when memory debugging is turned on, these two functions are 
16729 ** called via macros that record the current file and line number in the
16730 ** ThreadData structure.
16731 */
16732 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
16733   char *zNew;
16734   size_t n;
16735   if( z==0 ){
16736     return 0;
16737   }
16738   n = sqlite3Strlen30(z) + 1;
16739   assert( (n&0x7fffffff)==n );
16740   zNew = sqlite3DbMallocRaw(db, (int)n);
16741   if( zNew ){
16742     memcpy(zNew, z, n);
16743   }
16744   return zNew;
16745 }
16746 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, int n){
16747   char *zNew;
16748   if( z==0 ){
16749     return 0;
16750   }
16751   assert( (n&0x7fffffff)==n );
16752   zNew = sqlite3DbMallocRaw(db, n+1);
16753   if( zNew ){
16754     memcpy(zNew, z, n);
16755     zNew[n] = 0;
16756   }
16757   return zNew;
16758 }
16759
16760 /*
16761 ** Create a string from the zFromat argument and the va_list that follows.
16762 ** Store the string in memory obtained from sqliteMalloc() and make *pz
16763 ** point to that string.
16764 */
16765 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
16766   va_list ap;
16767   char *z;
16768
16769   va_start(ap, zFormat);
16770   z = sqlite3VMPrintf(db, zFormat, ap);
16771   va_end(ap);
16772   sqlite3DbFree(db, *pz);
16773   *pz = z;
16774 }
16775
16776
16777 /*
16778 ** This function must be called before exiting any API function (i.e. 
16779 ** returning control to the user) that has called sqlite3_malloc or
16780 ** sqlite3_realloc.
16781 **
16782 ** The returned value is normally a copy of the second argument to this
16783 ** function. However, if a malloc() failure has occurred since the previous
16784 ** invocation SQLITE_NOMEM is returned instead. 
16785 **
16786 ** If the first argument, db, is not NULL and a malloc() error has occurred,
16787 ** then the connection error-code (the value returned by sqlite3_errcode())
16788 ** is set to SQLITE_NOMEM.
16789 */
16790 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
16791   /* If the db handle is not NULL, then we must hold the connection handle
16792   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
16793   ** is unsafe, as is the call to sqlite3Error().
16794   */
16795   assert( !db || sqlite3_mutex_held(db->mutex) );
16796   if( db && (db->mallocFailed || rc==SQLITE_IOERR_NOMEM) ){
16797     sqlite3Error(db, SQLITE_NOMEM, 0);
16798     db->mallocFailed = 0;
16799     rc = SQLITE_NOMEM;
16800   }
16801   return rc & (db ? db->errMask : 0xff);
16802 }
16803
16804 /************** End of malloc.c **********************************************/
16805 /************** Begin file printf.c ******************************************/
16806 /*
16807 ** The "printf" code that follows dates from the 1980's.  It is in
16808 ** the public domain.  The original comments are included here for
16809 ** completeness.  They are very out-of-date but might be useful as
16810 ** an historical reference.  Most of the "enhancements" have been backed
16811 ** out so that the functionality is now the same as standard printf().
16812 **
16813 **************************************************************************
16814 **
16815 ** The following modules is an enhanced replacement for the "printf" subroutines
16816 ** found in the standard C library.  The following enhancements are
16817 ** supported:
16818 **
16819 **      +  Additional functions.  The standard set of "printf" functions
16820 **         includes printf, fprintf, sprintf, vprintf, vfprintf, and
16821 **         vsprintf.  This module adds the following:
16822 **
16823 **           *  snprintf -- Works like sprintf, but has an extra argument
16824 **                          which is the size of the buffer written to.
16825 **
16826 **           *  mprintf --  Similar to sprintf.  Writes output to memory
16827 **                          obtained from malloc.
16828 **
16829 **           *  xprintf --  Calls a function to dispose of output.
16830 **
16831 **           *  nprintf --  No output, but returns the number of characters
16832 **                          that would have been output by printf.
16833 **
16834 **           *  A v- version (ex: vsnprintf) of every function is also
16835 **              supplied.
16836 **
16837 **      +  A few extensions to the formatting notation are supported:
16838 **
16839 **           *  The "=" flag (similar to "-") causes the output to be
16840 **              be centered in the appropriately sized field.
16841 **
16842 **           *  The %b field outputs an integer in binary notation.
16843 **
16844 **           *  The %c field now accepts a precision.  The character output
16845 **              is repeated by the number of times the precision specifies.
16846 **
16847 **           *  The %' field works like %c, but takes as its character the
16848 **              next character of the format string, instead of the next
16849 **              argument.  For example,  printf("%.78'-")  prints 78 minus
16850 **              signs, the same as  printf("%.78c",'-').
16851 **
16852 **      +  When compiled using GCC on a SPARC, this version of printf is
16853 **         faster than the library printf for SUN OS 4.1.
16854 **
16855 **      +  All functions are fully reentrant.
16856 **
16857 */
16858
16859 /*
16860 ** Conversion types fall into various categories as defined by the
16861 ** following enumeration.
16862 */
16863 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
16864 #define etFLOAT       2 /* Floating point.  %f */
16865 #define etEXP         3 /* Exponentional notation. %e and %E */
16866 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
16867 #define etSIZE        5 /* Return number of characters processed so far. %n */
16868 #define etSTRING      6 /* Strings. %s */
16869 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
16870 #define etPERCENT     8 /* Percent symbol. %% */
16871 #define etCHARX       9 /* Characters. %c */
16872 /* The rest are extensions, not normally found in printf() */
16873 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
16874 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
16875                           NULL pointers replaced by SQL NULL.  %Q */
16876 #define etTOKEN      12 /* a pointer to a Token structure */
16877 #define etSRCLIST    13 /* a pointer to a SrcList */
16878 #define etPOINTER    14 /* The %p conversion */
16879 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
16880 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
16881
16882 #define etINVALID     0 /* Any unrecognized conversion type */
16883
16884
16885 /*
16886 ** An "etByte" is an 8-bit unsigned value.
16887 */
16888 typedef unsigned char etByte;
16889
16890 /*
16891 ** Each builtin conversion character (ex: the 'd' in "%d") is described
16892 ** by an instance of the following structure
16893 */
16894 typedef struct et_info {   /* Information about each format field */
16895   char fmttype;            /* The format field code letter */
16896   etByte base;             /* The base for radix conversion */
16897   etByte flags;            /* One or more of FLAG_ constants below */
16898   etByte type;             /* Conversion paradigm */
16899   etByte charset;          /* Offset into aDigits[] of the digits string */
16900   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
16901 } et_info;
16902
16903 /*
16904 ** Allowed values for et_info.flags
16905 */
16906 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
16907 #define FLAG_INTERN  2     /* True if for internal use only */
16908 #define FLAG_STRING  4     /* Allow infinity precision */
16909
16910
16911 /*
16912 ** The following table is searched linearly, so it is good to put the
16913 ** most frequently used conversion types first.
16914 */
16915 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
16916 static const char aPrefix[] = "-x0\000X0";
16917 static const et_info fmtinfo[] = {
16918   {  'd', 10, 1, etRADIX,      0,  0 },
16919   {  's',  0, 4, etSTRING,     0,  0 },
16920   {  'g',  0, 1, etGENERIC,    30, 0 },
16921   {  'z',  0, 4, etDYNSTRING,  0,  0 },
16922   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
16923   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
16924   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
16925   {  'c',  0, 0, etCHARX,      0,  0 },
16926   {  'o',  8, 0, etRADIX,      0,  2 },
16927   {  'u', 10, 0, etRADIX,      0,  0 },
16928   {  'x', 16, 0, etRADIX,      16, 1 },
16929   {  'X', 16, 0, etRADIX,      0,  4 },
16930 #ifndef SQLITE_OMIT_FLOATING_POINT
16931   {  'f',  0, 1, etFLOAT,      0,  0 },
16932   {  'e',  0, 1, etEXP,        30, 0 },
16933   {  'E',  0, 1, etEXP,        14, 0 },
16934   {  'G',  0, 1, etGENERIC,    14, 0 },
16935 #endif
16936   {  'i', 10, 1, etRADIX,      0,  0 },
16937   {  'n',  0, 0, etSIZE,       0,  0 },
16938   {  '%',  0, 0, etPERCENT,    0,  0 },
16939   {  'p', 16, 0, etPOINTER,    0,  1 },
16940
16941 /* All the rest have the FLAG_INTERN bit set and are thus for internal
16942 ** use only */
16943   {  'T',  0, 2, etTOKEN,      0,  0 },
16944   {  'S',  0, 2, etSRCLIST,    0,  0 },
16945   {  'r', 10, 3, etORDINAL,    0,  0 },
16946 };
16947
16948 /*
16949 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
16950 ** conversions will work.
16951 */
16952 #ifndef SQLITE_OMIT_FLOATING_POINT
16953 /*
16954 ** "*val" is a double such that 0.1 <= *val < 10.0
16955 ** Return the ascii code for the leading digit of *val, then
16956 ** multiply "*val" by 10.0 to renormalize.
16957 **
16958 ** Example:
16959 **     input:     *val = 3.14159
16960 **     output:    *val = 1.4159    function return = '3'
16961 **
16962 ** The counter *cnt is incremented each time.  After counter exceeds
16963 ** 16 (the number of significant digits in a 64-bit float) '0' is
16964 ** always returned.
16965 */
16966 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
16967   int digit;
16968   LONGDOUBLE_TYPE d;
16969   if( (*cnt)++ >= 16 ) return '0';
16970   digit = (int)*val;
16971   d = digit;
16972   digit += '0';
16973   *val = (*val - d)*10.0;
16974   return (char)digit;
16975 }
16976 #endif /* SQLITE_OMIT_FLOATING_POINT */
16977
16978 /*
16979 ** Append N space characters to the given string buffer.
16980 */
16981 static void appendSpace(StrAccum *pAccum, int N){
16982   static const char zSpaces[] = "                             ";
16983   while( N>=(int)sizeof(zSpaces)-1 ){
16984     sqlite3StrAccumAppend(pAccum, zSpaces, sizeof(zSpaces)-1);
16985     N -= sizeof(zSpaces)-1;
16986   }
16987   if( N>0 ){
16988     sqlite3StrAccumAppend(pAccum, zSpaces, N);
16989   }
16990 }
16991
16992 /*
16993 ** On machines with a small stack size, you can redefine the
16994 ** SQLITE_PRINT_BUF_SIZE to be less than 350.
16995 */
16996 #ifndef SQLITE_PRINT_BUF_SIZE
16997 # if defined(SQLITE_SMALL_STACK)
16998 #   define SQLITE_PRINT_BUF_SIZE 50
16999 # else
17000 #   define SQLITE_PRINT_BUF_SIZE 350
17001 # endif
17002 #endif
17003 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
17004
17005 /*
17006 ** The root program.  All variations call this core.
17007 **
17008 ** INPUTS:
17009 **   func   This is a pointer to a function taking three arguments
17010 **            1. A pointer to anything.  Same as the "arg" parameter.
17011 **            2. A pointer to the list of characters to be output
17012 **               (Note, this list is NOT null terminated.)
17013 **            3. An integer number of characters to be output.
17014 **               (Note: This number might be zero.)
17015 **
17016 **   arg    This is the pointer to anything which will be passed as the
17017 **          first argument to "func".  Use it for whatever you like.
17018 **
17019 **   fmt    This is the format string, as in the usual print.
17020 **
17021 **   ap     This is a pointer to a list of arguments.  Same as in
17022 **          vfprint.
17023 **
17024 ** OUTPUTS:
17025 **          The return value is the total number of characters sent to
17026 **          the function "func".  Returns -1 on a error.
17027 **
17028 ** Note that the order in which automatic variables are declared below
17029 ** seems to make a big difference in determining how fast this beast
17030 ** will run.
17031 */
17032 SQLITE_PRIVATE void sqlite3VXPrintf(
17033   StrAccum *pAccum,                  /* Accumulate results here */
17034   int useExtended,                   /* Allow extended %-conversions */
17035   const char *fmt,                   /* Format string */
17036   va_list ap                         /* arguments */
17037 ){
17038   int c;                     /* Next character in the format string */
17039   char *bufpt;               /* Pointer to the conversion buffer */
17040   int precision;             /* Precision of the current field */
17041   int length;                /* Length of the field */
17042   int idx;                   /* A general purpose loop counter */
17043   int width;                 /* Width of the current field */
17044   etByte flag_leftjustify;   /* True if "-" flag is present */
17045   etByte flag_plussign;      /* True if "+" flag is present */
17046   etByte flag_blanksign;     /* True if " " flag is present */
17047   etByte flag_alternateform; /* True if "#" flag is present */
17048   etByte flag_altform2;      /* True if "!" flag is present */
17049   etByte flag_zeropad;       /* True if field width constant starts with zero */
17050   etByte flag_long;          /* True if "l" flag is present */
17051   etByte flag_longlong;      /* True if the "ll" flag is present */
17052   etByte done;               /* Loop termination flag */
17053   sqlite_uint64 longvalue;   /* Value for integer types */
17054   LONGDOUBLE_TYPE realvalue; /* Value for real types */
17055   const et_info *infop;      /* Pointer to the appropriate info structure */
17056   char buf[etBUFSIZE];       /* Conversion buffer */
17057   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
17058   etByte xtype = 0;          /* Conversion paradigm */
17059   char *zExtra;              /* Extra memory used for etTCLESCAPE conversions */
17060 #ifndef SQLITE_OMIT_FLOATING_POINT
17061   int  exp, e2;              /* exponent of real numbers */
17062   double rounder;            /* Used for rounding floating point values */
17063   etByte flag_dp;            /* True if decimal point should be shown */
17064   etByte flag_rtz;           /* True if trailing zeros should be removed */
17065   etByte flag_exp;           /* True to force display of the exponent */
17066   int nsd;                   /* Number of significant digits returned */
17067 #endif
17068
17069   length = 0;
17070   bufpt = 0;
17071   for(; (c=(*fmt))!=0; ++fmt){
17072     if( c!='%' ){
17073       int amt;
17074       bufpt = (char *)fmt;
17075       amt = 1;
17076       while( (c=(*++fmt))!='%' && c!=0 ) amt++;
17077       sqlite3StrAccumAppend(pAccum, bufpt, amt);
17078       if( c==0 ) break;
17079     }
17080     if( (c=(*++fmt))==0 ){
17081       sqlite3StrAccumAppend(pAccum, "%", 1);
17082       break;
17083     }
17084     /* Find out what flags are present */
17085     flag_leftjustify = flag_plussign = flag_blanksign = 
17086      flag_alternateform = flag_altform2 = flag_zeropad = 0;
17087     done = 0;
17088     do{
17089       switch( c ){
17090         case '-':   flag_leftjustify = 1;     break;
17091         case '+':   flag_plussign = 1;        break;
17092         case ' ':   flag_blanksign = 1;       break;
17093         case '#':   flag_alternateform = 1;   break;
17094         case '!':   flag_altform2 = 1;        break;
17095         case '0':   flag_zeropad = 1;         break;
17096         default:    done = 1;                 break;
17097       }
17098     }while( !done && (c=(*++fmt))!=0 );
17099     /* Get the field width */
17100     width = 0;
17101     if( c=='*' ){
17102       width = va_arg(ap,int);
17103       if( width<0 ){
17104         flag_leftjustify = 1;
17105         width = -width;
17106       }
17107       c = *++fmt;
17108     }else{
17109       while( c>='0' && c<='9' ){
17110         width = width*10 + c - '0';
17111         c = *++fmt;
17112       }
17113     }
17114     if( width > etBUFSIZE-10 ){
17115       width = etBUFSIZE-10;
17116     }
17117     /* Get the precision */
17118     if( c=='.' ){
17119       precision = 0;
17120       c = *++fmt;
17121       if( c=='*' ){
17122         precision = va_arg(ap,int);
17123         if( precision<0 ) precision = -precision;
17124         c = *++fmt;
17125       }else{
17126         while( c>='0' && c<='9' ){
17127           precision = precision*10 + c - '0';
17128           c = *++fmt;
17129         }
17130       }
17131     }else{
17132       precision = -1;
17133     }
17134     /* Get the conversion type modifier */
17135     if( c=='l' ){
17136       flag_long = 1;
17137       c = *++fmt;
17138       if( c=='l' ){
17139         flag_longlong = 1;
17140         c = *++fmt;
17141       }else{
17142         flag_longlong = 0;
17143       }
17144     }else{
17145       flag_long = flag_longlong = 0;
17146     }
17147     /* Fetch the info entry for the field */
17148     infop = &fmtinfo[0];
17149     xtype = etINVALID;
17150     for(idx=0; idx<ArraySize(fmtinfo); idx++){
17151       if( c==fmtinfo[idx].fmttype ){
17152         infop = &fmtinfo[idx];
17153         if( useExtended || (infop->flags & FLAG_INTERN)==0 ){
17154           xtype = infop->type;
17155         }else{
17156           return;
17157         }
17158         break;
17159       }
17160     }
17161     zExtra = 0;
17162
17163
17164     /* Limit the precision to prevent overflowing buf[] during conversion */
17165     if( precision>etBUFSIZE-40 && (infop->flags & FLAG_STRING)==0 ){
17166       precision = etBUFSIZE-40;
17167     }
17168
17169     /*
17170     ** At this point, variables are initialized as follows:
17171     **
17172     **   flag_alternateform          TRUE if a '#' is present.
17173     **   flag_altform2               TRUE if a '!' is present.
17174     **   flag_plussign               TRUE if a '+' is present.
17175     **   flag_leftjustify            TRUE if a '-' is present or if the
17176     **                               field width was negative.
17177     **   flag_zeropad                TRUE if the width began with 0.
17178     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
17179     **                               the conversion character.
17180     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
17181     **                               the conversion character.
17182     **   flag_blanksign              TRUE if a ' ' is present.
17183     **   width                       The specified field width.  This is
17184     **                               always non-negative.  Zero is the default.
17185     **   precision                   The specified precision.  The default
17186     **                               is -1.
17187     **   xtype                       The class of the conversion.
17188     **   infop                       Pointer to the appropriate info struct.
17189     */
17190     switch( xtype ){
17191       case etPOINTER:
17192         flag_longlong = sizeof(char*)==sizeof(i64);
17193         flag_long = sizeof(char*)==sizeof(long int);
17194         /* Fall through into the next case */
17195       case etORDINAL:
17196       case etRADIX:
17197         if( infop->flags & FLAG_SIGNED ){
17198           i64 v;
17199           if( flag_longlong ){
17200             v = va_arg(ap,i64);
17201           }else if( flag_long ){
17202             v = va_arg(ap,long int);
17203           }else{
17204             v = va_arg(ap,int);
17205           }
17206           if( v<0 ){
17207             longvalue = -v;
17208             prefix = '-';
17209           }else{
17210             longvalue = v;
17211             if( flag_plussign )        prefix = '+';
17212             else if( flag_blanksign )  prefix = ' ';
17213             else                       prefix = 0;
17214           }
17215         }else{
17216           if( flag_longlong ){
17217             longvalue = va_arg(ap,u64);
17218           }else if( flag_long ){
17219             longvalue = va_arg(ap,unsigned long int);
17220           }else{
17221             longvalue = va_arg(ap,unsigned int);
17222           }
17223           prefix = 0;
17224         }
17225         if( longvalue==0 ) flag_alternateform = 0;
17226         if( flag_zeropad && precision<width-(prefix!=0) ){
17227           precision = width-(prefix!=0);
17228         }
17229         bufpt = &buf[etBUFSIZE-1];
17230         if( xtype==etORDINAL ){
17231           static const char zOrd[] = "thstndrd";
17232           int x = (int)(longvalue % 10);
17233           if( x>=4 || (longvalue/10)%10==1 ){
17234             x = 0;
17235           }
17236           buf[etBUFSIZE-3] = zOrd[x*2];
17237           buf[etBUFSIZE-2] = zOrd[x*2+1];
17238           bufpt -= 2;
17239         }
17240         {
17241           register const char *cset;      /* Use registers for speed */
17242           register int base;
17243           cset = &aDigits[infop->charset];
17244           base = infop->base;
17245           do{                                           /* Convert to ascii */
17246             *(--bufpt) = cset[longvalue%base];
17247             longvalue = longvalue/base;
17248           }while( longvalue>0 );
17249         }
17250         length = (int)(&buf[etBUFSIZE-1]-bufpt);
17251         for(idx=precision-length; idx>0; idx--){
17252           *(--bufpt) = '0';                             /* Zero pad */
17253         }
17254         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
17255         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
17256           const char *pre;
17257           char x;
17258           pre = &aPrefix[infop->prefix];
17259           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
17260         }
17261         length = (int)(&buf[etBUFSIZE-1]-bufpt);
17262         break;
17263       case etFLOAT:
17264       case etEXP:
17265       case etGENERIC:
17266         realvalue = va_arg(ap,double);
17267 #ifdef SQLITE_OMIT_FLOATING_POINT
17268         length = 0;
17269 #else
17270         if( precision<0 ) precision = 6;         /* Set default precision */
17271         if( precision>etBUFSIZE/2-10 ) precision = etBUFSIZE/2-10;
17272         if( realvalue<0.0 ){
17273           realvalue = -realvalue;
17274           prefix = '-';
17275         }else{
17276           if( flag_plussign )          prefix = '+';
17277           else if( flag_blanksign )    prefix = ' ';
17278           else                         prefix = 0;
17279         }
17280         if( xtype==etGENERIC && precision>0 ) precision--;
17281 #if 0
17282         /* Rounding works like BSD when the constant 0.4999 is used.  Wierd! */
17283         for(idx=precision, rounder=0.4999; idx>0; idx--, rounder*=0.1);
17284 #else
17285         /* It makes more sense to use 0.5 */
17286         for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
17287 #endif
17288         if( xtype==etFLOAT ) realvalue += rounder;
17289         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
17290         exp = 0;
17291         if( sqlite3IsNaN((double)realvalue) ){
17292           bufpt = "NaN";
17293           length = 3;
17294           break;
17295         }
17296         if( realvalue>0.0 ){
17297           while( realvalue>=1e32 && exp<=350 ){ realvalue *= 1e-32; exp+=32; }
17298           while( realvalue>=1e8 && exp<=350 ){ realvalue *= 1e-8; exp+=8; }
17299           while( realvalue>=10.0 && exp<=350 ){ realvalue *= 0.1; exp++; }
17300           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
17301           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
17302           if( exp>350 ){
17303             if( prefix=='-' ){
17304               bufpt = "-Inf";
17305             }else if( prefix=='+' ){
17306               bufpt = "+Inf";
17307             }else{
17308               bufpt = "Inf";
17309             }
17310             length = sqlite3Strlen30(bufpt);
17311             break;
17312           }
17313         }
17314         bufpt = buf;
17315         /*
17316         ** If the field type is etGENERIC, then convert to either etEXP
17317         ** or etFLOAT, as appropriate.
17318         */
17319         flag_exp = xtype==etEXP;
17320         if( xtype!=etFLOAT ){
17321           realvalue += rounder;
17322           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
17323         }
17324         if( xtype==etGENERIC ){
17325           flag_rtz = !flag_alternateform;
17326           if( exp<-4 || exp>precision ){
17327             xtype = etEXP;
17328           }else{
17329             precision = precision - exp;
17330             xtype = etFLOAT;
17331           }
17332         }else{
17333           flag_rtz = 0;
17334         }
17335         if( xtype==etEXP ){
17336           e2 = 0;
17337         }else{
17338           e2 = exp;
17339         }
17340         nsd = 0;
17341         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
17342         /* The sign in front of the number */
17343         if( prefix ){
17344           *(bufpt++) = prefix;
17345         }
17346         /* Digits prior to the decimal point */
17347         if( e2<0 ){
17348           *(bufpt++) = '0';
17349         }else{
17350           for(; e2>=0; e2--){
17351             *(bufpt++) = et_getdigit(&realvalue,&nsd);
17352           }
17353         }
17354         /* The decimal point */
17355         if( flag_dp ){
17356           *(bufpt++) = '.';
17357         }
17358         /* "0" digits after the decimal point but before the first
17359         ** significant digit of the number */
17360         for(e2++; e2<0; precision--, e2++){
17361           assert( precision>0 );
17362           *(bufpt++) = '0';
17363         }
17364         /* Significant digits after the decimal point */
17365         while( (precision--)>0 ){
17366           *(bufpt++) = et_getdigit(&realvalue,&nsd);
17367         }
17368         /* Remove trailing zeros and the "." if no digits follow the "." */
17369         if( flag_rtz && flag_dp ){
17370           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
17371           assert( bufpt>buf );
17372           if( bufpt[-1]=='.' ){
17373             if( flag_altform2 ){
17374               *(bufpt++) = '0';
17375             }else{
17376               *(--bufpt) = 0;
17377             }
17378           }
17379         }
17380         /* Add the "eNNN" suffix */
17381         if( flag_exp || xtype==etEXP ){
17382           *(bufpt++) = aDigits[infop->charset];
17383           if( exp<0 ){
17384             *(bufpt++) = '-'; exp = -exp;
17385           }else{
17386             *(bufpt++) = '+';
17387           }
17388           if( exp>=100 ){
17389             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
17390             exp %= 100;
17391           }
17392           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
17393           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
17394         }
17395         *bufpt = 0;
17396
17397         /* The converted number is in buf[] and zero terminated. Output it.
17398         ** Note that the number is in the usual order, not reversed as with
17399         ** integer conversions. */
17400         length = (int)(bufpt-buf);
17401         bufpt = buf;
17402
17403         /* Special case:  Add leading zeros if the flag_zeropad flag is
17404         ** set and we are not left justified */
17405         if( flag_zeropad && !flag_leftjustify && length < width){
17406           int i;
17407           int nPad = width - length;
17408           for(i=width; i>=nPad; i--){
17409             bufpt[i] = bufpt[i-nPad];
17410           }
17411           i = prefix!=0;
17412           while( nPad-- ) bufpt[i++] = '0';
17413           length = width;
17414         }
17415 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
17416         break;
17417       case etSIZE:
17418         *(va_arg(ap,int*)) = pAccum->nChar;
17419         length = width = 0;
17420         break;
17421       case etPERCENT:
17422         buf[0] = '%';
17423         bufpt = buf;
17424         length = 1;
17425         break;
17426       case etCHARX:
17427         c = va_arg(ap,int);
17428         buf[0] = (char)c;
17429         if( precision>=0 ){
17430           for(idx=1; idx<precision; idx++) buf[idx] = (char)c;
17431           length = precision;
17432         }else{
17433           length =1;
17434         }
17435         bufpt = buf;
17436         break;
17437       case etSTRING:
17438       case etDYNSTRING:
17439         bufpt = va_arg(ap,char*);
17440         if( bufpt==0 ){
17441           bufpt = "";
17442         }else if( xtype==etDYNSTRING ){
17443           zExtra = bufpt;
17444         }
17445         if( precision>=0 ){
17446           for(length=0; length<precision && bufpt[length]; length++){}
17447         }else{
17448           length = sqlite3Strlen30(bufpt);
17449         }
17450         break;
17451       case etSQLESCAPE:
17452       case etSQLESCAPE2:
17453       case etSQLESCAPE3: {
17454         int i, j, k, n, isnull;
17455         int needQuote;
17456         char ch;
17457         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
17458         char *escarg = va_arg(ap,char*);
17459         isnull = escarg==0;
17460         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
17461         k = precision;
17462         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
17463           if( ch==q )  n++;
17464         }
17465         needQuote = !isnull && xtype==etSQLESCAPE2;
17466         n += i + 1 + needQuote*2;
17467         if( n>etBUFSIZE ){
17468           bufpt = zExtra = sqlite3Malloc( n );
17469           if( bufpt==0 ){
17470             pAccum->mallocFailed = 1;
17471             return;
17472           }
17473         }else{
17474           bufpt = buf;
17475         }
17476         j = 0;
17477         if( needQuote ) bufpt[j++] = q;
17478         k = i;
17479         for(i=0; i<k; i++){
17480           bufpt[j++] = ch = escarg[i];
17481           if( ch==q ) bufpt[j++] = ch;
17482         }
17483         if( needQuote ) bufpt[j++] = q;
17484         bufpt[j] = 0;
17485         length = j;
17486         /* The precision in %q and %Q means how many input characters to
17487         ** consume, not the length of the output...
17488         ** if( precision>=0 && precision<length ) length = precision; */
17489         break;
17490       }
17491       case etTOKEN: {
17492         Token *pToken = va_arg(ap, Token*);
17493         if( pToken ){
17494           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
17495         }
17496         length = width = 0;
17497         break;
17498       }
17499       case etSRCLIST: {
17500         SrcList *pSrc = va_arg(ap, SrcList*);
17501         int k = va_arg(ap, int);
17502         struct SrcList_item *pItem = &pSrc->a[k];
17503         assert( k>=0 && k<pSrc->nSrc );
17504         if( pItem->zDatabase ){
17505           sqlite3StrAccumAppend(pAccum, pItem->zDatabase, -1);
17506           sqlite3StrAccumAppend(pAccum, ".", 1);
17507         }
17508         sqlite3StrAccumAppend(pAccum, pItem->zName, -1);
17509         length = width = 0;
17510         break;
17511       }
17512       default: {
17513         assert( xtype==etINVALID );
17514         return;
17515       }
17516     }/* End switch over the format type */
17517     /*
17518     ** The text of the conversion is pointed to by "bufpt" and is
17519     ** "length" characters long.  The field width is "width".  Do
17520     ** the output.
17521     */
17522     if( !flag_leftjustify ){
17523       register int nspace;
17524       nspace = width-length;
17525       if( nspace>0 ){
17526         appendSpace(pAccum, nspace);
17527       }
17528     }
17529     if( length>0 ){
17530       sqlite3StrAccumAppend(pAccum, bufpt, length);
17531     }
17532     if( flag_leftjustify ){
17533       register int nspace;
17534       nspace = width-length;
17535       if( nspace>0 ){
17536         appendSpace(pAccum, nspace);
17537       }
17538     }
17539     if( zExtra ){
17540       sqlite3_free(zExtra);
17541     }
17542   }/* End for loop over the format string */
17543 } /* End of function */
17544
17545 /*
17546 ** Append N bytes of text from z to the StrAccum object.
17547 */
17548 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
17549   assert( z!=0 || N==0 );
17550   if( p->tooBig | p->mallocFailed ){
17551     testcase(p->tooBig);
17552     testcase(p->mallocFailed);
17553     return;
17554   }
17555   if( N<0 ){
17556     N = sqlite3Strlen30(z);
17557   }
17558   if( N==0 || NEVER(z==0) ){
17559     return;
17560   }
17561   if( p->nChar+N >= p->nAlloc ){
17562     char *zNew;
17563     if( !p->useMalloc ){
17564       p->tooBig = 1;
17565       N = p->nAlloc - p->nChar - 1;
17566       if( N<=0 ){
17567         return;
17568       }
17569     }else{
17570       i64 szNew = p->nChar;
17571       szNew += N + 1;
17572       if( szNew > p->mxAlloc ){
17573         sqlite3StrAccumReset(p);
17574         p->tooBig = 1;
17575         return;
17576       }else{
17577         p->nAlloc = (int)szNew;
17578       }
17579       zNew = sqlite3DbMallocRaw(p->db, p->nAlloc );
17580       if( zNew ){
17581         memcpy(zNew, p->zText, p->nChar);
17582         sqlite3StrAccumReset(p);
17583         p->zText = zNew;
17584       }else{
17585         p->mallocFailed = 1;
17586         sqlite3StrAccumReset(p);
17587         return;
17588       }
17589     }
17590   }
17591   memcpy(&p->zText[p->nChar], z, N);
17592   p->nChar += N;
17593 }
17594
17595 /*
17596 ** Finish off a string by making sure it is zero-terminated.
17597 ** Return a pointer to the resulting string.  Return a NULL
17598 ** pointer if any kind of error was encountered.
17599 */
17600 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
17601   if( p->zText ){
17602     p->zText[p->nChar] = 0;
17603     if( p->useMalloc && p->zText==p->zBase ){
17604       p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
17605       if( p->zText ){
17606         memcpy(p->zText, p->zBase, p->nChar+1);
17607       }else{
17608         p->mallocFailed = 1;
17609       }
17610     }
17611   }
17612   return p->zText;
17613 }
17614
17615 /*
17616 ** Reset an StrAccum string.  Reclaim all malloced memory.
17617 */
17618 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
17619   if( p->zText!=p->zBase ){
17620     sqlite3DbFree(p->db, p->zText);
17621   }
17622   p->zText = 0;
17623 }
17624
17625 /*
17626 ** Initialize a string accumulator
17627 */
17628 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
17629   p->zText = p->zBase = zBase;
17630   p->db = 0;
17631   p->nChar = 0;
17632   p->nAlloc = n;
17633   p->mxAlloc = mx;
17634   p->useMalloc = 1;
17635   p->tooBig = 0;
17636   p->mallocFailed = 0;
17637 }
17638
17639 /*
17640 ** Print into memory obtained from sqliteMalloc().  Use the internal
17641 ** %-conversion extensions.
17642 */
17643 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
17644   char *z;
17645   char zBase[SQLITE_PRINT_BUF_SIZE];
17646   StrAccum acc;
17647   assert( db!=0 );
17648   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
17649                       db->aLimit[SQLITE_LIMIT_LENGTH]);
17650   acc.db = db;
17651   sqlite3VXPrintf(&acc, 1, zFormat, ap);
17652   z = sqlite3StrAccumFinish(&acc);
17653   if( acc.mallocFailed ){
17654     db->mallocFailed = 1;
17655   }
17656   return z;
17657 }
17658
17659 /*
17660 ** Print into memory obtained from sqliteMalloc().  Use the internal
17661 ** %-conversion extensions.
17662 */
17663 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
17664   va_list ap;
17665   char *z;
17666   va_start(ap, zFormat);
17667   z = sqlite3VMPrintf(db, zFormat, ap);
17668   va_end(ap);
17669   return z;
17670 }
17671
17672 /*
17673 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
17674 ** the string and before returnning.  This routine is intended to be used
17675 ** to modify an existing string.  For example:
17676 **
17677 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
17678 **
17679 */
17680 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
17681   va_list ap;
17682   char *z;
17683   va_start(ap, zFormat);
17684   z = sqlite3VMPrintf(db, zFormat, ap);
17685   va_end(ap);
17686   sqlite3DbFree(db, zStr);
17687   return z;
17688 }
17689
17690 /*
17691 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
17692 ** %-conversion extensions.
17693 */
17694 SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
17695   char *z;
17696   char zBase[SQLITE_PRINT_BUF_SIZE];
17697   StrAccum acc;
17698 #ifndef SQLITE_OMIT_AUTOINIT
17699   if( sqlite3_initialize() ) return 0;
17700 #endif
17701   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
17702   sqlite3VXPrintf(&acc, 0, zFormat, ap);
17703   z = sqlite3StrAccumFinish(&acc);
17704   return z;
17705 }
17706
17707 /*
17708 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
17709 ** %-conversion extensions.
17710 */
17711 SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
17712   va_list ap;
17713   char *z;
17714 #ifndef SQLITE_OMIT_AUTOINIT
17715   if( sqlite3_initialize() ) return 0;
17716 #endif
17717   va_start(ap, zFormat);
17718   z = sqlite3_vmprintf(zFormat, ap);
17719   va_end(ap);
17720   return z;
17721 }
17722
17723 /*
17724 ** sqlite3_snprintf() works like snprintf() except that it ignores the
17725 ** current locale settings.  This is important for SQLite because we
17726 ** are not able to use a "," as the decimal point in place of "." as
17727 ** specified by some locales.
17728 */
17729 SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
17730   char *z;
17731   va_list ap;
17732   StrAccum acc;
17733
17734   if( n<=0 ){
17735     return zBuf;
17736   }
17737   sqlite3StrAccumInit(&acc, zBuf, n, 0);
17738   acc.useMalloc = 0;
17739   va_start(ap,zFormat);
17740   sqlite3VXPrintf(&acc, 0, zFormat, ap);
17741   va_end(ap);
17742   z = sqlite3StrAccumFinish(&acc);
17743   return z;
17744 }
17745
17746 /*
17747 ** This is the routine that actually formats the sqlite3_log() message.
17748 ** We house it in a separate routine from sqlite3_log() to avoid using
17749 ** stack space on small-stack systems when logging is disabled.
17750 **
17751 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
17752 ** allocate memory because it might be called while the memory allocator
17753 ** mutex is held.
17754 */
17755 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
17756   StrAccum acc;                          /* String accumulator */
17757   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
17758
17759   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
17760   acc.useMalloc = 0;
17761   sqlite3VXPrintf(&acc, 0, zFormat, ap);
17762   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
17763                            sqlite3StrAccumFinish(&acc));
17764 }
17765
17766 /*
17767 ** Format and write a message to the log if logging is enabled.
17768 */
17769 SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
17770   va_list ap;                             /* Vararg list */
17771   if( sqlite3GlobalConfig.xLog ){
17772     va_start(ap, zFormat);
17773     renderLogMsg(iErrCode, zFormat, ap);
17774     va_end(ap);
17775   }
17776 }
17777
17778 #if defined(SQLITE_DEBUG)
17779 /*
17780 ** A version of printf() that understands %lld.  Used for debugging.
17781 ** The printf() built into some versions of windows does not understand %lld
17782 ** and segfaults if you give it a long long int.
17783 */
17784 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
17785   va_list ap;
17786   StrAccum acc;
17787   char zBuf[500];
17788   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
17789   acc.useMalloc = 0;
17790   va_start(ap,zFormat);
17791   sqlite3VXPrintf(&acc, 0, zFormat, ap);
17792   va_end(ap);
17793   sqlite3StrAccumFinish(&acc);
17794   fprintf(stdout,"%s", zBuf);
17795   fflush(stdout);
17796 }
17797 #endif
17798
17799 #ifndef SQLITE_OMIT_TRACE
17800 /*
17801 ** variable-argument wrapper around sqlite3VXPrintf().
17802 */
17803 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, const char *zFormat, ...){
17804   va_list ap;
17805   va_start(ap,zFormat);
17806   sqlite3VXPrintf(p, 1, zFormat, ap);
17807   va_end(ap);
17808 }
17809 #endif
17810
17811 /************** End of printf.c **********************************************/
17812 /************** Begin file random.c ******************************************/
17813 /*
17814 ** 2001 September 15
17815 **
17816 ** The author disclaims copyright to this source code.  In place of
17817 ** a legal notice, here is a blessing:
17818 **
17819 **    May you do good and not evil.
17820 **    May you find forgiveness for yourself and forgive others.
17821 **    May you share freely, never taking more than you give.
17822 **
17823 *************************************************************************
17824 ** This file contains code to implement a pseudo-random number
17825 ** generator (PRNG) for SQLite.
17826 **
17827 ** Random numbers are used by some of the database backends in order
17828 ** to generate random integer keys for tables or random filenames.
17829 */
17830
17831
17832 /* All threads share a single random number generator.
17833 ** This structure is the current state of the generator.
17834 */
17835 static SQLITE_WSD struct sqlite3PrngType {
17836   unsigned char isInit;          /* True if initialized */
17837   unsigned char i, j;            /* State variables */
17838   unsigned char s[256];          /* State variables */
17839 } sqlite3Prng;
17840
17841 /*
17842 ** Get a single 8-bit random value from the RC4 PRNG.  The Mutex
17843 ** must be held while executing this routine.
17844 **
17845 ** Why not just use a library random generator like lrand48() for this?
17846 ** Because the OP_NewRowid opcode in the VDBE depends on having a very
17847 ** good source of random numbers.  The lrand48() library function may
17848 ** well be good enough.  But maybe not.  Or maybe lrand48() has some
17849 ** subtle problems on some systems that could cause problems.  It is hard
17850 ** to know.  To minimize the risk of problems due to bad lrand48()
17851 ** implementations, SQLite uses this random number generator based
17852 ** on RC4, which we know works very well.
17853 **
17854 ** (Later):  Actually, OP_NewRowid does not depend on a good source of
17855 ** randomness any more.  But we will leave this code in all the same.
17856 */
17857 static u8 randomByte(void){
17858   unsigned char t;
17859
17860
17861   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
17862   ** state vector.  If writable static data is unsupported on the target,
17863   ** we have to locate the state vector at run-time.  In the more common
17864   ** case where writable static data is supported, wsdPrng can refer directly
17865   ** to the "sqlite3Prng" state vector declared above.
17866   */
17867 #ifdef SQLITE_OMIT_WSD
17868   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
17869 # define wsdPrng p[0]
17870 #else
17871 # define wsdPrng sqlite3Prng
17872 #endif
17873
17874
17875   /* Initialize the state of the random number generator once,
17876   ** the first time this routine is called.  The seed value does
17877   ** not need to contain a lot of randomness since we are not
17878   ** trying to do secure encryption or anything like that...
17879   **
17880   ** Nothing in this file or anywhere else in SQLite does any kind of
17881   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
17882   ** number generator) not as an encryption device.
17883   */
17884   if( !wsdPrng.isInit ){
17885     int i;
17886     char k[256];
17887     wsdPrng.j = 0;
17888     wsdPrng.i = 0;
17889     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
17890     for(i=0; i<256; i++){
17891       wsdPrng.s[i] = (u8)i;
17892     }
17893     for(i=0; i<256; i++){
17894       wsdPrng.j += wsdPrng.s[i] + k[i];
17895       t = wsdPrng.s[wsdPrng.j];
17896       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
17897       wsdPrng.s[i] = t;
17898     }
17899     wsdPrng.isInit = 1;
17900   }
17901
17902   /* Generate and return single random byte
17903   */
17904   wsdPrng.i++;
17905   t = wsdPrng.s[wsdPrng.i];
17906   wsdPrng.j += t;
17907   wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
17908   wsdPrng.s[wsdPrng.j] = t;
17909   t += wsdPrng.s[wsdPrng.i];
17910   return wsdPrng.s[t];
17911 }
17912
17913 /*
17914 ** Return N random bytes.
17915 */
17916 SQLITE_API void sqlite3_randomness(int N, void *pBuf){
17917   unsigned char *zBuf = pBuf;
17918 #if SQLITE_THREADSAFE
17919   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
17920 #endif
17921   sqlite3_mutex_enter(mutex);
17922   while( N-- ){
17923     *(zBuf++) = randomByte();
17924   }
17925   sqlite3_mutex_leave(mutex);
17926 }
17927
17928 #ifndef SQLITE_OMIT_BUILTIN_TEST
17929 /*
17930 ** For testing purposes, we sometimes want to preserve the state of
17931 ** PRNG and restore the PRNG to its saved state at a later time, or
17932 ** to reset the PRNG to its initial state.  These routines accomplish
17933 ** those tasks.
17934 **
17935 ** The sqlite3_test_control() interface calls these routines to
17936 ** control the PRNG.
17937 */
17938 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
17939 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
17940   memcpy(
17941     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
17942     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
17943     sizeof(sqlite3Prng)
17944   );
17945 }
17946 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
17947   memcpy(
17948     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
17949     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
17950     sizeof(sqlite3Prng)
17951   );
17952 }
17953 SQLITE_PRIVATE void sqlite3PrngResetState(void){
17954   GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
17955 }
17956 #endif /* SQLITE_OMIT_BUILTIN_TEST */
17957
17958 /************** End of random.c **********************************************/
17959 /************** Begin file utf.c *********************************************/
17960 /*
17961 ** 2004 April 13
17962 **
17963 ** The author disclaims copyright to this source code.  In place of
17964 ** a legal notice, here is a blessing:
17965 **
17966 **    May you do good and not evil.
17967 **    May you find forgiveness for yourself and forgive others.
17968 **    May you share freely, never taking more than you give.
17969 **
17970 *************************************************************************
17971 ** This file contains routines used to translate between UTF-8, 
17972 ** UTF-16, UTF-16BE, and UTF-16LE.
17973 **
17974 ** Notes on UTF-8:
17975 **
17976 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
17977 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
17978 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
17979 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
17980 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
17981 **
17982 **
17983 ** Notes on UTF-16:  (with wwww+1==uuuuu)
17984 **
17985 **      Word-0               Word-1          Value
17986 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
17987 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
17988 **
17989 **
17990 ** BOM or Byte Order Mark:
17991 **     0xff 0xfe   little-endian utf-16 follows
17992 **     0xfe 0xff   big-endian utf-16 follows
17993 **
17994 */
17995 /************** Include vdbeInt.h in the middle of utf.c *********************/
17996 /************** Begin file vdbeInt.h *****************************************/
17997 /*
17998 ** 2003 September 6
17999 **
18000 ** The author disclaims copyright to this source code.  In place of
18001 ** a legal notice, here is a blessing:
18002 **
18003 **    May you do good and not evil.
18004 **    May you find forgiveness for yourself and forgive others.
18005 **    May you share freely, never taking more than you give.
18006 **
18007 *************************************************************************
18008 ** This is the header file for information that is private to the
18009 ** VDBE.  This information used to all be at the top of the single
18010 ** source code file "vdbe.c".  When that file became too big (over
18011 ** 6000 lines long) it was split up into several smaller files and
18012 ** this header information was factored out.
18013 */
18014 #ifndef _VDBEINT_H_
18015 #define _VDBEINT_H_
18016
18017 /*
18018 ** SQL is translated into a sequence of instructions to be
18019 ** executed by a virtual machine.  Each instruction is an instance
18020 ** of the following structure.
18021 */
18022 typedef struct VdbeOp Op;
18023
18024 /*
18025 ** Boolean values
18026 */
18027 typedef unsigned char Bool;
18028
18029 /*
18030 ** A cursor is a pointer into a single BTree within a database file.
18031 ** The cursor can seek to a BTree entry with a particular key, or
18032 ** loop over all entries of the Btree.  You can also insert new BTree
18033 ** entries or retrieve the key or data from the entry that the cursor
18034 ** is currently pointing to.
18035 ** 
18036 ** Every cursor that the virtual machine has open is represented by an
18037 ** instance of the following structure.
18038 **
18039 ** If the VdbeCursor.isTriggerRow flag is set it means that this cursor is
18040 ** really a single row that represents the NEW or OLD pseudo-table of
18041 ** a row trigger.  The data for the row is stored in VdbeCursor.pData and
18042 ** the rowid is in VdbeCursor.iKey.
18043 */
18044 struct VdbeCursor {
18045   BtCursor *pCursor;    /* The cursor structure of the backend */
18046   int iDb;              /* Index of cursor database in db->aDb[] (or -1) */
18047   i64 lastRowid;        /* Last rowid from a Next or NextIdx operation */
18048   Bool zeroed;          /* True if zeroed out and ready for reuse */
18049   Bool rowidIsValid;    /* True if lastRowid is valid */
18050   Bool atFirst;         /* True if pointing to first entry */
18051   Bool useRandomRowid;  /* Generate new record numbers semi-randomly */
18052   Bool nullRow;         /* True if pointing to a row with no data */
18053   Bool deferredMoveto;  /* A call to sqlite3BtreeMoveto() is needed */
18054   Bool isTable;         /* True if a table requiring integer keys */
18055   Bool isIndex;         /* True if an index containing keys only - no data */
18056   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
18057   Btree *pBt;           /* Separate file holding temporary table */
18058   int pseudoTableReg;   /* Register holding pseudotable content. */
18059   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
18060   int nField;           /* Number of fields in the header */
18061   i64 seqCount;         /* Sequence counter */
18062   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
18063   const sqlite3_module *pModule;     /* Module for cursor pVtabCursor */
18064
18065   /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or 
18066   ** OP_IsUnique opcode on this cursor. */
18067   int seekResult;
18068
18069   /* Cached information about the header for the data record that the
18070   ** cursor is currently pointing to.  Only valid if cacheStatus matches
18071   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
18072   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
18073   ** the cache is out of date.
18074   **
18075   ** aRow might point to (ephemeral) data for the current row, or it might
18076   ** be NULL.
18077   */
18078   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
18079   int payloadSize;      /* Total number of bytes in the record */
18080   u32 *aType;           /* Type values for all entries in the record */
18081   u32 *aOffset;         /* Cached offsets to the start of each columns data */
18082   u8 *aRow;             /* Data for the current row, if all on one page */
18083 };
18084 typedef struct VdbeCursor VdbeCursor;
18085
18086 /*
18087 ** When a sub-program is executed (OP_Program), a structure of this type
18088 ** is allocated to store the current value of the program counter, as
18089 ** well as the current memory cell array and various other frame specific
18090 ** values stored in the Vdbe struct. When the sub-program is finished, 
18091 ** these values are copied back to the Vdbe from the VdbeFrame structure,
18092 ** restoring the state of the VM to as it was before the sub-program
18093 ** began executing.
18094 **
18095 ** Frames are stored in a linked list headed at Vdbe.pParent. Vdbe.pParent
18096 ** is the parent of the current frame, or zero if the current frame
18097 ** is the main Vdbe program.
18098 */
18099 typedef struct VdbeFrame VdbeFrame;
18100 struct VdbeFrame {
18101   Vdbe *v;                /* VM this frame belongs to */
18102   int pc;                 /* Program Counter */
18103   Op *aOp;                /* Program instructions */
18104   int nOp;                /* Size of aOp array */
18105   Mem *aMem;              /* Array of memory cells */
18106   int nMem;               /* Number of entries in aMem */
18107   VdbeCursor **apCsr;     /* Element of Vdbe cursors */
18108   u16 nCursor;            /* Number of entries in apCsr */
18109   void *token;            /* Copy of SubProgram.token */
18110   int nChildMem;          /* Number of memory cells for child frame */
18111   int nChildCsr;          /* Number of cursors for child frame */
18112   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
18113   int nChange;            /* Statement changes (Vdbe.nChanges)     */
18114   VdbeFrame *pParent;     /* Parent of this frame */
18115 };
18116
18117 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
18118
18119 /*
18120 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
18121 */
18122 #define CACHE_STALE 0
18123
18124 /*
18125 ** Internally, the vdbe manipulates nearly all SQL values as Mem
18126 ** structures. Each Mem struct may cache multiple representations (string,
18127 ** integer etc.) of the same value.  A value (and therefore Mem structure)
18128 ** has the following properties:
18129 **
18130 ** Each value has a manifest type. The manifest type of the value stored
18131 ** in a Mem struct is returned by the MemType(Mem*) macro. The type is
18132 ** one of SQLITE_NULL, SQLITE_INTEGER, SQLITE_REAL, SQLITE_TEXT or
18133 ** SQLITE_BLOB.
18134 */
18135 struct Mem {
18136   union {
18137     i64 i;              /* Integer value. */
18138     int nZero;          /* Used when bit MEM_Zero is set in flags */
18139     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
18140     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
18141     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
18142   } u;
18143   double r;           /* Real value */
18144   sqlite3 *db;        /* The associated database connection */
18145   char *z;            /* String or BLOB value */
18146   int n;              /* Number of characters in string value, excluding '\0' */
18147   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
18148   u8  type;           /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
18149   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
18150   void (*xDel)(void *);  /* If not null, call this function to delete Mem.z */
18151   char *zMalloc;      /* Dynamic buffer allocated by sqlite3_malloc() */
18152 };
18153
18154 /* One or more of the following flags are set to indicate the validOK
18155 ** representations of the value stored in the Mem struct.
18156 **
18157 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
18158 ** No other flags may be set in this case.
18159 **
18160 ** If the MEM_Str flag is set then Mem.z points at a string representation.
18161 ** Usually this is encoded in the same unicode encoding as the main
18162 ** database (see below for exceptions). If the MEM_Term flag is also
18163 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
18164 ** flags may coexist with the MEM_Str flag.
18165 **
18166 ** Multiple of these values can appear in Mem.flags.  But only one
18167 ** at a time can appear in Mem.type.
18168 */
18169 #define MEM_Null      0x0001   /* Value is NULL */
18170 #define MEM_Str       0x0002   /* Value is a string */
18171 #define MEM_Int       0x0004   /* Value is an integer */
18172 #define MEM_Real      0x0008   /* Value is a real number */
18173 #define MEM_Blob      0x0010   /* Value is a BLOB */
18174 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
18175 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
18176 #define MEM_TypeMask  0x00ff   /* Mask of type bits */
18177
18178 /* Whenever Mem contains a valid string or blob representation, one of
18179 ** the following flags must be set to determine the memory management
18180 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
18181 ** string is \000 or \u0000 terminated
18182 */
18183 #define MEM_Term      0x0200   /* String rep is nul terminated */
18184 #define MEM_Dyn       0x0400   /* Need to call sqliteFree() on Mem.z */
18185 #define MEM_Static    0x0800   /* Mem.z points to a static string */
18186 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
18187 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
18188 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
18189
18190 #ifdef SQLITE_OMIT_INCRBLOB
18191   #undef MEM_Zero
18192   #define MEM_Zero 0x0000
18193 #endif
18194
18195
18196 /*
18197 ** Clear any existing type flags from a Mem and replace them with f
18198 */
18199 #define MemSetTypeFlag(p, f) \
18200    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
18201
18202
18203 /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
18204 ** additional information about auxiliary information bound to arguments
18205 ** of the function.  This is used to implement the sqlite3_get_auxdata()
18206 ** and sqlite3_set_auxdata() APIs.  The "auxdata" is some auxiliary data
18207 ** that can be associated with a constant argument to a function.  This
18208 ** allows functions such as "regexp" to compile their constant regular
18209 ** expression argument once and reused the compiled code for multiple
18210 ** invocations.
18211 */
18212 struct VdbeFunc {
18213   FuncDef *pFunc;               /* The definition of the function */
18214   int nAux;                     /* Number of entries allocated for apAux[] */
18215   struct AuxData {
18216     void *pAux;                   /* Aux data for the i-th argument */
18217     void (*xDelete)(void *);      /* Destructor for the aux data */
18218   } apAux[1];                   /* One slot for each function argument */
18219 };
18220
18221 /*
18222 ** The "context" argument for a installable function.  A pointer to an
18223 ** instance of this structure is the first argument to the routines used
18224 ** implement the SQL functions.
18225 **
18226 ** There is a typedef for this structure in sqlite.h.  So all routines,
18227 ** even the public interface to SQLite, can use a pointer to this structure.
18228 ** But this file is the only place where the internal details of this
18229 ** structure are known.
18230 **
18231 ** This structure is defined inside of vdbeInt.h because it uses substructures
18232 ** (Mem) which are only defined there.
18233 */
18234 struct sqlite3_context {
18235   FuncDef *pFunc;       /* Pointer to function information.  MUST BE FIRST */
18236   VdbeFunc *pVdbeFunc;  /* Auxilary data, if created. */
18237   Mem s;                /* The return value is stored here */
18238   Mem *pMem;            /* Memory cell used to store aggregate context */
18239   int isError;          /* Error code returned by the function. */
18240   CollSeq *pColl;       /* Collating sequence */
18241 };
18242
18243 /*
18244 ** A Set structure is used for quick testing to see if a value
18245 ** is part of a small set.  Sets are used to implement code like
18246 ** this:
18247 **            x.y IN ('hi','hoo','hum')
18248 */
18249 typedef struct Set Set;
18250 struct Set {
18251   Hash hash;             /* A set is just a hash table */
18252   HashElem *prev;        /* Previously accessed hash elemen */
18253 };
18254
18255 /*
18256 ** An instance of the virtual machine.  This structure contains the complete
18257 ** state of the virtual machine.
18258 **
18259 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_compile()
18260 ** is really a pointer to an instance of this structure.
18261 **
18262 ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
18263 ** any virtual table method invocations made by the vdbe program. It is
18264 ** set to 2 for xDestroy method calls and 1 for all other methods. This
18265 ** variable is used for two purposes: to allow xDestroy methods to execute
18266 ** "DROP TABLE" statements and to prevent some nasty side effects of
18267 ** malloc failure when SQLite is invoked recursively by a virtual table 
18268 ** method function.
18269 */
18270 struct Vdbe {
18271   sqlite3 *db;            /* The database connection that owns this statement */
18272   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
18273   int nOp;                /* Number of instructions in the program */
18274   int nOpAlloc;           /* Number of slots allocated for aOp[] */
18275   Op *aOp;                /* Space to hold the virtual machine's program */
18276   int nLabel;             /* Number of labels used */
18277   int nLabelAlloc;        /* Number of slots allocated in aLabel[] */
18278   int *aLabel;            /* Space to hold the labels */
18279   Mem **apArg;            /* Arguments to currently executing user function */
18280   Mem *aColName;          /* Column names to return */
18281   Mem *pResultSet;        /* Pointer to an array of results */
18282   u16 nResColumn;         /* Number of columns in one row of the result set */
18283   u16 nCursor;            /* Number of slots in apCsr[] */
18284   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
18285   u8 errorAction;         /* Recovery action to do in case of an error */
18286   u8 okVar;               /* True if azVar[] has been initialized */
18287   ynVar nVar;             /* Number of entries in aVar[] */
18288   Mem *aVar;              /* Values for the OP_Variable opcode. */
18289   char **azVar;           /* Name of variables */
18290   u32 magic;              /* Magic number for sanity checking */
18291   int nMem;               /* Number of memory locations currently allocated */
18292   Mem *aMem;              /* The memory locations */
18293   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
18294   int pc;                 /* The program counter */
18295   int rc;                 /* Value to return */
18296   char *zErrMsg;          /* Error message written here */
18297   u8 explain;             /* True if EXPLAIN present on SQL command */
18298   u8 changeCntOn;         /* True to update the change-counter */
18299   u8 expired;             /* True if the VM needs to be recompiled */
18300   u8 runOnlyOnce;         /* Automatically expire on reset */
18301   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
18302   u8 inVtabMethod;        /* See comments above */
18303   u8 usesStmtJournal;     /* True if uses a statement journal */
18304   u8 readOnly;            /* True for read-only statements */
18305   u8 isPrepareV2;         /* True if prepared with prepare_v2() */
18306   int nChange;            /* Number of db changes made since last reset */
18307   int btreeMask;          /* Bitmask of db->aDb[] entries referenced */
18308   i64 startTime;          /* Time when query started - used for profiling */
18309   BtreeMutexArray aMutex; /* An array of Btree used here and needing locks */
18310   int aCounter[2];        /* Counters used by sqlite3_stmt_status() */
18311   char *zSql;             /* Text of the SQL statement that generated this */
18312   void *pFree;            /* Free this when deleting the vdbe */
18313   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
18314   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
18315   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
18316 #ifdef SQLITE_DEBUG
18317   FILE *trace;            /* Write an execution trace here, if not NULL */
18318 #endif
18319   VdbeFrame *pFrame;      /* Parent frame */
18320   int nFrame;             /* Number of frames in pFrame list */
18321   u32 expmask;            /* Binding to these vars invalidates VM */
18322 };
18323
18324 /*
18325 ** The following are allowed values for Vdbe.magic
18326 */
18327 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
18328 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
18329 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
18330 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
18331
18332 /*
18333 ** Function prototypes
18334 */
18335 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
18336 void sqliteVdbePopStack(Vdbe*,int);
18337 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
18338 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
18339 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
18340 #endif
18341 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
18342 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
18343 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
18344 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
18345 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
18346
18347 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
18348 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int*);
18349 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor *, i64 *);
18350 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
18351 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
18352 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
18353 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
18354 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
18355 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
18356 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
18357 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
18358 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
18359 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
18360 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
18361 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
18362 #ifdef SQLITE_OMIT_FLOATING_POINT
18363 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
18364 #else
18365 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
18366 #endif
18367 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
18368 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
18369 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
18370 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
18371 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, int);
18372 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
18373 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
18374 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
18375 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
18376 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
18377 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
18378 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem*);
18379 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
18380 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p);
18381 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
18382 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
18383 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
18384 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
18385 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
18386 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
18387 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem);
18388
18389 #ifndef SQLITE_OMIT_FOREIGN_KEY
18390 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
18391 #else
18392 # define sqlite3VdbeCheckFk(p,i) 0
18393 #endif
18394
18395 #ifndef SQLITE_OMIT_SHARED_CACHE
18396 SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p);
18397 #else
18398 # define sqlite3VdbeMutexArrayEnter(p)
18399 #endif
18400
18401 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
18402 #ifdef SQLITE_DEBUG
18403 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
18404 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
18405 #endif
18406 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
18407
18408 #ifndef SQLITE_OMIT_INCRBLOB
18409 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
18410 #else
18411   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
18412 #endif
18413
18414 #endif /* !defined(_VDBEINT_H_) */
18415
18416 /************** End of vdbeInt.h *********************************************/
18417 /************** Continuing where we left off in utf.c ************************/
18418
18419 #ifndef SQLITE_AMALGAMATION
18420 /*
18421 ** The following constant value is used by the SQLITE_BIGENDIAN and
18422 ** SQLITE_LITTLEENDIAN macros.
18423 */
18424 SQLITE_PRIVATE const int sqlite3one = 1;
18425 #endif /* SQLITE_AMALGAMATION */
18426
18427 /*
18428 ** This lookup table is used to help decode the first byte of
18429 ** a multi-byte UTF8 character.
18430 */
18431 static const unsigned char sqlite3Utf8Trans1[] = {
18432   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18433   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
18434   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
18435   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
18436   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18437   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
18438   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
18439   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
18440 };
18441
18442
18443 #define WRITE_UTF8(zOut, c) {                          \
18444   if( c<0x00080 ){                                     \
18445     *zOut++ = (u8)(c&0xFF);                            \
18446   }                                                    \
18447   else if( c<0x00800 ){                                \
18448     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
18449     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
18450   }                                                    \
18451   else if( c<0x10000 ){                                \
18452     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
18453     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
18454     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
18455   }else{                                               \
18456     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
18457     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
18458     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
18459     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
18460   }                                                    \
18461 }
18462
18463 #define WRITE_UTF16LE(zOut, c) {                                    \
18464   if( c<=0xFFFF ){                                                  \
18465     *zOut++ = (u8)(c&0x00FF);                                       \
18466     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
18467   }else{                                                            \
18468     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
18469     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
18470     *zOut++ = (u8)(c&0x00FF);                                       \
18471     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
18472   }                                                                 \
18473 }
18474
18475 #define WRITE_UTF16BE(zOut, c) {                                    \
18476   if( c<=0xFFFF ){                                                  \
18477     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
18478     *zOut++ = (u8)(c&0x00FF);                                       \
18479   }else{                                                            \
18480     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
18481     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
18482     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
18483     *zOut++ = (u8)(c&0x00FF);                                       \
18484   }                                                                 \
18485 }
18486
18487 #define READ_UTF16LE(zIn, TERM, c){                                   \
18488   c = (*zIn++);                                                       \
18489   c += ((*zIn++)<<8);                                                 \
18490   if( c>=0xD800 && c<0xE000 && TERM ){                                \
18491     int c2 = (*zIn++);                                                \
18492     c2 += ((*zIn++)<<8);                                              \
18493     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
18494   }                                                                   \
18495 }
18496
18497 #define READ_UTF16BE(zIn, TERM, c){                                   \
18498   c = ((*zIn++)<<8);                                                  \
18499   c += (*zIn++);                                                      \
18500   if( c>=0xD800 && c<0xE000 && TERM ){                                \
18501     int c2 = ((*zIn++)<<8);                                           \
18502     c2 += (*zIn++);                                                   \
18503     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
18504   }                                                                   \
18505 }
18506
18507 /*
18508 ** Translate a single UTF-8 character.  Return the unicode value.
18509 **
18510 ** During translation, assume that the byte that zTerm points
18511 ** is a 0x00.
18512 **
18513 ** Write a pointer to the next unread byte back into *pzNext.
18514 **
18515 ** Notes On Invalid UTF-8:
18516 **
18517 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
18518 **     be encoded as a multi-byte character.  Any multi-byte character that
18519 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
18520 **
18521 **  *  This routine never allows a UTF16 surrogate value to be encoded.
18522 **     If a multi-byte character attempts to encode a value between
18523 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
18524 **
18525 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
18526 **     byte of a character are interpreted as single-byte characters
18527 **     and rendered as themselves even though they are technically
18528 **     invalid characters.
18529 **
18530 **  *  This routine accepts an infinite number of different UTF8 encodings
18531 **     for unicode values 0x80 and greater.  It do not change over-length
18532 **     encodings to 0xfffd as some systems recommend.
18533 */
18534 #define READ_UTF8(zIn, zTerm, c)                           \
18535   c = *(zIn++);                                            \
18536   if( c>=0xc0 ){                                           \
18537     c = sqlite3Utf8Trans1[c-0xc0];                         \
18538     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
18539       c = (c<<6) + (0x3f & *(zIn++));                      \
18540     }                                                      \
18541     if( c<0x80                                             \
18542         || (c&0xFFFFF800)==0xD800                          \
18543         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
18544   }
18545 SQLITE_PRIVATE int sqlite3Utf8Read(
18546   const unsigned char *zIn,       /* First byte of UTF-8 character */
18547   const unsigned char **pzNext    /* Write first byte past UTF-8 char here */
18548 ){
18549   int c;
18550
18551   /* Same as READ_UTF8() above but without the zTerm parameter.
18552   ** For this routine, we assume the UTF8 string is always zero-terminated.
18553   */
18554   c = *(zIn++);
18555   if( c>=0xc0 ){
18556     c = sqlite3Utf8Trans1[c-0xc0];
18557     while( (*zIn & 0xc0)==0x80 ){
18558       c = (c<<6) + (0x3f & *(zIn++));
18559     }
18560     if( c<0x80
18561         || (c&0xFFFFF800)==0xD800
18562         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
18563   }
18564   *pzNext = zIn;
18565   return c;
18566 }
18567
18568
18569
18570
18571 /*
18572 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
18573 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
18574 */ 
18575 /* #define TRANSLATE_TRACE 1 */
18576
18577 #ifndef SQLITE_OMIT_UTF16
18578 /*
18579 ** This routine transforms the internal text encoding used by pMem to
18580 ** desiredEnc. It is an error if the string is already of the desired
18581 ** encoding, or if *pMem does not contain a string value.
18582 */
18583 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
18584   int len;                    /* Maximum length of output string in bytes */
18585   unsigned char *zOut;                  /* Output buffer */
18586   unsigned char *zIn;                   /* Input iterator */
18587   unsigned char *zTerm;                 /* End of input */
18588   unsigned char *z;                     /* Output iterator */
18589   unsigned int c;
18590
18591   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
18592   assert( pMem->flags&MEM_Str );
18593   assert( pMem->enc!=desiredEnc );
18594   assert( pMem->enc!=0 );
18595   assert( pMem->n>=0 );
18596
18597 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
18598   {
18599     char zBuf[100];
18600     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
18601     fprintf(stderr, "INPUT:  %s\n", zBuf);
18602   }
18603 #endif
18604
18605   /* If the translation is between UTF-16 little and big endian, then 
18606   ** all that is required is to swap the byte order. This case is handled
18607   ** differently from the others.
18608   */
18609   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
18610     u8 temp;
18611     int rc;
18612     rc = sqlite3VdbeMemMakeWriteable(pMem);
18613     if( rc!=SQLITE_OK ){
18614       assert( rc==SQLITE_NOMEM );
18615       return SQLITE_NOMEM;
18616     }
18617     zIn = (u8*)pMem->z;
18618     zTerm = &zIn[pMem->n&~1];
18619     while( zIn<zTerm ){
18620       temp = *zIn;
18621       *zIn = *(zIn+1);
18622       zIn++;
18623       *zIn++ = temp;
18624     }
18625     pMem->enc = desiredEnc;
18626     goto translate_out;
18627   }
18628
18629   /* Set len to the maximum number of bytes required in the output buffer. */
18630   if( desiredEnc==SQLITE_UTF8 ){
18631     /* When converting from UTF-16, the maximum growth results from
18632     ** translating a 2-byte character to a 4-byte UTF-8 character.
18633     ** A single byte is required for the output string
18634     ** nul-terminator.
18635     */
18636     pMem->n &= ~1;
18637     len = pMem->n * 2 + 1;
18638   }else{
18639     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
18640     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
18641     ** character. Two bytes are required in the output buffer for the
18642     ** nul-terminator.
18643     */
18644     len = pMem->n * 2 + 2;
18645   }
18646
18647   /* Set zIn to point at the start of the input buffer and zTerm to point 1
18648   ** byte past the end.
18649   **
18650   ** Variable zOut is set to point at the output buffer, space obtained
18651   ** from sqlite3_malloc().
18652   */
18653   zIn = (u8*)pMem->z;
18654   zTerm = &zIn[pMem->n];
18655   zOut = sqlite3DbMallocRaw(pMem->db, len);
18656   if( !zOut ){
18657     return SQLITE_NOMEM;
18658   }
18659   z = zOut;
18660
18661   if( pMem->enc==SQLITE_UTF8 ){
18662     if( desiredEnc==SQLITE_UTF16LE ){
18663       /* UTF-8 -> UTF-16 Little-endian */
18664       while( zIn<zTerm ){
18665         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
18666         READ_UTF8(zIn, zTerm, c);
18667         WRITE_UTF16LE(z, c);
18668       }
18669     }else{
18670       assert( desiredEnc==SQLITE_UTF16BE );
18671       /* UTF-8 -> UTF-16 Big-endian */
18672       while( zIn<zTerm ){
18673         /* c = sqlite3Utf8Read(zIn, zTerm, (const u8**)&zIn); */
18674         READ_UTF8(zIn, zTerm, c);
18675         WRITE_UTF16BE(z, c);
18676       }
18677     }
18678     pMem->n = (int)(z - zOut);
18679     *z++ = 0;
18680   }else{
18681     assert( desiredEnc==SQLITE_UTF8 );
18682     if( pMem->enc==SQLITE_UTF16LE ){
18683       /* UTF-16 Little-endian -> UTF-8 */
18684       while( zIn<zTerm ){
18685         READ_UTF16LE(zIn, zIn<zTerm, c); 
18686         WRITE_UTF8(z, c);
18687       }
18688     }else{
18689       /* UTF-16 Big-endian -> UTF-8 */
18690       while( zIn<zTerm ){
18691         READ_UTF16BE(zIn, zIn<zTerm, c); 
18692         WRITE_UTF8(z, c);
18693       }
18694     }
18695     pMem->n = (int)(z - zOut);
18696   }
18697   *z = 0;
18698   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
18699
18700   sqlite3VdbeMemRelease(pMem);
18701   pMem->flags &= ~(MEM_Static|MEM_Dyn|MEM_Ephem);
18702   pMem->enc = desiredEnc;
18703   pMem->flags |= (MEM_Term|MEM_Dyn);
18704   pMem->z = (char*)zOut;
18705   pMem->zMalloc = pMem->z;
18706
18707 translate_out:
18708 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
18709   {
18710     char zBuf[100];
18711     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
18712     fprintf(stderr, "OUTPUT: %s\n", zBuf);
18713   }
18714 #endif
18715   return SQLITE_OK;
18716 }
18717
18718 /*
18719 ** This routine checks for a byte-order mark at the beginning of the 
18720 ** UTF-16 string stored in *pMem. If one is present, it is removed and
18721 ** the encoding of the Mem adjusted. This routine does not do any
18722 ** byte-swapping, it just sets Mem.enc appropriately.
18723 **
18724 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
18725 ** changed by this function.
18726 */
18727 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
18728   int rc = SQLITE_OK;
18729   u8 bom = 0;
18730
18731   assert( pMem->n>=0 );
18732   if( pMem->n>1 ){
18733     u8 b1 = *(u8 *)pMem->z;
18734     u8 b2 = *(((u8 *)pMem->z) + 1);
18735     if( b1==0xFE && b2==0xFF ){
18736       bom = SQLITE_UTF16BE;
18737     }
18738     if( b1==0xFF && b2==0xFE ){
18739       bom = SQLITE_UTF16LE;
18740     }
18741   }
18742   
18743   if( bom ){
18744     rc = sqlite3VdbeMemMakeWriteable(pMem);
18745     if( rc==SQLITE_OK ){
18746       pMem->n -= 2;
18747       memmove(pMem->z, &pMem->z[2], pMem->n);
18748       pMem->z[pMem->n] = '\0';
18749       pMem->z[pMem->n+1] = '\0';
18750       pMem->flags |= MEM_Term;
18751       pMem->enc = bom;
18752     }
18753   }
18754   return rc;
18755 }
18756 #endif /* SQLITE_OMIT_UTF16 */
18757
18758 /*
18759 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
18760 ** return the number of unicode characters in pZ up to (but not including)
18761 ** the first 0x00 byte. If nByte is not less than zero, return the
18762 ** number of unicode characters in the first nByte of pZ (or up to 
18763 ** the first 0x00, whichever comes first).
18764 */
18765 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
18766   int r = 0;
18767   const u8 *z = (const u8*)zIn;
18768   const u8 *zTerm;
18769   if( nByte>=0 ){
18770     zTerm = &z[nByte];
18771   }else{
18772     zTerm = (const u8*)(-1);
18773   }
18774   assert( z<=zTerm );
18775   while( *z!=0 && z<zTerm ){
18776     SQLITE_SKIP_UTF8(z);
18777     r++;
18778   }
18779   return r;
18780 }
18781
18782 /* This test function is not currently used by the automated test-suite. 
18783 ** Hence it is only available in debug builds.
18784 */
18785 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
18786 /*
18787 ** Translate UTF-8 to UTF-8.
18788 **
18789 ** This has the effect of making sure that the string is well-formed
18790 ** UTF-8.  Miscoded characters are removed.
18791 **
18792 ** The translation is done in-place (since it is impossible for the
18793 ** correct UTF-8 encoding to be longer than a malformed encoding).
18794 */
18795 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
18796   unsigned char *zOut = zIn;
18797   unsigned char *zStart = zIn;
18798   u32 c;
18799
18800   while( zIn[0] ){
18801     c = sqlite3Utf8Read(zIn, (const u8**)&zIn);
18802     if( c!=0xfffd ){
18803       WRITE_UTF8(zOut, c);
18804     }
18805   }
18806   *zOut = 0;
18807   return (int)(zOut - zStart);
18808 }
18809 #endif
18810
18811 #ifndef SQLITE_OMIT_UTF16
18812 /*
18813 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
18814 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
18815 ** be freed by the calling function.
18816 **
18817 ** NULL is returned if there is an allocation error.
18818 */
18819 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
18820   Mem m;
18821   memset(&m, 0, sizeof(m));
18822   m.db = db;
18823   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
18824   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
18825   if( db->mallocFailed ){
18826     sqlite3VdbeMemRelease(&m);
18827     m.z = 0;
18828   }
18829   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
18830   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
18831   assert( (m.flags & MEM_Dyn)!=0 || db->mallocFailed );
18832   assert( m.z || db->mallocFailed );
18833   return m.z;
18834 }
18835
18836 /*
18837 ** Convert a UTF-8 string to the UTF-16 encoding specified by parameter
18838 ** enc. A pointer to the new string is returned, and the value of *pnOut
18839 ** is set to the length of the returned string in bytes. The call should
18840 ** arrange to call sqlite3DbFree() on the returned pointer when it is
18841 ** no longer required.
18842 ** 
18843 ** If a malloc failure occurs, NULL is returned and the db.mallocFailed
18844 ** flag set.
18845 */
18846 #ifdef SQLITE_ENABLE_STAT2
18847 SQLITE_PRIVATE char *sqlite3Utf8to16(sqlite3 *db, u8 enc, char *z, int n, int *pnOut){
18848   Mem m;
18849   memset(&m, 0, sizeof(m));
18850   m.db = db;
18851   sqlite3VdbeMemSetStr(&m, z, n, SQLITE_UTF8, SQLITE_STATIC);
18852   if( sqlite3VdbeMemTranslate(&m, enc) ){
18853     assert( db->mallocFailed );
18854     return 0;
18855   }
18856   assert( m.z==m.zMalloc );
18857   *pnOut = m.n;
18858   return m.z;
18859 }
18860 #endif
18861
18862 /*
18863 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
18864 ** Return the number of bytes in the first nChar unicode characters
18865 ** in pZ.  nChar must be non-negative.
18866 */
18867 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
18868   int c;
18869   unsigned char const *z = zIn;
18870   int n = 0;
18871   
18872   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
18873     while( n<nChar ){
18874       READ_UTF16BE(z, 1, c);
18875       n++;
18876     }
18877   }else{
18878     while( n<nChar ){
18879       READ_UTF16LE(z, 1, c);
18880       n++;
18881     }
18882   }
18883   return (int)(z-(unsigned char const *)zIn);
18884 }
18885
18886 #if defined(SQLITE_TEST)
18887 /*
18888 ** This routine is called from the TCL test function "translate_selftest".
18889 ** It checks that the primitives for serializing and deserializing
18890 ** characters in each encoding are inverses of each other.
18891 */
18892 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
18893   unsigned int i, t;
18894   unsigned char zBuf[20];
18895   unsigned char *z;
18896   int n;
18897   unsigned int c;
18898
18899   for(i=0; i<0x00110000; i++){
18900     z = zBuf;
18901     WRITE_UTF8(z, i);
18902     n = (int)(z-zBuf);
18903     assert( n>0 && n<=4 );
18904     z[0] = 0;
18905     z = zBuf;
18906     c = sqlite3Utf8Read(z, (const u8**)&z);
18907     t = i;
18908     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
18909     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
18910     assert( c==t );
18911     assert( (z-zBuf)==n );
18912   }
18913   for(i=0; i<0x00110000; i++){
18914     if( i>=0xD800 && i<0xE000 ) continue;
18915     z = zBuf;
18916     WRITE_UTF16LE(z, i);
18917     n = (int)(z-zBuf);
18918     assert( n>0 && n<=4 );
18919     z[0] = 0;
18920     z = zBuf;
18921     READ_UTF16LE(z, 1, c);
18922     assert( c==i );
18923     assert( (z-zBuf)==n );
18924   }
18925   for(i=0; i<0x00110000; i++){
18926     if( i>=0xD800 && i<0xE000 ) continue;
18927     z = zBuf;
18928     WRITE_UTF16BE(z, i);
18929     n = (int)(z-zBuf);
18930     assert( n>0 && n<=4 );
18931     z[0] = 0;
18932     z = zBuf;
18933     READ_UTF16BE(z, 1, c);
18934     assert( c==i );
18935     assert( (z-zBuf)==n );
18936   }
18937 }
18938 #endif /* SQLITE_TEST */
18939 #endif /* SQLITE_OMIT_UTF16 */
18940
18941 /************** End of utf.c *************************************************/
18942 /************** Begin file util.c ********************************************/
18943 /*
18944 ** 2001 September 15
18945 **
18946 ** The author disclaims copyright to this source code.  In place of
18947 ** a legal notice, here is a blessing:
18948 **
18949 **    May you do good and not evil.
18950 **    May you find forgiveness for yourself and forgive others.
18951 **    May you share freely, never taking more than you give.
18952 **
18953 *************************************************************************
18954 ** Utility functions used throughout sqlite.
18955 **
18956 ** This file contains functions for allocating memory, comparing
18957 ** strings, and stuff like that.
18958 **
18959 */
18960 #ifdef SQLITE_HAVE_ISNAN
18961 # include <math.h>
18962 #endif
18963
18964 /*
18965 ** Routine needed to support the testcase() macro.
18966 */
18967 #ifdef SQLITE_COVERAGE_TEST
18968 SQLITE_PRIVATE void sqlite3Coverage(int x){
18969   static int dummy = 0;
18970   dummy += x;
18971 }
18972 #endif
18973
18974 #ifndef SQLITE_OMIT_FLOATING_POINT
18975 /*
18976 ** Return true if the floating point value is Not a Number (NaN).
18977 **
18978 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
18979 ** Otherwise, we have our own implementation that works on most systems.
18980 */
18981 SQLITE_PRIVATE int sqlite3IsNaN(double x){
18982   int rc;   /* The value return */
18983 #if !defined(SQLITE_HAVE_ISNAN)
18984   /*
18985   ** Systems that support the isnan() library function should probably
18986   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
18987   ** found that many systems do not have a working isnan() function so
18988   ** this implementation is provided as an alternative.
18989   **
18990   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
18991   ** On the other hand, the use of -ffast-math comes with the following
18992   ** warning:
18993   **
18994   **      This option [-ffast-math] should never be turned on by any
18995   **      -O option since it can result in incorrect output for programs
18996   **      which depend on an exact implementation of IEEE or ISO 
18997   **      rules/specifications for math functions.
18998   **
18999   ** Under MSVC, this NaN test may fail if compiled with a floating-
19000   ** point precision mode other than /fp:precise.  From the MSDN 
19001   ** documentation:
19002   **
19003   **      The compiler [with /fp:precise] will properly handle comparisons 
19004   **      involving NaN. For example, x != x evaluates to true if x is NaN 
19005   **      ...
19006   */
19007 #ifdef __FAST_MATH__
19008 # error SQLite will not work correctly with the -ffast-math option of GCC.
19009 #endif
19010   volatile double y = x;
19011   volatile double z = y;
19012   rc = (y!=z);
19013 #else  /* if defined(SQLITE_HAVE_ISNAN) */
19014   rc = isnan(x);
19015 #endif /* SQLITE_HAVE_ISNAN */
19016   testcase( rc );
19017   return rc;
19018 }
19019 #endif /* SQLITE_OMIT_FLOATING_POINT */
19020
19021 /*
19022 ** Compute a string length that is limited to what can be stored in
19023 ** lower 30 bits of a 32-bit signed integer.
19024 **
19025 ** The value returned will never be negative.  Nor will it ever be greater
19026 ** than the actual length of the string.  For very long strings (greater
19027 ** than 1GiB) the value returned might be less than the true string length.
19028 */
19029 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
19030   const char *z2 = z;
19031   if( z==0 ) return 0;
19032   while( *z2 ){ z2++; }
19033   return 0x3fffffff & (int)(z2 - z);
19034 }
19035
19036 /*
19037 ** Set the most recent error code and error string for the sqlite
19038 ** handle "db". The error code is set to "err_code".
19039 **
19040 ** If it is not NULL, string zFormat specifies the format of the
19041 ** error string in the style of the printf functions: The following
19042 ** format characters are allowed:
19043 **
19044 **      %s      Insert a string
19045 **      %z      A string that should be freed after use
19046 **      %d      Insert an integer
19047 **      %T      Insert a token
19048 **      %S      Insert the first element of a SrcList
19049 **
19050 ** zFormat and any string tokens that follow it are assumed to be
19051 ** encoded in UTF-8.
19052 **
19053 ** To clear the most recent error for sqlite handle "db", sqlite3Error
19054 ** should be called with err_code set to SQLITE_OK and zFormat set
19055 ** to NULL.
19056 */
19057 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code, const char *zFormat, ...){
19058   if( db && (db->pErr || (db->pErr = sqlite3ValueNew(db))!=0) ){
19059     db->errCode = err_code;
19060     if( zFormat ){
19061       char *z;
19062       va_list ap;
19063       va_start(ap, zFormat);
19064       z = sqlite3VMPrintf(db, zFormat, ap);
19065       va_end(ap);
19066       sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
19067     }else{
19068       sqlite3ValueSetStr(db->pErr, 0, 0, SQLITE_UTF8, SQLITE_STATIC);
19069     }
19070   }
19071 }
19072
19073 /*
19074 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
19075 ** The following formatting characters are allowed:
19076 **
19077 **      %s      Insert a string
19078 **      %z      A string that should be freed after use
19079 **      %d      Insert an integer
19080 **      %T      Insert a token
19081 **      %S      Insert the first element of a SrcList
19082 **
19083 ** This function should be used to report any error that occurs whilst
19084 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
19085 ** last thing the sqlite3_prepare() function does is copy the error
19086 ** stored by this function into the database handle using sqlite3Error().
19087 ** Function sqlite3Error() should be used during statement execution
19088 ** (sqlite3_step() etc.).
19089 */
19090 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
19091   char *zMsg;
19092   va_list ap;
19093   sqlite3 *db = pParse->db;
19094   va_start(ap, zFormat);
19095   zMsg = sqlite3VMPrintf(db, zFormat, ap);
19096   va_end(ap);
19097   if( db->suppressErr ){
19098     sqlite3DbFree(db, zMsg);
19099   }else{
19100     pParse->nErr++;
19101     sqlite3DbFree(db, pParse->zErrMsg);
19102     pParse->zErrMsg = zMsg;
19103     pParse->rc = SQLITE_ERROR;
19104   }
19105 }
19106
19107 /*
19108 ** Convert an SQL-style quoted string into a normal string by removing
19109 ** the quote characters.  The conversion is done in-place.  If the
19110 ** input does not begin with a quote character, then this routine
19111 ** is a no-op.
19112 **
19113 ** The input string must be zero-terminated.  A new zero-terminator
19114 ** is added to the dequoted string.
19115 **
19116 ** The return value is -1 if no dequoting occurs or the length of the
19117 ** dequoted string, exclusive of the zero terminator, if dequoting does
19118 ** occur.
19119 **
19120 ** 2002-Feb-14: This routine is extended to remove MS-Access style
19121 ** brackets from around identifers.  For example:  "[a-b-c]" becomes
19122 ** "a-b-c".
19123 */
19124 SQLITE_PRIVATE int sqlite3Dequote(char *z){
19125   char quote;
19126   int i, j;
19127   if( z==0 ) return -1;
19128   quote = z[0];
19129   switch( quote ){
19130     case '\'':  break;
19131     case '"':   break;
19132     case '`':   break;                /* For MySQL compatibility */
19133     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
19134     default:    return -1;
19135   }
19136   for(i=1, j=0; ALWAYS(z[i]); i++){
19137     if( z[i]==quote ){
19138       if( z[i+1]==quote ){
19139         z[j++] = quote;
19140         i++;
19141       }else{
19142         break;
19143       }
19144     }else{
19145       z[j++] = z[i];
19146     }
19147   }
19148   z[j] = 0;
19149   return j;
19150 }
19151
19152 /* Convenient short-hand */
19153 #define UpperToLower sqlite3UpperToLower
19154
19155 /*
19156 ** Some systems have stricmp().  Others have strcasecmp().  Because
19157 ** there is no consistency, we will define our own.
19158 */
19159 SQLITE_PRIVATE int sqlite3StrICmp(const char *zLeft, const char *zRight){
19160   register unsigned char *a, *b;
19161   a = (unsigned char *)zLeft;
19162   b = (unsigned char *)zRight;
19163   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
19164   return UpperToLower[*a] - UpperToLower[*b];
19165 }
19166 SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
19167   register unsigned char *a, *b;
19168   a = (unsigned char *)zLeft;
19169   b = (unsigned char *)zRight;
19170   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
19171   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
19172 }
19173
19174 /*
19175 ** Return TRUE if z is a pure numeric string.  Return FALSE and leave
19176 ** *realnum unchanged if the string contains any character which is not
19177 ** part of a number.
19178 **
19179 ** If the string is pure numeric, set *realnum to TRUE if the string
19180 ** contains the '.' character or an "E+000" style exponentiation suffix.
19181 ** Otherwise set *realnum to FALSE.  Note that just becaue *realnum is
19182 ** false does not mean that the number can be successfully converted into
19183 ** an integer - it might be too big.
19184 **
19185 ** An empty string is considered non-numeric.
19186 */
19187 SQLITE_PRIVATE int sqlite3IsNumber(const char *z, int *realnum, u8 enc){
19188   int incr = (enc==SQLITE_UTF8?1:2);
19189   if( enc==SQLITE_UTF16BE ) z++;
19190   if( *z=='-' || *z=='+' ) z += incr;
19191   if( !sqlite3Isdigit(*z) ){
19192     return 0;
19193   }
19194   z += incr;
19195   *realnum = 0;
19196   while( sqlite3Isdigit(*z) ){ z += incr; }
19197 #ifndef SQLITE_OMIT_FLOATING_POINT
19198   if( *z=='.' ){
19199     z += incr;
19200     if( !sqlite3Isdigit(*z) ) return 0;
19201     while( sqlite3Isdigit(*z) ){ z += incr; }
19202     *realnum = 1;
19203   }
19204   if( *z=='e' || *z=='E' ){
19205     z += incr;
19206     if( *z=='+' || *z=='-' ) z += incr;
19207     if( !sqlite3Isdigit(*z) ) return 0;
19208     while( sqlite3Isdigit(*z) ){ z += incr; }
19209     *realnum = 1;
19210   }
19211 #endif
19212   return *z==0;
19213 }
19214
19215 /*
19216 ** The string z[] is an ASCII representation of a real number.
19217 ** Convert this string to a double.
19218 **
19219 ** This routine assumes that z[] really is a valid number.  If it
19220 ** is not, the result is undefined.
19221 **
19222 ** This routine is used instead of the library atof() function because
19223 ** the library atof() might want to use "," as the decimal point instead
19224 ** of "." depending on how locale is set.  But that would cause problems
19225 ** for SQL.  So this routine always uses "." regardless of locale.
19226 */
19227 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult){
19228 #ifndef SQLITE_OMIT_FLOATING_POINT
19229   const char *zBegin = z;
19230   /* sign * significand * (10 ^ (esign * exponent)) */
19231   int sign = 1;   /* sign of significand */
19232   i64 s = 0;      /* significand */
19233   int d = 0;      /* adjust exponent for shifting decimal point */
19234   int esign = 1;  /* sign of exponent */
19235   int e = 0;      /* exponent */
19236   double result;
19237   int nDigits = 0;
19238
19239   /* skip leading spaces */
19240   while( sqlite3Isspace(*z) ) z++;
19241   /* get sign of significand */
19242   if( *z=='-' ){
19243     sign = -1;
19244     z++;
19245   }else if( *z=='+' ){
19246     z++;
19247   }
19248   /* skip leading zeroes */
19249   while( z[0]=='0' ) z++, nDigits++;
19250
19251   /* copy max significant digits to significand */
19252   while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
19253     s = s*10 + (*z - '0');
19254     z++, nDigits++;
19255   }
19256   /* skip non-significant significand digits
19257   ** (increase exponent by d to shift decimal left) */
19258   while( sqlite3Isdigit(*z) ) z++, nDigits++, d++;
19259
19260   /* if decimal point is present */
19261   if( *z=='.' ){
19262     z++;
19263     /* copy digits from after decimal to significand
19264     ** (decrease exponent by d to shift decimal right) */
19265     while( sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
19266       s = s*10 + (*z - '0');
19267       z++, nDigits++, d--;
19268     }
19269     /* skip non-significant digits */
19270     while( sqlite3Isdigit(*z) ) z++, nDigits++;
19271   }
19272
19273   /* if exponent is present */
19274   if( *z=='e' || *z=='E' ){
19275     z++;
19276     /* get sign of exponent */
19277     if( *z=='-' ){
19278       esign = -1;
19279       z++;
19280     }else if( *z=='+' ){
19281       z++;
19282     }
19283     /* copy digits to exponent */
19284     while( sqlite3Isdigit(*z) ){
19285       e = e*10 + (*z - '0');
19286       z++;
19287     }
19288   }
19289
19290   /* adjust exponent by d, and update sign */
19291   e = (e*esign) + d;
19292   if( e<0 ) {
19293     esign = -1;
19294     e *= -1;
19295   } else {
19296     esign = 1;
19297   }
19298
19299   /* if 0 significand */
19300   if( !s ) {
19301     /* In the IEEE 754 standard, zero is signed.
19302     ** Add the sign if we've seen at least one digit */
19303     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
19304   } else {
19305     /* attempt to reduce exponent */
19306     if( esign>0 ){
19307       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
19308     }else{
19309       while( !(s%10) && e>0 ) e--,s/=10;
19310     }
19311
19312     /* adjust the sign of significand */
19313     s = sign<0 ? -s : s;
19314
19315     /* if exponent, scale significand as appropriate
19316     ** and store in result. */
19317     if( e ){
19318       double scale = 1.0;
19319       /* attempt to handle extremely small/large numbers better */
19320       if( e>307 && e<342 ){
19321         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
19322         if( esign<0 ){
19323           result = s / scale;
19324           result /= 1.0e+308;
19325         }else{
19326           result = s * scale;
19327           result *= 1.0e+308;
19328         }
19329       }else{
19330         /* 1.0e+22 is the largest power of 10 than can be 
19331         ** represented exactly. */
19332         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
19333         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
19334         if( esign<0 ){
19335           result = s / scale;
19336         }else{
19337           result = s * scale;
19338         }
19339       }
19340     } else {
19341       result = (double)s;
19342     }
19343   }
19344
19345   /* store the result */
19346   *pResult = result;
19347
19348   /* return number of characters used */
19349   return (int)(z - zBegin);
19350 #else
19351   return sqlite3Atoi64(z, pResult);
19352 #endif /* SQLITE_OMIT_FLOATING_POINT */
19353 }
19354
19355 /*
19356 ** Compare the 19-character string zNum against the text representation
19357 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
19358 ** if zNum is less than, equal to, or greater than the string.
19359 **
19360 ** Unlike memcmp() this routine is guaranteed to return the difference
19361 ** in the values of the last digit if the only difference is in the
19362 ** last digit.  So, for example,
19363 **
19364 **      compare2pow63("9223372036854775800")
19365 **
19366 ** will return -8.
19367 */
19368 static int compare2pow63(const char *zNum){
19369   int c;
19370   c = memcmp(zNum,"922337203685477580",18)*10;
19371   if( c==0 ){
19372     c = zNum[18] - '8';
19373     testcase( c==(-1) );
19374     testcase( c==0 );
19375     testcase( c==(+1) );
19376   }
19377   return c;
19378 }
19379
19380
19381 /*
19382 ** Return TRUE if zNum is a 64-bit signed integer and write
19383 ** the value of the integer into *pNum.  If zNum is not an integer
19384 ** or is an integer that is too large to be expressed with 64 bits,
19385 ** then return false.
19386 **
19387 ** When this routine was originally written it dealt with only
19388 ** 32-bit numbers.  At that time, it was much faster than the
19389 ** atoi() library routine in RedHat 7.2.
19390 */
19391 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum){
19392   i64 v = 0;
19393   int neg;
19394   int i, c;
19395   const char *zStart;
19396   while( sqlite3Isspace(*zNum) ) zNum++;
19397   if( *zNum=='-' ){
19398     neg = 1;
19399     zNum++;
19400   }else if( *zNum=='+' ){
19401     neg = 0;
19402     zNum++;
19403   }else{
19404     neg = 0;
19405   }
19406   zStart = zNum;
19407   while( zNum[0]=='0' ){ zNum++; } /* Skip over leading zeros. Ticket #2454 */
19408   for(i=0; (c=zNum[i])>='0' && c<='9'; i++){
19409     v = v*10 + c - '0';
19410   }
19411   *pNum = neg ? -v : v;
19412   testcase( i==18 );
19413   testcase( i==19 );
19414   testcase( i==20 );
19415   if( c!=0 || (i==0 && zStart==zNum) || i>19 ){
19416     /* zNum is empty or contains non-numeric text or is longer
19417     ** than 19 digits (thus guaranting that it is too large) */
19418     return 0;
19419   }else if( i<19 ){
19420     /* Less than 19 digits, so we know that it fits in 64 bits */
19421     return 1;
19422   }else{
19423     /* 19-digit numbers must be no larger than 9223372036854775807 if positive
19424     ** or 9223372036854775808 if negative.  Note that 9223372036854665808
19425     ** is 2^63. */
19426     return compare2pow63(zNum)<neg;
19427   }
19428 }
19429
19430 /*
19431 ** The string zNum represents an unsigned integer.  The zNum string
19432 ** consists of one or more digit characters and is terminated by
19433 ** a zero character.  Any stray characters in zNum result in undefined
19434 ** behavior.
19435 **
19436 ** If the unsigned integer that zNum represents will fit in a
19437 ** 64-bit signed integer, return TRUE.  Otherwise return FALSE.
19438 **
19439 ** If the negFlag parameter is true, that means that zNum really represents
19440 ** a negative number.  (The leading "-" is omitted from zNum.)  This
19441 ** parameter is needed to determine a boundary case.  A string
19442 ** of "9223373036854775808" returns false if negFlag is false or true
19443 ** if negFlag is true.
19444 **
19445 ** Leading zeros are ignored.
19446 */
19447 SQLITE_PRIVATE int sqlite3FitsIn64Bits(const char *zNum, int negFlag){
19448   int i;
19449   int neg = 0;
19450
19451   assert( zNum[0]>='0' && zNum[0]<='9' ); /* zNum is an unsigned number */
19452
19453   if( negFlag ) neg = 1-neg;
19454   while( *zNum=='0' ){
19455     zNum++;   /* Skip leading zeros.  Ticket #2454 */
19456   }
19457   for(i=0; zNum[i]; i++){ assert( zNum[i]>='0' && zNum[i]<='9' ); }
19458   testcase( i==18 );
19459   testcase( i==19 );
19460   testcase( i==20 );
19461   if( i<19 ){
19462     /* Guaranteed to fit if less than 19 digits */
19463     return 1;
19464   }else if( i>19 ){
19465     /* Guaranteed to be too big if greater than 19 digits */
19466     return 0;
19467   }else{
19468     /* Compare against 2^63. */
19469     return compare2pow63(zNum)<neg;
19470   }
19471 }
19472
19473 /*
19474 ** If zNum represents an integer that will fit in 32-bits, then set
19475 ** *pValue to that integer and return true.  Otherwise return false.
19476 **
19477 ** Any non-numeric characters that following zNum are ignored.
19478 ** This is different from sqlite3Atoi64() which requires the
19479 ** input number to be zero-terminated.
19480 */
19481 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
19482   sqlite_int64 v = 0;
19483   int i, c;
19484   int neg = 0;
19485   if( zNum[0]=='-' ){
19486     neg = 1;
19487     zNum++;
19488   }else if( zNum[0]=='+' ){
19489     zNum++;
19490   }
19491   while( zNum[0]=='0' ) zNum++;
19492   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
19493     v = v*10 + c;
19494   }
19495
19496   /* The longest decimal representation of a 32 bit integer is 10 digits:
19497   **
19498   **             1234567890
19499   **     2^31 -> 2147483648
19500   */
19501   testcase( i==10 );
19502   if( i>10 ){
19503     return 0;
19504   }
19505   testcase( v-neg==2147483647 );
19506   if( v-neg>2147483647 ){
19507     return 0;
19508   }
19509   if( neg ){
19510     v = -v;
19511   }
19512   *pValue = (int)v;
19513   return 1;
19514 }
19515
19516 /*
19517 ** The variable-length integer encoding is as follows:
19518 **
19519 ** KEY:
19520 **         A = 0xxxxxxx    7 bits of data and one flag bit
19521 **         B = 1xxxxxxx    7 bits of data and one flag bit
19522 **         C = xxxxxxxx    8 bits of data
19523 **
19524 **  7 bits - A
19525 ** 14 bits - BA
19526 ** 21 bits - BBA
19527 ** 28 bits - BBBA
19528 ** 35 bits - BBBBA
19529 ** 42 bits - BBBBBA
19530 ** 49 bits - BBBBBBA
19531 ** 56 bits - BBBBBBBA
19532 ** 64 bits - BBBBBBBBC
19533 */
19534
19535 /*
19536 ** Write a 64-bit variable-length integer to memory starting at p[0].
19537 ** The length of data write will be between 1 and 9 bytes.  The number
19538 ** of bytes written is returned.
19539 **
19540 ** A variable-length integer consists of the lower 7 bits of each byte
19541 ** for all bytes that have the 8th bit set and one byte with the 8th
19542 ** bit clear.  Except, if we get to the 9th byte, it stores the full
19543 ** 8 bits and is the last byte.
19544 */
19545 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
19546   int i, j, n;
19547   u8 buf[10];
19548   if( v & (((u64)0xff000000)<<32) ){
19549     p[8] = (u8)v;
19550     v >>= 8;
19551     for(i=7; i>=0; i--){
19552       p[i] = (u8)((v & 0x7f) | 0x80);
19553       v >>= 7;
19554     }
19555     return 9;
19556   }    
19557   n = 0;
19558   do{
19559     buf[n++] = (u8)((v & 0x7f) | 0x80);
19560     v >>= 7;
19561   }while( v!=0 );
19562   buf[0] &= 0x7f;
19563   assert( n<=9 );
19564   for(i=0, j=n-1; j>=0; j--, i++){
19565     p[i] = buf[j];
19566   }
19567   return n;
19568 }
19569
19570 /*
19571 ** This routine is a faster version of sqlite3PutVarint() that only
19572 ** works for 32-bit positive integers and which is optimized for
19573 ** the common case of small integers.  A MACRO version, putVarint32,
19574 ** is provided which inlines the single-byte case.  All code should use
19575 ** the MACRO version as this function assumes the single-byte case has
19576 ** already been handled.
19577 */
19578 SQLITE_PRIVATE int sqlite3PutVarint32(unsigned char *p, u32 v){
19579 #ifndef putVarint32
19580   if( (v & ~0x7f)==0 ){
19581     p[0] = v;
19582     return 1;
19583   }
19584 #endif
19585   if( (v & ~0x3fff)==0 ){
19586     p[0] = (u8)((v>>7) | 0x80);
19587     p[1] = (u8)(v & 0x7f);
19588     return 2;
19589   }
19590   return sqlite3PutVarint(p, v);
19591 }
19592
19593 /*
19594 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
19595 ** are defined here rather than simply putting the constant expressions
19596 ** inline in order to work around bugs in the RVT compiler.
19597 **
19598 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
19599 **
19600 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
19601 */
19602 #define SLOT_2_0     0x001fc07f
19603 #define SLOT_4_2_0   0xf01fc07f
19604
19605
19606 /*
19607 ** Read a 64-bit variable-length integer from memory starting at p[0].
19608 ** Return the number of bytes read.  The value is stored in *v.
19609 */
19610 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
19611   u32 a,b,s;
19612
19613   a = *p;
19614   /* a: p0 (unmasked) */
19615   if (!(a&0x80))
19616   {
19617     *v = a;
19618     return 1;
19619   }
19620
19621   p++;
19622   b = *p;
19623   /* b: p1 (unmasked) */
19624   if (!(b&0x80))
19625   {
19626     a &= 0x7f;
19627     a = a<<7;
19628     a |= b;
19629     *v = a;
19630     return 2;
19631   }
19632
19633   /* Verify that constants are precomputed correctly */
19634   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
19635   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
19636
19637   p++;
19638   a = a<<14;
19639   a |= *p;
19640   /* a: p0<<14 | p2 (unmasked) */
19641   if (!(a&0x80))
19642   {
19643     a &= SLOT_2_0;
19644     b &= 0x7f;
19645     b = b<<7;
19646     a |= b;
19647     *v = a;
19648     return 3;
19649   }
19650
19651   /* CSE1 from below */
19652   a &= SLOT_2_0;
19653   p++;
19654   b = b<<14;
19655   b |= *p;
19656   /* b: p1<<14 | p3 (unmasked) */
19657   if (!(b&0x80))
19658   {
19659     b &= SLOT_2_0;
19660     /* moved CSE1 up */
19661     /* a &= (0x7f<<14)|(0x7f); */
19662     a = a<<7;
19663     a |= b;
19664     *v = a;
19665     return 4;
19666   }
19667
19668   /* a: p0<<14 | p2 (masked) */
19669   /* b: p1<<14 | p3 (unmasked) */
19670   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19671   /* moved CSE1 up */
19672   /* a &= (0x7f<<14)|(0x7f); */
19673   b &= SLOT_2_0;
19674   s = a;
19675   /* s: p0<<14 | p2 (masked) */
19676
19677   p++;
19678   a = a<<14;
19679   a |= *p;
19680   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
19681   if (!(a&0x80))
19682   {
19683     /* we can skip these cause they were (effectively) done above in calc'ing s */
19684     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
19685     /* b &= (0x7f<<14)|(0x7f); */
19686     b = b<<7;
19687     a |= b;
19688     s = s>>18;
19689     *v = ((u64)s)<<32 | a;
19690     return 5;
19691   }
19692
19693   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19694   s = s<<7;
19695   s |= b;
19696   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
19697
19698   p++;
19699   b = b<<14;
19700   b |= *p;
19701   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
19702   if (!(b&0x80))
19703   {
19704     /* we can skip this cause it was (effectively) done above in calc'ing s */
19705     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
19706     a &= SLOT_2_0;
19707     a = a<<7;
19708     a |= b;
19709     s = s>>18;
19710     *v = ((u64)s)<<32 | a;
19711     return 6;
19712   }
19713
19714   p++;
19715   a = a<<14;
19716   a |= *p;
19717   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
19718   if (!(a&0x80))
19719   {
19720     a &= SLOT_4_2_0;
19721     b &= SLOT_2_0;
19722     b = b<<7;
19723     a |= b;
19724     s = s>>11;
19725     *v = ((u64)s)<<32 | a;
19726     return 7;
19727   }
19728
19729   /* CSE2 from below */
19730   a &= SLOT_2_0;
19731   p++;
19732   b = b<<14;
19733   b |= *p;
19734   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
19735   if (!(b&0x80))
19736   {
19737     b &= SLOT_4_2_0;
19738     /* moved CSE2 up */
19739     /* a &= (0x7f<<14)|(0x7f); */
19740     a = a<<7;
19741     a |= b;
19742     s = s>>4;
19743     *v = ((u64)s)<<32 | a;
19744     return 8;
19745   }
19746
19747   p++;
19748   a = a<<15;
19749   a |= *p;
19750   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
19751
19752   /* moved CSE2 up */
19753   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
19754   b &= SLOT_2_0;
19755   b = b<<8;
19756   a |= b;
19757
19758   s = s<<4;
19759   b = p[-4];
19760   b &= 0x7f;
19761   b = b>>3;
19762   s |= b;
19763
19764   *v = ((u64)s)<<32 | a;
19765
19766   return 9;
19767 }
19768
19769 /*
19770 ** Read a 32-bit variable-length integer from memory starting at p[0].
19771 ** Return the number of bytes read.  The value is stored in *v.
19772 **
19773 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
19774 ** integer, then set *v to 0xffffffff.
19775 **
19776 ** A MACRO version, getVarint32, is provided which inlines the 
19777 ** single-byte case.  All code should use the MACRO version as 
19778 ** this function assumes the single-byte case has already been handled.
19779 */
19780 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
19781   u32 a,b;
19782
19783   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
19784   ** by the getVarin32() macro */
19785   a = *p;
19786   /* a: p0 (unmasked) */
19787 #ifndef getVarint32
19788   if (!(a&0x80))
19789   {
19790     /* Values between 0 and 127 */
19791     *v = a;
19792     return 1;
19793   }
19794 #endif
19795
19796   /* The 2-byte case */
19797   p++;
19798   b = *p;
19799   /* b: p1 (unmasked) */
19800   if (!(b&0x80))
19801   {
19802     /* Values between 128 and 16383 */
19803     a &= 0x7f;
19804     a = a<<7;
19805     *v = a | b;
19806     return 2;
19807   }
19808
19809   /* The 3-byte case */
19810   p++;
19811   a = a<<14;
19812   a |= *p;
19813   /* a: p0<<14 | p2 (unmasked) */
19814   if (!(a&0x80))
19815   {
19816     /* Values between 16384 and 2097151 */
19817     a &= (0x7f<<14)|(0x7f);
19818     b &= 0x7f;
19819     b = b<<7;
19820     *v = a | b;
19821     return 3;
19822   }
19823
19824   /* A 32-bit varint is used to store size information in btrees.
19825   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
19826   ** A 3-byte varint is sufficient, for example, to record the size
19827   ** of a 1048569-byte BLOB or string.
19828   **
19829   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
19830   ** rare larger cases can be handled by the slower 64-bit varint
19831   ** routine.
19832   */
19833 #if 1
19834   {
19835     u64 v64;
19836     u8 n;
19837
19838     p -= 2;
19839     n = sqlite3GetVarint(p, &v64);
19840     assert( n>3 && n<=9 );
19841     if( (v64 & SQLITE_MAX_U32)!=v64 ){
19842       *v = 0xffffffff;
19843     }else{
19844       *v = (u32)v64;
19845     }
19846     return n;
19847   }
19848
19849 #else
19850   /* For following code (kept for historical record only) shows an
19851   ** unrolling for the 3- and 4-byte varint cases.  This code is
19852   ** slightly faster, but it is also larger and much harder to test.
19853   */
19854   p++;
19855   b = b<<14;
19856   b |= *p;
19857   /* b: p1<<14 | p3 (unmasked) */
19858   if (!(b&0x80))
19859   {
19860     /* Values between 2097152 and 268435455 */
19861     b &= (0x7f<<14)|(0x7f);
19862     a &= (0x7f<<14)|(0x7f);
19863     a = a<<7;
19864     *v = a | b;
19865     return 4;
19866   }
19867
19868   p++;
19869   a = a<<14;
19870   a |= *p;
19871   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
19872   if (!(a&0x80))
19873   {
19874     /* Values  between 268435456 and 34359738367 */
19875     a &= SLOT_4_2_0;
19876     b &= SLOT_4_2_0;
19877     b = b<<7;
19878     *v = a | b;
19879     return 5;
19880   }
19881
19882   /* We can only reach this point when reading a corrupt database
19883   ** file.  In that case we are not in any hurry.  Use the (relatively
19884   ** slow) general-purpose sqlite3GetVarint() routine to extract the
19885   ** value. */
19886   {
19887     u64 v64;
19888     u8 n;
19889
19890     p -= 4;
19891     n = sqlite3GetVarint(p, &v64);
19892     assert( n>5 && n<=9 );
19893     *v = (u32)v64;
19894     return n;
19895   }
19896 #endif
19897 }
19898
19899 /*
19900 ** Return the number of bytes that will be needed to store the given
19901 ** 64-bit integer.
19902 */
19903 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
19904   int i = 0;
19905   do{
19906     i++;
19907     v >>= 7;
19908   }while( v!=0 && ALWAYS(i<9) );
19909   return i;
19910 }
19911
19912
19913 /*
19914 ** Read or write a four-byte big-endian integer value.
19915 */
19916 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
19917   return (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
19918 }
19919 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
19920   p[0] = (u8)(v>>24);
19921   p[1] = (u8)(v>>16);
19922   p[2] = (u8)(v>>8);
19923   p[3] = (u8)v;
19924 }
19925
19926
19927
19928 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
19929 /*
19930 ** Translate a single byte of Hex into an integer.
19931 ** This routine only works if h really is a valid hexadecimal
19932 ** character:  0..9a..fA..F
19933 */
19934 static u8 hexToInt(int h){
19935   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
19936 #ifdef SQLITE_ASCII
19937   h += 9*(1&(h>>6));
19938 #endif
19939 #ifdef SQLITE_EBCDIC
19940   h += 9*(1&~(h>>4));
19941 #endif
19942   return (u8)(h & 0xf);
19943 }
19944 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
19945
19946 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
19947 /*
19948 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
19949 ** value.  Return a pointer to its binary value.  Space to hold the
19950 ** binary value has been obtained from malloc and must be freed by
19951 ** the calling routine.
19952 */
19953 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
19954   char *zBlob;
19955   int i;
19956
19957   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
19958   n--;
19959   if( zBlob ){
19960     for(i=0; i<n; i+=2){
19961       zBlob[i/2] = (hexToInt(z[i])<<4) | hexToInt(z[i+1]);
19962     }
19963     zBlob[i/2] = 0;
19964   }
19965   return zBlob;
19966 }
19967 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
19968
19969 /*
19970 ** Log an error that is an API call on a connection pointer that should
19971 ** not have been used.  The "type" of connection pointer is given as the
19972 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
19973 */
19974 static void logBadConnection(const char *zType){
19975   sqlite3_log(SQLITE_MISUSE, 
19976      "API call with %s database connection pointer",
19977      zType
19978   );
19979 }
19980
19981 /*
19982 ** Check to make sure we have a valid db pointer.  This test is not
19983 ** foolproof but it does provide some measure of protection against
19984 ** misuse of the interface such as passing in db pointers that are
19985 ** NULL or which have been previously closed.  If this routine returns
19986 ** 1 it means that the db pointer is valid and 0 if it should not be
19987 ** dereferenced for any reason.  The calling function should invoke
19988 ** SQLITE_MISUSE immediately.
19989 **
19990 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
19991 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
19992 ** open properly and is not fit for general use but which can be
19993 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
19994 */
19995 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
19996   u32 magic;
19997   if( db==0 ){
19998     logBadConnection("NULL");
19999     return 0;
20000   }
20001   magic = db->magic;
20002   if( magic!=SQLITE_MAGIC_OPEN ){
20003     if( sqlite3SafetyCheckSickOrOk(db) ){
20004       testcase( sqlite3GlobalConfig.xLog!=0 );
20005       logBadConnection("unopened");
20006     }
20007     return 0;
20008   }else{
20009     return 1;
20010   }
20011 }
20012 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
20013   u32 magic;
20014   magic = db->magic;
20015   if( magic!=SQLITE_MAGIC_SICK &&
20016       magic!=SQLITE_MAGIC_OPEN &&
20017       magic!=SQLITE_MAGIC_BUSY ){
20018     testcase( sqlite3GlobalConfig.xLog!=0 );
20019     logBadConnection("invalid");
20020     return 0;
20021   }else{
20022     return 1;
20023   }
20024 }
20025
20026 /************** End of util.c ************************************************/
20027 /************** Begin file hash.c ********************************************/
20028 /*
20029 ** 2001 September 22
20030 **
20031 ** The author disclaims copyright to this source code.  In place of
20032 ** a legal notice, here is a blessing:
20033 **
20034 **    May you do good and not evil.
20035 **    May you find forgiveness for yourself and forgive others.
20036 **    May you share freely, never taking more than you give.
20037 **
20038 *************************************************************************
20039 ** This is the implementation of generic hash-tables
20040 ** used in SQLite.
20041 */
20042
20043 /* Turn bulk memory into a hash table object by initializing the
20044 ** fields of the Hash structure.
20045 **
20046 ** "pNew" is a pointer to the hash table that is to be initialized.
20047 */
20048 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
20049   assert( pNew!=0 );
20050   pNew->first = 0;
20051   pNew->count = 0;
20052   pNew->htsize = 0;
20053   pNew->ht = 0;
20054 }
20055
20056 /* Remove all entries from a hash table.  Reclaim all memory.
20057 ** Call this routine to delete a hash table or to reset a hash table
20058 ** to the empty state.
20059 */
20060 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
20061   HashElem *elem;         /* For looping over all elements of the table */
20062
20063   assert( pH!=0 );
20064   elem = pH->first;
20065   pH->first = 0;
20066   sqlite3_free(pH->ht);
20067   pH->ht = 0;
20068   pH->htsize = 0;
20069   while( elem ){
20070     HashElem *next_elem = elem->next;
20071     sqlite3_free(elem);
20072     elem = next_elem;
20073   }
20074   pH->count = 0;
20075 }
20076
20077 /*
20078 ** The hashing function.
20079 */
20080 static unsigned int strHash(const char *z, int nKey){
20081   int h = 0;
20082   assert( nKey>=0 );
20083   while( nKey > 0  ){
20084     h = (h<<3) ^ h ^ sqlite3UpperToLower[(unsigned char)*z++];
20085     nKey--;
20086   }
20087   return h;
20088 }
20089
20090
20091 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
20092 ** insert pNew into the pEntry hash bucket.
20093 */
20094 static void insertElement(
20095   Hash *pH,              /* The complete hash table */
20096   struct _ht *pEntry,    /* The entry into which pNew is inserted */
20097   HashElem *pNew         /* The element to be inserted */
20098 ){
20099   HashElem *pHead;       /* First element already in pEntry */
20100   if( pEntry ){
20101     pHead = pEntry->count ? pEntry->chain : 0;
20102     pEntry->count++;
20103     pEntry->chain = pNew;
20104   }else{
20105     pHead = 0;
20106   }
20107   if( pHead ){
20108     pNew->next = pHead;
20109     pNew->prev = pHead->prev;
20110     if( pHead->prev ){ pHead->prev->next = pNew; }
20111     else             { pH->first = pNew; }
20112     pHead->prev = pNew;
20113   }else{
20114     pNew->next = pH->first;
20115     if( pH->first ){ pH->first->prev = pNew; }
20116     pNew->prev = 0;
20117     pH->first = pNew;
20118   }
20119 }
20120
20121
20122 /* Resize the hash table so that it cantains "new_size" buckets.
20123 **
20124 ** The hash table might fail to resize if sqlite3_malloc() fails or
20125 ** if the new size is the same as the prior size.
20126 ** Return TRUE if the resize occurs and false if not.
20127 */
20128 static int rehash(Hash *pH, unsigned int new_size){
20129   struct _ht *new_ht;            /* The new hash table */
20130   HashElem *elem, *next_elem;    /* For looping over existing elements */
20131
20132 #if SQLITE_MALLOC_SOFT_LIMIT>0
20133   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
20134     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
20135   }
20136   if( new_size==pH->htsize ) return 0;
20137 #endif
20138
20139   /* The inability to allocates space for a larger hash table is
20140   ** a performance hit but it is not a fatal error.  So mark the
20141   ** allocation as a benign.
20142   */
20143   sqlite3BeginBenignMalloc();
20144   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
20145   sqlite3EndBenignMalloc();
20146
20147   if( new_ht==0 ) return 0;
20148   sqlite3_free(pH->ht);
20149   pH->ht = new_ht;
20150   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
20151   memset(new_ht, 0, new_size*sizeof(struct _ht));
20152   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
20153     unsigned int h = strHash(elem->pKey, elem->nKey) % new_size;
20154     next_elem = elem->next;
20155     insertElement(pH, &new_ht[h], elem);
20156   }
20157   return 1;
20158 }
20159
20160 /* This function (for internal use only) locates an element in an
20161 ** hash table that matches the given key.  The hash for this key has
20162 ** already been computed and is passed as the 4th parameter.
20163 */
20164 static HashElem *findElementGivenHash(
20165   const Hash *pH,     /* The pH to be searched */
20166   const char *pKey,   /* The key we are searching for */
20167   int nKey,           /* Bytes in key (not counting zero terminator) */
20168   unsigned int h      /* The hash for this key. */
20169 ){
20170   HashElem *elem;                /* Used to loop thru the element list */
20171   int count;                     /* Number of elements left to test */
20172
20173   if( pH->ht ){
20174     struct _ht *pEntry = &pH->ht[h];
20175     elem = pEntry->chain;
20176     count = pEntry->count;
20177   }else{
20178     elem = pH->first;
20179     count = pH->count;
20180   }
20181   while( count-- && ALWAYS(elem) ){
20182     if( elem->nKey==nKey && sqlite3StrNICmp(elem->pKey,pKey,nKey)==0 ){ 
20183       return elem;
20184     }
20185     elem = elem->next;
20186   }
20187   return 0;
20188 }
20189
20190 /* Remove a single entry from the hash table given a pointer to that
20191 ** element and a hash on the element's key.
20192 */
20193 static void removeElementGivenHash(
20194   Hash *pH,         /* The pH containing "elem" */
20195   HashElem* elem,   /* The element to be removed from the pH */
20196   unsigned int h    /* Hash value for the element */
20197 ){
20198   struct _ht *pEntry;
20199   if( elem->prev ){
20200     elem->prev->next = elem->next; 
20201   }else{
20202     pH->first = elem->next;
20203   }
20204   if( elem->next ){
20205     elem->next->prev = elem->prev;
20206   }
20207   if( pH->ht ){
20208     pEntry = &pH->ht[h];
20209     if( pEntry->chain==elem ){
20210       pEntry->chain = elem->next;
20211     }
20212     pEntry->count--;
20213     assert( pEntry->count>=0 );
20214   }
20215   sqlite3_free( elem );
20216   pH->count--;
20217   if( pH->count<=0 ){
20218     assert( pH->first==0 );
20219     assert( pH->count==0 );
20220     sqlite3HashClear(pH);
20221   }
20222 }
20223
20224 /* Attempt to locate an element of the hash table pH with a key
20225 ** that matches pKey,nKey.  Return the data for this element if it is
20226 ** found, or NULL if there is no match.
20227 */
20228 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey, int nKey){
20229   HashElem *elem;    /* The element that matches key */
20230   unsigned int h;    /* A hash on key */
20231
20232   assert( pH!=0 );
20233   assert( pKey!=0 );
20234   assert( nKey>=0 );
20235   if( pH->ht ){
20236     h = strHash(pKey, nKey) % pH->htsize;
20237   }else{
20238     h = 0;
20239   }
20240   elem = findElementGivenHash(pH, pKey, nKey, h);
20241   return elem ? elem->data : 0;
20242 }
20243
20244 /* Insert an element into the hash table pH.  The key is pKey,nKey
20245 ** and the data is "data".
20246 **
20247 ** If no element exists with a matching key, then a new
20248 ** element is created and NULL is returned.
20249 **
20250 ** If another element already exists with the same key, then the
20251 ** new data replaces the old data and the old data is returned.
20252 ** The key is not copied in this instance.  If a malloc fails, then
20253 ** the new data is returned and the hash table is unchanged.
20254 **
20255 ** If the "data" parameter to this function is NULL, then the
20256 ** element corresponding to "key" is removed from the hash table.
20257 */
20258 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, int nKey, void *data){
20259   unsigned int h;       /* the hash of the key modulo hash table size */
20260   HashElem *elem;       /* Used to loop thru the element list */
20261   HashElem *new_elem;   /* New element added to the pH */
20262
20263   assert( pH!=0 );
20264   assert( pKey!=0 );
20265   assert( nKey>=0 );
20266   if( pH->htsize ){
20267     h = strHash(pKey, nKey) % pH->htsize;
20268   }else{
20269     h = 0;
20270   }
20271   elem = findElementGivenHash(pH,pKey,nKey,h);
20272   if( elem ){
20273     void *old_data = elem->data;
20274     if( data==0 ){
20275       removeElementGivenHash(pH,elem,h);
20276     }else{
20277       elem->data = data;
20278       elem->pKey = pKey;
20279       assert(nKey==elem->nKey);
20280     }
20281     return old_data;
20282   }
20283   if( data==0 ) return 0;
20284   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
20285   if( new_elem==0 ) return data;
20286   new_elem->pKey = pKey;
20287   new_elem->nKey = nKey;
20288   new_elem->data = data;
20289   pH->count++;
20290   if( pH->count>=10 && pH->count > 2*pH->htsize ){
20291     if( rehash(pH, pH->count*2) ){
20292       assert( pH->htsize>0 );
20293       h = strHash(pKey, nKey) % pH->htsize;
20294     }
20295   }
20296   if( pH->ht ){
20297     insertElement(pH, &pH->ht[h], new_elem);
20298   }else{
20299     insertElement(pH, 0, new_elem);
20300   }
20301   return 0;
20302 }
20303
20304 /************** End of hash.c ************************************************/
20305 /************** Begin file opcodes.c *****************************************/
20306 /* Automatically generated.  Do not edit */
20307 /* See the mkopcodec.awk script for details. */
20308 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
20309 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
20310  static const char *const azName[] = { "?",
20311      /*   1 */ "Goto",
20312      /*   2 */ "Gosub",
20313      /*   3 */ "Return",
20314      /*   4 */ "Yield",
20315      /*   5 */ "HaltIfNull",
20316      /*   6 */ "Halt",
20317      /*   7 */ "Integer",
20318      /*   8 */ "Int64",
20319      /*   9 */ "String",
20320      /*  10 */ "Null",
20321      /*  11 */ "Blob",
20322      /*  12 */ "Variable",
20323      /*  13 */ "Move",
20324      /*  14 */ "Copy",
20325      /*  15 */ "SCopy",
20326      /*  16 */ "ResultRow",
20327      /*  17 */ "CollSeq",
20328      /*  18 */ "Function",
20329      /*  19 */ "Not",
20330      /*  20 */ "AddImm",
20331      /*  21 */ "MustBeInt",
20332      /*  22 */ "RealAffinity",
20333      /*  23 */ "Permutation",
20334      /*  24 */ "Compare",
20335      /*  25 */ "Jump",
20336      /*  26 */ "If",
20337      /*  27 */ "IfNot",
20338      /*  28 */ "Column",
20339      /*  29 */ "Affinity",
20340      /*  30 */ "MakeRecord",
20341      /*  31 */ "Count",
20342      /*  32 */ "Savepoint",
20343      /*  33 */ "AutoCommit",
20344      /*  34 */ "Transaction",
20345      /*  35 */ "ReadCookie",
20346      /*  36 */ "SetCookie",
20347      /*  37 */ "VerifyCookie",
20348      /*  38 */ "OpenRead",
20349      /*  39 */ "OpenWrite",
20350      /*  40 */ "OpenEphemeral",
20351      /*  41 */ "OpenPseudo",
20352      /*  42 */ "Close",
20353      /*  43 */ "SeekLt",
20354      /*  44 */ "SeekLe",
20355      /*  45 */ "SeekGe",
20356      /*  46 */ "SeekGt",
20357      /*  47 */ "Seek",
20358      /*  48 */ "NotFound",
20359      /*  49 */ "Found",
20360      /*  50 */ "IsUnique",
20361      /*  51 */ "NotExists",
20362      /*  52 */ "Sequence",
20363      /*  53 */ "NewRowid",
20364      /*  54 */ "Insert",
20365      /*  55 */ "InsertInt",
20366      /*  56 */ "Delete",
20367      /*  57 */ "ResetCount",
20368      /*  58 */ "RowKey",
20369      /*  59 */ "RowData",
20370      /*  60 */ "Rowid",
20371      /*  61 */ "NullRow",
20372      /*  62 */ "Last",
20373      /*  63 */ "Sort",
20374      /*  64 */ "Rewind",
20375      /*  65 */ "Prev",
20376      /*  66 */ "Next",
20377      /*  67 */ "IdxInsert",
20378      /*  68 */ "Or",
20379      /*  69 */ "And",
20380      /*  70 */ "IdxDelete",
20381      /*  71 */ "IdxRowid",
20382      /*  72 */ "IdxLT",
20383      /*  73 */ "IsNull",
20384      /*  74 */ "NotNull",
20385      /*  75 */ "Ne",
20386      /*  76 */ "Eq",
20387      /*  77 */ "Gt",
20388      /*  78 */ "Le",
20389      /*  79 */ "Lt",
20390      /*  80 */ "Ge",
20391      /*  81 */ "IdxGE",
20392      /*  82 */ "BitAnd",
20393      /*  83 */ "BitOr",
20394      /*  84 */ "ShiftLeft",
20395      /*  85 */ "ShiftRight",
20396      /*  86 */ "Add",
20397      /*  87 */ "Subtract",
20398      /*  88 */ "Multiply",
20399      /*  89 */ "Divide",
20400      /*  90 */ "Remainder",
20401      /*  91 */ "Concat",
20402      /*  92 */ "Destroy",
20403      /*  93 */ "BitNot",
20404      /*  94 */ "String8",
20405      /*  95 */ "Clear",
20406      /*  96 */ "CreateIndex",
20407      /*  97 */ "CreateTable",
20408      /*  98 */ "ParseSchema",
20409      /*  99 */ "LoadAnalysis",
20410      /* 100 */ "DropTable",
20411      /* 101 */ "DropIndex",
20412      /* 102 */ "DropTrigger",
20413      /* 103 */ "IntegrityCk",
20414      /* 104 */ "RowSetAdd",
20415      /* 105 */ "RowSetRead",
20416      /* 106 */ "RowSetTest",
20417      /* 107 */ "Program",
20418      /* 108 */ "Param",
20419      /* 109 */ "FkCounter",
20420      /* 110 */ "FkIfZero",
20421      /* 111 */ "MemMax",
20422      /* 112 */ "IfPos",
20423      /* 113 */ "IfNeg",
20424      /* 114 */ "IfZero",
20425      /* 115 */ "AggStep",
20426      /* 116 */ "AggFinal",
20427      /* 117 */ "Vacuum",
20428      /* 118 */ "IncrVacuum",
20429      /* 119 */ "Expire",
20430      /* 120 */ "TableLock",
20431      /* 121 */ "VBegin",
20432      /* 122 */ "VCreate",
20433      /* 123 */ "VDestroy",
20434      /* 124 */ "VOpen",
20435      /* 125 */ "VFilter",
20436      /* 126 */ "VColumn",
20437      /* 127 */ "VNext",
20438      /* 128 */ "VRename",
20439      /* 129 */ "VUpdate",
20440      /* 130 */ "Real",
20441      /* 131 */ "Pagecount",
20442      /* 132 */ "Trace",
20443      /* 133 */ "Noop",
20444      /* 134 */ "Explain",
20445      /* 135 */ "NotUsed_135",
20446      /* 136 */ "NotUsed_136",
20447      /* 137 */ "NotUsed_137",
20448      /* 138 */ "NotUsed_138",
20449      /* 139 */ "NotUsed_139",
20450      /* 140 */ "NotUsed_140",
20451      /* 141 */ "ToText",
20452      /* 142 */ "ToBlob",
20453      /* 143 */ "ToNumeric",
20454      /* 144 */ "ToInt",
20455      /* 145 */ "ToReal",
20456   };
20457   return azName[i];
20458 }
20459 #endif
20460
20461 /************** End of opcodes.c *********************************************/
20462 /************** Begin file os_os2.c ******************************************/
20463 /*
20464 ** 2006 Feb 14
20465 **
20466 ** The author disclaims copyright to this source code.  In place of
20467 ** a legal notice, here is a blessing:
20468 **
20469 **    May you do good and not evil.
20470 **    May you find forgiveness for yourself and forgive others.
20471 **    May you share freely, never taking more than you give.
20472 **
20473 ******************************************************************************
20474 **
20475 ** This file contains code that is specific to OS/2.
20476 */
20477
20478
20479 #if SQLITE_OS_OS2
20480
20481 /*
20482 ** A Note About Memory Allocation:
20483 **
20484 ** This driver uses malloc()/free() directly rather than going through
20485 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
20486 ** are designed for use on embedded systems where memory is scarce and
20487 ** malloc failures happen frequently.  OS/2 does not typically run on
20488 ** embedded systems, and when it does the developers normally have bigger
20489 ** problems to worry about than running out of memory.  So there is not
20490 ** a compelling need to use the wrappers.
20491 **
20492 ** But there is a good reason to not use the wrappers.  If we use the
20493 ** wrappers then we will get simulated malloc() failures within this
20494 ** driver.  And that causes all kinds of problems for our tests.  We
20495 ** could enhance SQLite to deal with simulated malloc failures within
20496 ** the OS driver, but the code to deal with those failure would not
20497 ** be exercised on Linux (which does not need to malloc() in the driver)
20498 ** and so we would have difficulty writing coverage tests for that
20499 ** code.  Better to leave the code out, we think.
20500 **
20501 ** The point of this discussion is as follows:  When creating a new
20502 ** OS layer for an embedded system, if you use this file as an example,
20503 ** avoid the use of malloc()/free().  Those routines work ok on OS/2
20504 ** desktops but not so well in embedded systems.
20505 */
20506
20507 /*
20508 ** Macros used to determine whether or not to use threads.
20509 */
20510 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE
20511 # define SQLITE_OS2_THREADS 1
20512 #endif
20513
20514 /*
20515 ** Include code that is common to all os_*.c files
20516 */
20517 /************** Include os_common.h in the middle of os_os2.c ****************/
20518 /************** Begin file os_common.h ***************************************/
20519 /*
20520 ** 2004 May 22
20521 **
20522 ** The author disclaims copyright to this source code.  In place of
20523 ** a legal notice, here is a blessing:
20524 **
20525 **    May you do good and not evil.
20526 **    May you find forgiveness for yourself and forgive others.
20527 **    May you share freely, never taking more than you give.
20528 **
20529 ******************************************************************************
20530 **
20531 ** This file contains macros and a little bit of code that is common to
20532 ** all of the platform-specific files (os_*.c) and is #included into those
20533 ** files.
20534 **
20535 ** This file should be #included by the os_*.c files only.  It is not a
20536 ** general purpose header file.
20537 */
20538 #ifndef _OS_COMMON_H_
20539 #define _OS_COMMON_H_
20540
20541 /*
20542 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
20543 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
20544 ** switch.  The following code should catch this problem at compile-time.
20545 */
20546 #ifdef MEMORY_DEBUG
20547 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
20548 #endif
20549
20550 #ifdef SQLITE_DEBUG
20551 SQLITE_PRIVATE int sqlite3OSTrace = 0;
20552 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
20553 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
20554 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
20555 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
20556 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
20557 #define OSTRACE6(X,Y,Z,A,B,C) \
20558     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
20559 #define OSTRACE7(X,Y,Z,A,B,C,D) \
20560     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
20561 #else
20562 #define OSTRACE1(X)
20563 #define OSTRACE2(X,Y)
20564 #define OSTRACE3(X,Y,Z)
20565 #define OSTRACE4(X,Y,Z,A)
20566 #define OSTRACE5(X,Y,Z,A,B)
20567 #define OSTRACE6(X,Y,Z,A,B,C)
20568 #define OSTRACE7(X,Y,Z,A,B,C,D)
20569 #endif
20570
20571 /*
20572 ** Macros for performance tracing.  Normally turned off.  Only works
20573 ** on i486 hardware.
20574 */
20575 #ifdef SQLITE_PERFORMANCE_TRACE
20576
20577 /* 
20578 ** hwtime.h contains inline assembler code for implementing 
20579 ** high-performance timing routines.
20580 */
20581 /************** Include hwtime.h in the middle of os_common.h ****************/
20582 /************** Begin file hwtime.h ******************************************/
20583 /*
20584 ** 2008 May 27
20585 **
20586 ** The author disclaims copyright to this source code.  In place of
20587 ** a legal notice, here is a blessing:
20588 **
20589 **    May you do good and not evil.
20590 **    May you find forgiveness for yourself and forgive others.
20591 **    May you share freely, never taking more than you give.
20592 **
20593 ******************************************************************************
20594 **
20595 ** This file contains inline asm code for retrieving "high-performance"
20596 ** counters for x86 class CPUs.
20597 */
20598 #ifndef _HWTIME_H_
20599 #define _HWTIME_H_
20600
20601 /*
20602 ** The following routine only works on pentium-class (or newer) processors.
20603 ** It uses the RDTSC opcode to read the cycle count value out of the
20604 ** processor and returns that value.  This can be used for high-res
20605 ** profiling.
20606 */
20607 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
20608       (defined(i386) || defined(__i386__) || defined(_M_IX86))
20609
20610   #if defined(__GNUC__)
20611
20612   __inline__ sqlite_uint64 sqlite3Hwtime(void){
20613      unsigned int lo, hi;
20614      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
20615      return (sqlite_uint64)hi << 32 | lo;
20616   }
20617
20618   #elif defined(_MSC_VER)
20619
20620   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
20621      __asm {
20622         rdtsc
20623         ret       ; return value at EDX:EAX
20624      }
20625   }
20626
20627   #endif
20628
20629 #elif (defined(__GNUC__) && defined(__x86_64__))
20630
20631   __inline__ sqlite_uint64 sqlite3Hwtime(void){
20632       unsigned long val;
20633       __asm__ __volatile__ ("rdtsc" : "=A" (val));
20634       return val;
20635   }
20636  
20637 #elif (defined(__GNUC__) && defined(__ppc__))
20638
20639   __inline__ sqlite_uint64 sqlite3Hwtime(void){
20640       unsigned long long retval;
20641       unsigned long junk;
20642       __asm__ __volatile__ ("\n\
20643           1:      mftbu   %1\n\
20644                   mftb    %L0\n\
20645                   mftbu   %0\n\
20646                   cmpw    %0,%1\n\
20647                   bne     1b"
20648                   : "=r" (retval), "=r" (junk));
20649       return retval;
20650   }
20651
20652 #else
20653
20654   #error Need implementation of sqlite3Hwtime() for your platform.
20655
20656   /*
20657   ** To compile without implementing sqlite3Hwtime() for your platform,
20658   ** you can remove the above #error and use the following
20659   ** stub function.  You will lose timing support for many
20660   ** of the debugging and testing utilities, but it should at
20661   ** least compile and run.
20662   */
20663 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
20664
20665 #endif
20666
20667 #endif /* !defined(_HWTIME_H_) */
20668
20669 /************** End of hwtime.h **********************************************/
20670 /************** Continuing where we left off in os_common.h ******************/
20671
20672 static sqlite_uint64 g_start;
20673 static sqlite_uint64 g_elapsed;
20674 #define TIMER_START       g_start=sqlite3Hwtime()
20675 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
20676 #define TIMER_ELAPSED     g_elapsed
20677 #else
20678 #define TIMER_START
20679 #define TIMER_END
20680 #define TIMER_ELAPSED     ((sqlite_uint64)0)
20681 #endif
20682
20683 /*
20684 ** If we compile with the SQLITE_TEST macro set, then the following block
20685 ** of code will give us the ability to simulate a disk I/O error.  This
20686 ** is used for testing the I/O recovery logic.
20687 */
20688 #ifdef SQLITE_TEST
20689 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
20690 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
20691 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
20692 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
20693 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
20694 SQLITE_API int sqlite3_diskfull_pending = 0;
20695 SQLITE_API int sqlite3_diskfull = 0;
20696 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
20697 #define SimulateIOError(CODE)  \
20698   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
20699        || sqlite3_io_error_pending-- == 1 )  \
20700               { local_ioerr(); CODE; }
20701 static void local_ioerr(){
20702   IOTRACE(("IOERR\n"));
20703   sqlite3_io_error_hit++;
20704   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
20705 }
20706 #define SimulateDiskfullError(CODE) \
20707    if( sqlite3_diskfull_pending ){ \
20708      if( sqlite3_diskfull_pending == 1 ){ \
20709        local_ioerr(); \
20710        sqlite3_diskfull = 1; \
20711        sqlite3_io_error_hit = 1; \
20712        CODE; \
20713      }else{ \
20714        sqlite3_diskfull_pending--; \
20715      } \
20716    }
20717 #else
20718 #define SimulateIOErrorBenign(X)
20719 #define SimulateIOError(A)
20720 #define SimulateDiskfullError(A)
20721 #endif
20722
20723 /*
20724 ** When testing, keep a count of the number of open files.
20725 */
20726 #ifdef SQLITE_TEST
20727 SQLITE_API int sqlite3_open_file_count = 0;
20728 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
20729 #else
20730 #define OpenCounter(X)
20731 #endif
20732
20733 #endif /* !defined(_OS_COMMON_H_) */
20734
20735 /************** End of os_common.h *******************************************/
20736 /************** Continuing where we left off in os_os2.c *********************/
20737
20738 /*
20739 ** The os2File structure is subclass of sqlite3_file specific for the OS/2
20740 ** protability layer.
20741 */
20742 typedef struct os2File os2File;
20743 struct os2File {
20744   const sqlite3_io_methods *pMethod;  /* Always the first entry */
20745   HFILE h;                  /* Handle for accessing the file */
20746   char* pathToDel;          /* Name of file to delete on close, NULL if not */
20747   unsigned char locktype;   /* Type of lock currently held on this file */
20748 };
20749
20750 #define LOCK_TIMEOUT 10L /* the default locking timeout */
20751
20752 /*****************************************************************************
20753 ** The next group of routines implement the I/O methods specified
20754 ** by the sqlite3_io_methods object.
20755 ******************************************************************************/
20756
20757 /*
20758 ** Close a file.
20759 */
20760 static int os2Close( sqlite3_file *id ){
20761   APIRET rc = NO_ERROR;
20762   os2File *pFile;
20763   if( id && (pFile = (os2File*)id) != 0 ){
20764     OSTRACE2( "CLOSE %d\n", pFile->h );
20765     rc = DosClose( pFile->h );
20766     pFile->locktype = NO_LOCK;
20767     if( pFile->pathToDel != NULL ){
20768       rc = DosForceDelete( (PSZ)pFile->pathToDel );
20769       free( pFile->pathToDel );
20770       pFile->pathToDel = NULL;
20771     }
20772     id = 0;
20773     OpenCounter( -1 );
20774   }
20775
20776   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20777 }
20778
20779 /*
20780 ** Read data from a file into a buffer.  Return SQLITE_OK if all
20781 ** bytes were read successfully and SQLITE_IOERR if anything goes
20782 ** wrong.
20783 */
20784 static int os2Read(
20785   sqlite3_file *id,               /* File to read from */
20786   void *pBuf,                     /* Write content into this buffer */
20787   int amt,                        /* Number of bytes to read */
20788   sqlite3_int64 offset            /* Begin reading at this offset */
20789 ){
20790   ULONG fileLocation = 0L;
20791   ULONG got;
20792   os2File *pFile = (os2File*)id;
20793   assert( id!=0 );
20794   SimulateIOError( return SQLITE_IOERR_READ );
20795   OSTRACE3( "READ %d lock=%d\n", pFile->h, pFile->locktype );
20796   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20797     return SQLITE_IOERR;
20798   }
20799   if( DosRead( pFile->h, pBuf, amt, &got ) != NO_ERROR ){
20800     return SQLITE_IOERR_READ;
20801   }
20802   if( got == (ULONG)amt )
20803     return SQLITE_OK;
20804   else {
20805     /* Unread portions of the input buffer must be zero-filled */
20806     memset(&((char*)pBuf)[got], 0, amt-got);
20807     return SQLITE_IOERR_SHORT_READ;
20808   }
20809 }
20810
20811 /*
20812 ** Write data from a buffer into a file.  Return SQLITE_OK on success
20813 ** or some other error code on failure.
20814 */
20815 static int os2Write(
20816   sqlite3_file *id,               /* File to write into */
20817   const void *pBuf,               /* The bytes to be written */
20818   int amt,                        /* Number of bytes to write */
20819   sqlite3_int64 offset            /* Offset into the file to begin writing at */
20820 ){
20821   ULONG fileLocation = 0L;
20822   APIRET rc = NO_ERROR;
20823   ULONG wrote;
20824   os2File *pFile = (os2File*)id;
20825   assert( id!=0 );
20826   SimulateIOError( return SQLITE_IOERR_WRITE );
20827   SimulateDiskfullError( return SQLITE_FULL );
20828   OSTRACE3( "WRITE %d lock=%d\n", pFile->h, pFile->locktype );
20829   if( DosSetFilePtr(pFile->h, offset, FILE_BEGIN, &fileLocation) != NO_ERROR ){
20830     return SQLITE_IOERR;
20831   }
20832   assert( amt>0 );
20833   while( amt > 0 &&
20834          ( rc = DosWrite( pFile->h, (PVOID)pBuf, amt, &wrote ) ) == NO_ERROR &&
20835          wrote > 0
20836   ){
20837     amt -= wrote;
20838     pBuf = &((char*)pBuf)[wrote];
20839   }
20840
20841   return ( rc != NO_ERROR || amt > (int)wrote ) ? SQLITE_FULL : SQLITE_OK;
20842 }
20843
20844 /*
20845 ** Truncate an open file to a specified size
20846 */
20847 static int os2Truncate( sqlite3_file *id, i64 nByte ){
20848   APIRET rc = NO_ERROR;
20849   os2File *pFile = (os2File*)id;
20850   OSTRACE3( "TRUNCATE %d %lld\n", pFile->h, nByte );
20851   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
20852   rc = DosSetFileSize( pFile->h, nByte );
20853   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_TRUNCATE;
20854 }
20855
20856 #ifdef SQLITE_TEST
20857 /*
20858 ** Count the number of fullsyncs and normal syncs.  This is used to test
20859 ** that syncs and fullsyncs are occuring at the right times.
20860 */
20861 SQLITE_API int sqlite3_sync_count = 0;
20862 SQLITE_API int sqlite3_fullsync_count = 0;
20863 #endif
20864
20865 /*
20866 ** Make sure all writes to a particular file are committed to disk.
20867 */
20868 static int os2Sync( sqlite3_file *id, int flags ){
20869   os2File *pFile = (os2File*)id;
20870   OSTRACE3( "SYNC %d lock=%d\n", pFile->h, pFile->locktype );
20871 #ifdef SQLITE_TEST
20872   if( flags & SQLITE_SYNC_FULL){
20873     sqlite3_fullsync_count++;
20874   }
20875   sqlite3_sync_count++;
20876 #endif
20877   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
20878   ** no-op
20879   */
20880 #ifdef SQLITE_NO_SYNC
20881   UNUSED_PARAMETER(pFile);
20882   return SQLITE_OK;
20883 #else
20884   return DosResetBuffer( pFile->h ) == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
20885 #endif
20886 }
20887
20888 /*
20889 ** Determine the current size of a file in bytes
20890 */
20891 static int os2FileSize( sqlite3_file *id, sqlite3_int64 *pSize ){
20892   APIRET rc = NO_ERROR;
20893   FILESTATUS3 fsts3FileInfo;
20894   memset(&fsts3FileInfo, 0, sizeof(fsts3FileInfo));
20895   assert( id!=0 );
20896   SimulateIOError( return SQLITE_IOERR_FSTAT );
20897   rc = DosQueryFileInfo( ((os2File*)id)->h, FIL_STANDARD, &fsts3FileInfo, sizeof(FILESTATUS3) );
20898   if( rc == NO_ERROR ){
20899     *pSize = fsts3FileInfo.cbFile;
20900     return SQLITE_OK;
20901   }else{
20902     return SQLITE_IOERR_FSTAT;
20903   }
20904 }
20905
20906 /*
20907 ** Acquire a reader lock.
20908 */
20909 static int getReadLock( os2File *pFile ){
20910   FILELOCK  LockArea,
20911             UnlockArea;
20912   APIRET res;
20913   memset(&LockArea, 0, sizeof(LockArea));
20914   memset(&UnlockArea, 0, sizeof(UnlockArea));
20915   LockArea.lOffset = SHARED_FIRST;
20916   LockArea.lRange = SHARED_SIZE;
20917   UnlockArea.lOffset = 0L;
20918   UnlockArea.lRange = 0L;
20919   res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
20920   OSTRACE3( "GETREADLOCK %d res=%d\n", pFile->h, res );
20921   return res;
20922 }
20923
20924 /*
20925 ** Undo a readlock
20926 */
20927 static int unlockReadLock( os2File *id ){
20928   FILELOCK  LockArea,
20929             UnlockArea;
20930   APIRET res;
20931   memset(&LockArea, 0, sizeof(LockArea));
20932   memset(&UnlockArea, 0, sizeof(UnlockArea));
20933   LockArea.lOffset = 0L;
20934   LockArea.lRange = 0L;
20935   UnlockArea.lOffset = SHARED_FIRST;
20936   UnlockArea.lRange = SHARED_SIZE;
20937   res = DosSetFileLocks( id->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 1L );
20938   OSTRACE3( "UNLOCK-READLOCK file handle=%d res=%d?\n", id->h, res );
20939   return res;
20940 }
20941
20942 /*
20943 ** Lock the file with the lock specified by parameter locktype - one
20944 ** of the following:
20945 **
20946 **     (1) SHARED_LOCK
20947 **     (2) RESERVED_LOCK
20948 **     (3) PENDING_LOCK
20949 **     (4) EXCLUSIVE_LOCK
20950 **
20951 ** Sometimes when requesting one lock state, additional lock states
20952 ** are inserted in between.  The locking might fail on one of the later
20953 ** transitions leaving the lock state different from what it started but
20954 ** still short of its goal.  The following chart shows the allowed
20955 ** transitions and the inserted intermediate states:
20956 **
20957 **    UNLOCKED -> SHARED
20958 **    SHARED -> RESERVED
20959 **    SHARED -> (PENDING) -> EXCLUSIVE
20960 **    RESERVED -> (PENDING) -> EXCLUSIVE
20961 **    PENDING -> EXCLUSIVE
20962 **
20963 ** This routine will only increase a lock.  The os2Unlock() routine
20964 ** erases all locks at once and returns us immediately to locking level 0.
20965 ** It is not possible to lower the locking level one step at a time.  You
20966 ** must go straight to locking level 0.
20967 */
20968 static int os2Lock( sqlite3_file *id, int locktype ){
20969   int rc = SQLITE_OK;       /* Return code from subroutines */
20970   APIRET res = NO_ERROR;    /* Result of an OS/2 lock call */
20971   int newLocktype;       /* Set pFile->locktype to this value before exiting */
20972   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
20973   FILELOCK  LockArea,
20974             UnlockArea;
20975   os2File *pFile = (os2File*)id;
20976   memset(&LockArea, 0, sizeof(LockArea));
20977   memset(&UnlockArea, 0, sizeof(UnlockArea));
20978   assert( pFile!=0 );
20979   OSTRACE4( "LOCK %d %d was %d\n", pFile->h, locktype, pFile->locktype );
20980
20981   /* If there is already a lock of this type or more restrictive on the
20982   ** os2File, do nothing. Don't use the end_lock: exit path, as
20983   ** sqlite3_mutex_enter() hasn't been called yet.
20984   */
20985   if( pFile->locktype>=locktype ){
20986     OSTRACE3( "LOCK %d %d ok (already held)\n", pFile->h, locktype );
20987     return SQLITE_OK;
20988   }
20989
20990   /* Make sure the locking sequence is correct
20991   */
20992   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
20993   assert( locktype!=PENDING_LOCK );
20994   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
20995
20996   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
20997   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
20998   ** the PENDING_LOCK byte is temporary.
20999   */
21000   newLocktype = pFile->locktype;
21001   if( pFile->locktype==NO_LOCK
21002       || (locktype==EXCLUSIVE_LOCK && pFile->locktype==RESERVED_LOCK)
21003   ){
21004     LockArea.lOffset = PENDING_BYTE;
21005     LockArea.lRange = 1L;
21006     UnlockArea.lOffset = 0L;
21007     UnlockArea.lRange = 0L;
21008
21009     /* wait longer than LOCK_TIMEOUT here not to have to try multiple times */
21010     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, 100L, 0L );
21011     if( res == NO_ERROR ){
21012       gotPendingLock = 1;
21013       OSTRACE3( "LOCK %d pending lock boolean set.  res=%d\n", pFile->h, res );
21014     }
21015   }
21016
21017   /* Acquire a shared lock
21018   */
21019   if( locktype==SHARED_LOCK && res == NO_ERROR ){
21020     assert( pFile->locktype==NO_LOCK );
21021     res = getReadLock(pFile);
21022     if( res == NO_ERROR ){
21023       newLocktype = SHARED_LOCK;
21024     }
21025     OSTRACE3( "LOCK %d acquire shared lock. res=%d\n", pFile->h, res );
21026   }
21027
21028   /* Acquire a RESERVED lock
21029   */
21030   if( locktype==RESERVED_LOCK && res == NO_ERROR ){
21031     assert( pFile->locktype==SHARED_LOCK );
21032     LockArea.lOffset = RESERVED_BYTE;
21033     LockArea.lRange = 1L;
21034     UnlockArea.lOffset = 0L;
21035     UnlockArea.lRange = 0L;
21036     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21037     if( res == NO_ERROR ){
21038       newLocktype = RESERVED_LOCK;
21039     }
21040     OSTRACE3( "LOCK %d acquire reserved lock. res=%d\n", pFile->h, res );
21041   }
21042
21043   /* Acquire a PENDING lock
21044   */
21045   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
21046     newLocktype = PENDING_LOCK;
21047     gotPendingLock = 0;
21048     OSTRACE2( "LOCK %d acquire pending lock. pending lock boolean unset.\n", pFile->h );
21049   }
21050
21051   /* Acquire an EXCLUSIVE lock
21052   */
21053   if( locktype==EXCLUSIVE_LOCK && res == NO_ERROR ){
21054     assert( pFile->locktype>=SHARED_LOCK );
21055     res = unlockReadLock(pFile);
21056     OSTRACE2( "unreadlock = %d\n", res );
21057     LockArea.lOffset = SHARED_FIRST;
21058     LockArea.lRange = SHARED_SIZE;
21059     UnlockArea.lOffset = 0L;
21060     UnlockArea.lRange = 0L;
21061     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21062     if( res == NO_ERROR ){
21063       newLocktype = EXCLUSIVE_LOCK;
21064     }else{
21065       OSTRACE2( "OS/2 error-code = %d\n", res );
21066       getReadLock(pFile);
21067     }
21068     OSTRACE3( "LOCK %d acquire exclusive lock.  res=%d\n", pFile->h, res );
21069   }
21070
21071   /* If we are holding a PENDING lock that ought to be released, then
21072   ** release it now.
21073   */
21074   if( gotPendingLock && locktype==SHARED_LOCK ){
21075     int r;
21076     LockArea.lOffset = 0L;
21077     LockArea.lRange = 0L;
21078     UnlockArea.lOffset = PENDING_BYTE;
21079     UnlockArea.lRange = 1L;
21080     r = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21081     OSTRACE3( "LOCK %d unlocking pending/is shared. r=%d\n", pFile->h, r );
21082   }
21083
21084   /* Update the state of the lock has held in the file descriptor then
21085   ** return the appropriate result code.
21086   */
21087   if( res == NO_ERROR ){
21088     rc = SQLITE_OK;
21089   }else{
21090     OSTRACE4( "LOCK FAILED %d trying for %d but got %d\n", pFile->h,
21091               locktype, newLocktype );
21092     rc = SQLITE_BUSY;
21093   }
21094   pFile->locktype = newLocktype;
21095   OSTRACE3( "LOCK %d now %d\n", pFile->h, pFile->locktype );
21096   return rc;
21097 }
21098
21099 /*
21100 ** This routine checks if there is a RESERVED lock held on the specified
21101 ** file by this or any other process. If such a lock is held, return
21102 ** non-zero, otherwise zero.
21103 */
21104 static int os2CheckReservedLock( sqlite3_file *id, int *pOut ){
21105   int r = 0;
21106   os2File *pFile = (os2File*)id;
21107   assert( pFile!=0 );
21108   if( pFile->locktype>=RESERVED_LOCK ){
21109     r = 1;
21110     OSTRACE3( "TEST WR-LOCK %d %d (local)\n", pFile->h, r );
21111   }else{
21112     FILELOCK  LockArea,
21113               UnlockArea;
21114     APIRET rc = NO_ERROR;
21115     memset(&LockArea, 0, sizeof(LockArea));
21116     memset(&UnlockArea, 0, sizeof(UnlockArea));
21117     LockArea.lOffset = RESERVED_BYTE;
21118     LockArea.lRange = 1L;
21119     UnlockArea.lOffset = 0L;
21120     UnlockArea.lRange = 0L;
21121     rc = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21122     OSTRACE3( "TEST WR-LOCK %d lock reserved byte rc=%d\n", pFile->h, rc );
21123     if( rc == NO_ERROR ){
21124       APIRET rcu = NO_ERROR; /* return code for unlocking */
21125       LockArea.lOffset = 0L;
21126       LockArea.lRange = 0L;
21127       UnlockArea.lOffset = RESERVED_BYTE;
21128       UnlockArea.lRange = 1L;
21129       rcu = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21130       OSTRACE3( "TEST WR-LOCK %d unlock reserved byte r=%d\n", pFile->h, rcu );
21131     }
21132     r = !(rc == NO_ERROR);
21133     OSTRACE3( "TEST WR-LOCK %d %d (remote)\n", pFile->h, r );
21134   }
21135   *pOut = r;
21136   return SQLITE_OK;
21137 }
21138
21139 /*
21140 ** Lower the locking level on file descriptor id to locktype.  locktype
21141 ** must be either NO_LOCK or SHARED_LOCK.
21142 **
21143 ** If the locking level of the file descriptor is already at or below
21144 ** the requested locking level, this routine is a no-op.
21145 **
21146 ** It is not possible for this routine to fail if the second argument
21147 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
21148 ** might return SQLITE_IOERR;
21149 */
21150 static int os2Unlock( sqlite3_file *id, int locktype ){
21151   int type;
21152   os2File *pFile = (os2File*)id;
21153   APIRET rc = SQLITE_OK;
21154   APIRET res = NO_ERROR;
21155   FILELOCK  LockArea,
21156             UnlockArea;
21157   memset(&LockArea, 0, sizeof(LockArea));
21158   memset(&UnlockArea, 0, sizeof(UnlockArea));
21159   assert( pFile!=0 );
21160   assert( locktype<=SHARED_LOCK );
21161   OSTRACE4( "UNLOCK %d to %d was %d\n", pFile->h, locktype, pFile->locktype );
21162   type = pFile->locktype;
21163   if( type>=EXCLUSIVE_LOCK ){
21164     LockArea.lOffset = 0L;
21165     LockArea.lRange = 0L;
21166     UnlockArea.lOffset = SHARED_FIRST;
21167     UnlockArea.lRange = SHARED_SIZE;
21168     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21169     OSTRACE3( "UNLOCK %d exclusive lock res=%d\n", pFile->h, res );
21170     if( locktype==SHARED_LOCK && getReadLock(pFile) != NO_ERROR ){
21171       /* This should never happen.  We should always be able to
21172       ** reacquire the read lock */
21173       OSTRACE3( "UNLOCK %d to %d getReadLock() failed\n", pFile->h, locktype );
21174       rc = SQLITE_IOERR_UNLOCK;
21175     }
21176   }
21177   if( type>=RESERVED_LOCK ){
21178     LockArea.lOffset = 0L;
21179     LockArea.lRange = 0L;
21180     UnlockArea.lOffset = RESERVED_BYTE;
21181     UnlockArea.lRange = 1L;
21182     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21183     OSTRACE3( "UNLOCK %d reserved res=%d\n", pFile->h, res );
21184   }
21185   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
21186     res = unlockReadLock(pFile);
21187     OSTRACE5( "UNLOCK %d is %d want %d res=%d\n", pFile->h, type, locktype, res );
21188   }
21189   if( type>=PENDING_LOCK ){
21190     LockArea.lOffset = 0L;
21191     LockArea.lRange = 0L;
21192     UnlockArea.lOffset = PENDING_BYTE;
21193     UnlockArea.lRange = 1L;
21194     res = DosSetFileLocks( pFile->h, &UnlockArea, &LockArea, LOCK_TIMEOUT, 0L );
21195     OSTRACE3( "UNLOCK %d pending res=%d\n", pFile->h, res );
21196   }
21197   pFile->locktype = locktype;
21198   OSTRACE3( "UNLOCK %d now %d\n", pFile->h, pFile->locktype );
21199   return rc;
21200 }
21201
21202 /*
21203 ** Control and query of the open file handle.
21204 */
21205 static int os2FileControl(sqlite3_file *id, int op, void *pArg){
21206   switch( op ){
21207     case SQLITE_FCNTL_LOCKSTATE: {
21208       *(int*)pArg = ((os2File*)id)->locktype;
21209       OSTRACE3( "FCNTL_LOCKSTATE %d lock=%d\n", ((os2File*)id)->h, ((os2File*)id)->locktype );
21210       return SQLITE_OK;
21211     }
21212   }
21213   return SQLITE_ERROR;
21214 }
21215
21216 /*
21217 ** Return the sector size in bytes of the underlying block device for
21218 ** the specified file. This is almost always 512 bytes, but may be
21219 ** larger for some devices.
21220 **
21221 ** SQLite code assumes this function cannot fail. It also assumes that
21222 ** if two files are created in the same file-system directory (i.e.
21223 ** a database and its journal file) that the sector size will be the
21224 ** same for both.
21225 */
21226 static int os2SectorSize(sqlite3_file *id){
21227   return SQLITE_DEFAULT_SECTOR_SIZE;
21228 }
21229
21230 /*
21231 ** Return a vector of device characteristics.
21232 */
21233 static int os2DeviceCharacteristics(sqlite3_file *id){
21234   return 0;
21235 }
21236
21237
21238 /*
21239 ** Character set conversion objects used by conversion routines.
21240 */
21241 static UconvObject ucUtf8 = NULL; /* convert between UTF-8 and UCS-2 */
21242 static UconvObject uclCp = NULL;  /* convert between local codepage and UCS-2 */
21243
21244 /*
21245 ** Helper function to initialize the conversion objects from and to UTF-8.
21246 */
21247 static void initUconvObjects( void ){
21248   if( UniCreateUconvObject( UTF_8, &ucUtf8 ) != ULS_SUCCESS )
21249     ucUtf8 = NULL;
21250   if ( UniCreateUconvObject( (UniChar *)L"@path=yes", &uclCp ) != ULS_SUCCESS )
21251     uclCp = NULL;
21252 }
21253
21254 /*
21255 ** Helper function to free the conversion objects from and to UTF-8.
21256 */
21257 static void freeUconvObjects( void ){
21258   if ( ucUtf8 )
21259     UniFreeUconvObject( ucUtf8 );
21260   if ( uclCp )
21261     UniFreeUconvObject( uclCp );
21262   ucUtf8 = NULL;
21263   uclCp = NULL;
21264 }
21265
21266 /*
21267 ** Helper function to convert UTF-8 filenames to local OS/2 codepage.
21268 ** The two-step process: first convert the incoming UTF-8 string
21269 ** into UCS-2 and then from UCS-2 to the current codepage.
21270 ** The returned char pointer has to be freed.
21271 */
21272 static char *convertUtf8PathToCp( const char *in ){
21273   UniChar tempPath[CCHMAXPATH];
21274   char *out = (char *)calloc( CCHMAXPATH, 1 );
21275
21276   if( !out )
21277     return NULL;
21278
21279   if( !ucUtf8 || !uclCp )
21280     initUconvObjects();
21281
21282   /* determine string for the conversion of UTF-8 which is CP1208 */
21283   if( UniStrToUcs( ucUtf8, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
21284     return out; /* if conversion fails, return the empty string */
21285
21286   /* conversion for current codepage which can be used for paths */
21287   UniStrFromUcs( uclCp, out, tempPath, CCHMAXPATH );
21288
21289   return out;
21290 }
21291
21292 /*
21293 ** Helper function to convert filenames from local codepage to UTF-8.
21294 ** The two-step process: first convert the incoming codepage-specific
21295 ** string into UCS-2 and then from UCS-2 to the codepage of UTF-8.
21296 ** The returned char pointer has to be freed.
21297 **
21298 ** This function is non-static to be able to use this in shell.c and
21299 ** similar applications that take command line arguments.
21300 */
21301 char *convertCpPathToUtf8( const char *in ){
21302   UniChar tempPath[CCHMAXPATH];
21303   char *out = (char *)calloc( CCHMAXPATH, 1 );
21304
21305   if( !out )
21306     return NULL;
21307
21308   if( !ucUtf8 || !uclCp )
21309     initUconvObjects();
21310
21311   /* conversion for current codepage which can be used for paths */
21312   if( UniStrToUcs( uclCp, tempPath, (char *)in, CCHMAXPATH ) != ULS_SUCCESS )
21313     return out; /* if conversion fails, return the empty string */
21314
21315   /* determine string for the conversion of UTF-8 which is CP1208 */
21316   UniStrFromUcs( ucUtf8, out, tempPath, CCHMAXPATH );
21317
21318   return out;
21319 }
21320
21321 /*
21322 ** This vector defines all the methods that can operate on an
21323 ** sqlite3_file for os2.
21324 */
21325 static const sqlite3_io_methods os2IoMethod = {
21326   1,                        /* iVersion */
21327   os2Close,
21328   os2Read,
21329   os2Write,
21330   os2Truncate,
21331   os2Sync,
21332   os2FileSize,
21333   os2Lock,
21334   os2Unlock,
21335   os2CheckReservedLock,
21336   os2FileControl,
21337   os2SectorSize,
21338   os2DeviceCharacteristics
21339 };
21340
21341 /***************************************************************************
21342 ** Here ends the I/O methods that form the sqlite3_io_methods object.
21343 **
21344 ** The next block of code implements the VFS methods.
21345 ****************************************************************************/
21346
21347 /*
21348 ** Create a temporary file name in zBuf.  zBuf must be big enough to
21349 ** hold at pVfs->mxPathname characters.
21350 */
21351 static int getTempname(int nBuf, char *zBuf ){
21352   static const unsigned char zChars[] =
21353     "abcdefghijklmnopqrstuvwxyz"
21354     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
21355     "0123456789";
21356   int i, j;
21357   char zTempPathBuf[3];
21358   PSZ zTempPath = (PSZ)&zTempPathBuf;
21359   if( sqlite3_temp_directory ){
21360     zTempPath = sqlite3_temp_directory;
21361   }else{
21362     if( DosScanEnv( (PSZ)"TEMP", &zTempPath ) ){
21363       if( DosScanEnv( (PSZ)"TMP", &zTempPath ) ){
21364         if( DosScanEnv( (PSZ)"TMPDIR", &zTempPath ) ){
21365            ULONG ulDriveNum = 0, ulDriveMap = 0;
21366            DosQueryCurrentDisk( &ulDriveNum, &ulDriveMap );
21367            sprintf( (char*)zTempPath, "%c:", (char)( 'A' + ulDriveNum - 1 ) );
21368         }
21369       }
21370     }
21371   }
21372   /* Strip off a trailing slashes or backslashes, otherwise we would get *
21373    * multiple (back)slashes which causes DosOpen() to fail.              *
21374    * Trailing spaces are not allowed, either.                            */
21375   j = sqlite3Strlen30(zTempPath);
21376   while( j > 0 && ( zTempPath[j-1] == '\\' || zTempPath[j-1] == '/'
21377                     || zTempPath[j-1] == ' ' ) ){
21378     j--;
21379   }
21380   zTempPath[j] = '\0';
21381   if( !sqlite3_temp_directory ){
21382     char *zTempPathUTF = convertCpPathToUtf8( zTempPath );
21383     sqlite3_snprintf( nBuf-30, zBuf,
21384                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPathUTF );
21385     free( zTempPathUTF );
21386   }else{
21387     sqlite3_snprintf( nBuf-30, zBuf,
21388                       "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath );
21389   }
21390   j = sqlite3Strlen30( zBuf );
21391   sqlite3_randomness( 20, &zBuf[j] );
21392   for( i = 0; i < 20; i++, j++ ){
21393     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
21394   }
21395   zBuf[j] = 0;
21396   OSTRACE2( "TEMP FILENAME: %s\n", zBuf );
21397   return SQLITE_OK;
21398 }
21399
21400
21401 /*
21402 ** Turn a relative pathname into a full pathname.  Write the full
21403 ** pathname into zFull[].  zFull[] will be at least pVfs->mxPathname
21404 ** bytes in size.
21405 */
21406 static int os2FullPathname(
21407   sqlite3_vfs *pVfs,          /* Pointer to vfs object */
21408   const char *zRelative,      /* Possibly relative input path */
21409   int nFull,                  /* Size of output buffer in bytes */
21410   char *zFull                 /* Output buffer */
21411 ){
21412   char *zRelativeCp = convertUtf8PathToCp( zRelative );
21413   char zFullCp[CCHMAXPATH] = "\0";
21414   char *zFullUTF;
21415   APIRET rc = DosQueryPathInfo( zRelativeCp, FIL_QUERYFULLNAME, zFullCp,
21416                                 CCHMAXPATH );
21417   free( zRelativeCp );
21418   zFullUTF = convertCpPathToUtf8( zFullCp );
21419   sqlite3_snprintf( nFull, zFull, zFullUTF );
21420   free( zFullUTF );
21421   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR;
21422 }
21423
21424
21425 /*
21426 ** Open a file.
21427 */
21428 static int os2Open(
21429   sqlite3_vfs *pVfs,            /* Not used */
21430   const char *zName,            /* Name of the file */
21431   sqlite3_file *id,             /* Write the SQLite file handle here */
21432   int flags,                    /* Open mode flags */
21433   int *pOutFlags                /* Status return flags */
21434 ){
21435   HFILE h;
21436   ULONG ulFileAttribute = FILE_NORMAL;
21437   ULONG ulOpenFlags = 0;
21438   ULONG ulOpenMode = 0;
21439   os2File *pFile = (os2File*)id;
21440   APIRET rc = NO_ERROR;
21441   ULONG ulAction;
21442   char *zNameCp;
21443   char zTmpname[CCHMAXPATH+1];    /* Buffer to hold name of temp file */
21444
21445   /* If the second argument to this function is NULL, generate a 
21446   ** temporary file name to use 
21447   */
21448   if( !zName ){
21449     int rc = getTempname(CCHMAXPATH+1, zTmpname);
21450     if( rc!=SQLITE_OK ){
21451       return rc;
21452     }
21453     zName = zTmpname;
21454   }
21455
21456
21457   memset( pFile, 0, sizeof(*pFile) );
21458
21459   OSTRACE2( "OPEN want %d\n", flags );
21460
21461   if( flags & SQLITE_OPEN_READWRITE ){
21462     ulOpenMode |= OPEN_ACCESS_READWRITE;
21463     OSTRACE1( "OPEN read/write\n" );
21464   }else{
21465     ulOpenMode |= OPEN_ACCESS_READONLY;
21466     OSTRACE1( "OPEN read only\n" );
21467   }
21468
21469   if( flags & SQLITE_OPEN_CREATE ){
21470     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_CREATE_IF_NEW;
21471     OSTRACE1( "OPEN open new/create\n" );
21472   }else{
21473     ulOpenFlags |= OPEN_ACTION_OPEN_IF_EXISTS | OPEN_ACTION_FAIL_IF_NEW;
21474     OSTRACE1( "OPEN open existing\n" );
21475   }
21476
21477   if( flags & SQLITE_OPEN_MAIN_DB ){
21478     ulOpenMode |= OPEN_SHARE_DENYNONE;
21479     OSTRACE1( "OPEN share read/write\n" );
21480   }else{
21481     ulOpenMode |= OPEN_SHARE_DENYWRITE;
21482     OSTRACE1( "OPEN share read only\n" );
21483   }
21484
21485   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
21486     char pathUtf8[CCHMAXPATH];
21487 #ifdef NDEBUG /* when debugging we want to make sure it is deleted */
21488     ulFileAttribute = FILE_HIDDEN;
21489 #endif
21490     os2FullPathname( pVfs, zName, CCHMAXPATH, pathUtf8 );
21491     pFile->pathToDel = convertUtf8PathToCp( pathUtf8 );
21492     OSTRACE1( "OPEN hidden/delete on close file attributes\n" );
21493   }else{
21494     pFile->pathToDel = NULL;
21495     OSTRACE1( "OPEN normal file attribute\n" );
21496   }
21497
21498   /* always open in random access mode for possibly better speed */
21499   ulOpenMode |= OPEN_FLAGS_RANDOM;
21500   ulOpenMode |= OPEN_FLAGS_FAIL_ON_ERROR;
21501   ulOpenMode |= OPEN_FLAGS_NOINHERIT;
21502
21503   zNameCp = convertUtf8PathToCp( zName );
21504   rc = DosOpen( (PSZ)zNameCp,
21505                 &h,
21506                 &ulAction,
21507                 0L,
21508                 ulFileAttribute,
21509                 ulOpenFlags,
21510                 ulOpenMode,
21511                 (PEAOP2)NULL );
21512   free( zNameCp );
21513   if( rc != NO_ERROR ){
21514     OSTRACE7( "OPEN Invalid handle rc=%d: zName=%s, ulAction=%#lx, ulAttr=%#lx, ulFlags=%#lx, ulMode=%#lx\n",
21515               rc, zName, ulAction, ulFileAttribute, ulOpenFlags, ulOpenMode );
21516     if( pFile->pathToDel )
21517       free( pFile->pathToDel );
21518     pFile->pathToDel = NULL;
21519     if( flags & SQLITE_OPEN_READWRITE ){
21520       OSTRACE2( "OPEN %d Invalid handle\n", ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE) );
21521       return os2Open( pVfs, zName, id,
21522                       ((flags | SQLITE_OPEN_READONLY) & ~SQLITE_OPEN_READWRITE),
21523                       pOutFlags );
21524     }else{
21525       return SQLITE_CANTOPEN;
21526     }
21527   }
21528
21529   if( pOutFlags ){
21530     *pOutFlags = flags & SQLITE_OPEN_READWRITE ? SQLITE_OPEN_READWRITE : SQLITE_OPEN_READONLY;
21531   }
21532
21533   pFile->pMethod = &os2IoMethod;
21534   pFile->h = h;
21535   OpenCounter(+1);
21536   OSTRACE3( "OPEN %d pOutFlags=%d\n", pFile->h, pOutFlags );
21537   return SQLITE_OK;
21538 }
21539
21540 /*
21541 ** Delete the named file.
21542 */
21543 static int os2Delete(
21544   sqlite3_vfs *pVfs,                     /* Not used on os2 */
21545   const char *zFilename,                 /* Name of file to delete */
21546   int syncDir                            /* Not used on os2 */
21547 ){
21548   APIRET rc = NO_ERROR;
21549   char *zFilenameCp = convertUtf8PathToCp( zFilename );
21550   SimulateIOError( return SQLITE_IOERR_DELETE );
21551   rc = DosDelete( (PSZ)zFilenameCp );
21552   free( zFilenameCp );
21553   OSTRACE2( "DELETE \"%s\"\n", zFilename );
21554   return rc == NO_ERROR ? SQLITE_OK : SQLITE_IOERR_DELETE;
21555 }
21556
21557 /*
21558 ** Check the existance and status of a file.
21559 */
21560 static int os2Access(
21561   sqlite3_vfs *pVfs,        /* Not used on os2 */
21562   const char *zFilename,    /* Name of file to check */
21563   int flags,                /* Type of test to make on this file */
21564   int *pOut                 /* Write results here */
21565 ){
21566   FILESTATUS3 fsts3ConfigInfo;
21567   APIRET rc = NO_ERROR;
21568   char *zFilenameCp = convertUtf8PathToCp( zFilename );
21569
21570   memset( &fsts3ConfigInfo, 0, sizeof(fsts3ConfigInfo) );
21571   rc = DosQueryPathInfo( (PSZ)zFilenameCp, FIL_STANDARD,
21572                          &fsts3ConfigInfo, sizeof(FILESTATUS3) );
21573   free( zFilenameCp );
21574   OSTRACE4( "ACCESS fsts3ConfigInfo.attrFile=%d flags=%d rc=%d\n",
21575             fsts3ConfigInfo.attrFile, flags, rc );
21576   switch( flags ){
21577     case SQLITE_ACCESS_READ:
21578     case SQLITE_ACCESS_EXISTS:
21579       rc = (rc == NO_ERROR);
21580       OSTRACE3( "ACCESS %s access of read and exists  rc=%d\n", zFilename, rc );
21581       break;
21582     case SQLITE_ACCESS_READWRITE:
21583       rc = (rc == NO_ERROR) && ( (fsts3ConfigInfo.attrFile & FILE_READONLY) == 0 );
21584       OSTRACE3( "ACCESS %s access of read/write  rc=%d\n", zFilename, rc );
21585       break;
21586     default:
21587       assert( !"Invalid flags argument" );
21588   }
21589   *pOut = rc;
21590   return SQLITE_OK;
21591 }
21592
21593
21594 #ifndef SQLITE_OMIT_LOAD_EXTENSION
21595 /*
21596 ** Interfaces for opening a shared library, finding entry points
21597 ** within the shared library, and closing the shared library.
21598 */
21599 /*
21600 ** Interfaces for opening a shared library, finding entry points
21601 ** within the shared library, and closing the shared library.
21602 */
21603 static void *os2DlOpen(sqlite3_vfs *pVfs, const char *zFilename){
21604   UCHAR loadErr[256];
21605   HMODULE hmod;
21606   APIRET rc;
21607   char *zFilenameCp = convertUtf8PathToCp(zFilename);
21608   rc = DosLoadModule((PSZ)loadErr, sizeof(loadErr), zFilenameCp, &hmod);
21609   free(zFilenameCp);
21610   return rc != NO_ERROR ? 0 : (void*)hmod;
21611 }
21612 /*
21613 ** A no-op since the error code is returned on the DosLoadModule call.
21614 ** os2Dlopen returns zero if DosLoadModule is not successful.
21615 */
21616 static void os2DlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
21617 /* no-op */
21618 }
21619 static void *os2DlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol){
21620   PFN pfn;
21621   APIRET rc;
21622   rc = DosQueryProcAddr((HMODULE)pHandle, 0L, zSymbol, &pfn);
21623   if( rc != NO_ERROR ){
21624     /* if the symbol itself was not found, search again for the same
21625      * symbol with an extra underscore, that might be needed depending
21626      * on the calling convention */
21627     char _zSymbol[256] = "_";
21628     strncat(_zSymbol, zSymbol, 255);
21629     rc = DosQueryProcAddr((HMODULE)pHandle, 0L, _zSymbol, &pfn);
21630   }
21631   return rc != NO_ERROR ? 0 : (void*)pfn;
21632 }
21633 static void os2DlClose(sqlite3_vfs *pVfs, void *pHandle){
21634   DosFreeModule((HMODULE)pHandle);
21635 }
21636 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
21637   #define os2DlOpen 0
21638   #define os2DlError 0
21639   #define os2DlSym 0
21640   #define os2DlClose 0
21641 #endif
21642
21643
21644 /*
21645 ** Write up to nBuf bytes of randomness into zBuf.
21646 */
21647 static int os2Randomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf ){
21648   int n = 0;
21649 #if defined(SQLITE_TEST)
21650   n = nBuf;
21651   memset(zBuf, 0, nBuf);
21652 #else
21653   int sizeofULong = sizeof(ULONG);
21654   if( (int)sizeof(DATETIME) <= nBuf - n ){
21655     DATETIME x;
21656     DosGetDateTime(&x);
21657     memcpy(&zBuf[n], &x, sizeof(x));
21658     n += sizeof(x);
21659   }
21660
21661   if( sizeofULong <= nBuf - n ){
21662     PPIB ppib;
21663     DosGetInfoBlocks(NULL, &ppib);
21664     memcpy(&zBuf[n], &ppib->pib_ulpid, sizeofULong);
21665     n += sizeofULong;
21666   }
21667
21668   if( sizeofULong <= nBuf - n ){
21669     PTIB ptib;
21670     DosGetInfoBlocks(&ptib, NULL);
21671     memcpy(&zBuf[n], &ptib->tib_ptib2->tib2_ultid, sizeofULong);
21672     n += sizeofULong;
21673   }
21674
21675   /* if we still haven't filled the buffer yet the following will */
21676   /* grab everything once instead of making several calls for a single item */
21677   if( sizeofULong <= nBuf - n ){
21678     ULONG ulSysInfo[QSV_MAX];
21679     DosQuerySysInfo(1L, QSV_MAX, ulSysInfo, sizeofULong * QSV_MAX);
21680
21681     memcpy(&zBuf[n], &ulSysInfo[QSV_MS_COUNT - 1], sizeofULong);
21682     n += sizeofULong;
21683
21684     if( sizeofULong <= nBuf - n ){
21685       memcpy(&zBuf[n], &ulSysInfo[QSV_TIMER_INTERVAL - 1], sizeofULong);
21686       n += sizeofULong;
21687     }
21688     if( sizeofULong <= nBuf - n ){
21689       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_LOW - 1], sizeofULong);
21690       n += sizeofULong;
21691     }
21692     if( sizeofULong <= nBuf - n ){
21693       memcpy(&zBuf[n], &ulSysInfo[QSV_TIME_HIGH - 1], sizeofULong);
21694       n += sizeofULong;
21695     }
21696     if( sizeofULong <= nBuf - n ){
21697       memcpy(&zBuf[n], &ulSysInfo[QSV_TOTAVAILMEM - 1], sizeofULong);
21698       n += sizeofULong;
21699     }
21700   }
21701 #endif
21702
21703   return n;
21704 }
21705
21706 /*
21707 ** Sleep for a little while.  Return the amount of time slept.
21708 ** The argument is the number of microseconds we want to sleep.
21709 ** The return value is the number of microseconds of sleep actually
21710 ** requested from the underlying operating system, a number which
21711 ** might be greater than or equal to the argument, but not less
21712 ** than the argument.
21713 */
21714 static int os2Sleep( sqlite3_vfs *pVfs, int microsec ){
21715   DosSleep( (microsec/1000) );
21716   return microsec;
21717 }
21718
21719 /*
21720 ** The following variable, if set to a non-zero value, becomes the result
21721 ** returned from sqlite3OsCurrentTime().  This is used for testing.
21722 */
21723 #ifdef SQLITE_TEST
21724 SQLITE_API int sqlite3_current_time = 0;
21725 #endif
21726
21727 /*
21728 ** Find the current time (in Universal Coordinated Time).  Write the
21729 ** current time and date as a Julian Day number into *prNow and
21730 ** return 0.  Return 1 if the time and date cannot be found.
21731 */
21732 int os2CurrentTime( sqlite3_vfs *pVfs, double *prNow ){
21733   double now;
21734   SHORT minute; /* needs to be able to cope with negative timezone offset */
21735   USHORT second, hour,
21736          day, month, year;
21737   DATETIME dt;
21738   DosGetDateTime( &dt );
21739   second = (USHORT)dt.seconds;
21740   minute = (SHORT)dt.minutes + dt.timezone;
21741   hour = (USHORT)dt.hours;
21742   day = (USHORT)dt.day;
21743   month = (USHORT)dt.month;
21744   year = (USHORT)dt.year;
21745
21746   /* Calculations from http://www.astro.keele.ac.uk/~rno/Astronomy/hjd.html
21747      http://www.astro.keele.ac.uk/~rno/Astronomy/hjd-0.1.c */
21748   /* Calculate the Julian days */
21749   now = day - 32076 +
21750     1461*(year + 4800 + (month - 14)/12)/4 +
21751     367*(month - 2 - (month - 14)/12*12)/12 -
21752     3*((year + 4900 + (month - 14)/12)/100)/4;
21753
21754   /* Add the fractional hours, mins and seconds */
21755   now += (hour + 12.0)/24.0;
21756   now += minute/1440.0;
21757   now += second/86400.0;
21758   *prNow = now;
21759 #ifdef SQLITE_TEST
21760   if( sqlite3_current_time ){
21761     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
21762   }
21763 #endif
21764   return 0;
21765 }
21766
21767 static int os2GetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
21768   return 0;
21769 }
21770
21771 /*
21772 ** Initialize and deinitialize the operating system interface.
21773 */
21774 SQLITE_API int sqlite3_os_init(void){
21775   static sqlite3_vfs os2Vfs = {
21776     1,                 /* iVersion */
21777     sizeof(os2File),   /* szOsFile */
21778     CCHMAXPATH,        /* mxPathname */
21779     0,                 /* pNext */
21780     "os2",             /* zName */
21781     0,                 /* pAppData */
21782
21783     os2Open,           /* xOpen */
21784     os2Delete,         /* xDelete */
21785     os2Access,         /* xAccess */
21786     os2FullPathname,   /* xFullPathname */
21787     os2DlOpen,         /* xDlOpen */
21788     os2DlError,        /* xDlError */
21789     os2DlSym,          /* xDlSym */
21790     os2DlClose,        /* xDlClose */
21791     os2Randomness,     /* xRandomness */
21792     os2Sleep,          /* xSleep */
21793     os2CurrentTime,    /* xCurrentTime */
21794     os2GetLastError    /* xGetLastError */
21795   };
21796   sqlite3_vfs_register(&os2Vfs, 1);
21797   initUconvObjects();
21798   return SQLITE_OK;
21799 }
21800 SQLITE_API int sqlite3_os_end(void){
21801   freeUconvObjects();
21802   return SQLITE_OK;
21803 }
21804
21805 #endif /* SQLITE_OS_OS2 */
21806
21807 /************** End of os_os2.c **********************************************/
21808 /************** Begin file os_unix.c *****************************************/
21809 /*
21810 ** 2004 May 22
21811 **
21812 ** The author disclaims copyright to this source code.  In place of
21813 ** a legal notice, here is a blessing:
21814 **
21815 **    May you do good and not evil.
21816 **    May you find forgiveness for yourself and forgive others.
21817 **    May you share freely, never taking more than you give.
21818 **
21819 ******************************************************************************
21820 **
21821 ** This file contains the VFS implementation for unix-like operating systems
21822 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
21823 **
21824 ** There are actually several different VFS implementations in this file.
21825 ** The differences are in the way that file locking is done.  The default
21826 ** implementation uses Posix Advisory Locks.  Alternative implementations
21827 ** use flock(), dot-files, various proprietary locking schemas, or simply
21828 ** skip locking all together.
21829 **
21830 ** This source file is organized into divisions where the logic for various
21831 ** subfunctions is contained within the appropriate division.  PLEASE
21832 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
21833 ** in the correct division and should be clearly labeled.
21834 **
21835 ** The layout of divisions is as follows:
21836 **
21837 **   *  General-purpose declarations and utility functions.
21838 **   *  Unique file ID logic used by VxWorks.
21839 **   *  Various locking primitive implementations (all except proxy locking):
21840 **      + for Posix Advisory Locks
21841 **      + for no-op locks
21842 **      + for dot-file locks
21843 **      + for flock() locking
21844 **      + for named semaphore locks (VxWorks only)
21845 **      + for AFP filesystem locks (MacOSX only)
21846 **   *  sqlite3_file methods not associated with locking.
21847 **   *  Definitions of sqlite3_io_methods objects for all locking
21848 **      methods plus "finder" functions for each locking method.
21849 **   *  sqlite3_vfs method implementations.
21850 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
21851 **   *  Definitions of sqlite3_vfs objects for all locking methods
21852 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
21853 */
21854 #if SQLITE_OS_UNIX              /* This file is used on unix only */
21855
21856 /*
21857 ** There are various methods for file locking used for concurrency
21858 ** control:
21859 **
21860 **   1. POSIX locking (the default),
21861 **   2. No locking,
21862 **   3. Dot-file locking,
21863 **   4. flock() locking,
21864 **   5. AFP locking (OSX only),
21865 **   6. Named POSIX semaphores (VXWorks only),
21866 **   7. proxy locking. (OSX only)
21867 **
21868 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
21869 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
21870 ** selection of the appropriate locking style based on the filesystem
21871 ** where the database is located.  
21872 */
21873 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
21874 #  if defined(__APPLE__)
21875 #    define SQLITE_ENABLE_LOCKING_STYLE 1
21876 #  else
21877 #    define SQLITE_ENABLE_LOCKING_STYLE 0
21878 #  endif
21879 #endif
21880
21881 /*
21882 ** Define the OS_VXWORKS pre-processor macro to 1 if building on 
21883 ** vxworks, or 0 otherwise.
21884 */
21885 #ifndef OS_VXWORKS
21886 #  if defined(__RTP__) || defined(_WRS_KERNEL)
21887 #    define OS_VXWORKS 1
21888 #  else
21889 #    define OS_VXWORKS 0
21890 #  endif
21891 #endif
21892
21893 /*
21894 ** These #defines should enable >2GB file support on Posix if the
21895 ** underlying operating system supports it.  If the OS lacks
21896 ** large file support, these should be no-ops.
21897 **
21898 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
21899 ** on the compiler command line.  This is necessary if you are compiling
21900 ** on a recent machine (ex: RedHat 7.2) but you want your code to work
21901 ** on an older machine (ex: RedHat 6.0).  If you compile on RedHat 7.2
21902 ** without this option, LFS is enable.  But LFS does not exist in the kernel
21903 ** in RedHat 6.0, so the code won't work.  Hence, for maximum binary
21904 ** portability you should omit LFS.
21905 **
21906 ** The previous paragraph was written in 2005.  (This paragraph is written
21907 ** on 2008-11-28.) These days, all Linux kernels support large files, so
21908 ** you should probably leave LFS enabled.  But some embedded platforms might
21909 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
21910 */
21911 #ifndef SQLITE_DISABLE_LFS
21912 # define _LARGE_FILE       1
21913 # ifndef _FILE_OFFSET_BITS
21914 #   define _FILE_OFFSET_BITS 64
21915 # endif
21916 # define _LARGEFILE_SOURCE 1
21917 #endif
21918
21919 /*
21920 ** standard include files.
21921 */
21922 #include <sys/types.h>
21923 #include <sys/stat.h>
21924 #include <fcntl.h>
21925 #include <unistd.h>
21926 #include <sys/time.h>
21927 #include <errno.h>
21928
21929 #if SQLITE_ENABLE_LOCKING_STYLE
21930 # include <sys/ioctl.h>
21931 # if OS_VXWORKS
21932 #  include <semaphore.h>
21933 #  include <limits.h>
21934 # else
21935 #  include <sys/file.h>
21936 #  include <sys/param.h>
21937 # endif
21938 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
21939
21940 #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
21941 # include <sys/mount.h>
21942 #endif
21943
21944 /*
21945 ** Allowed values of unixFile.fsFlags
21946 */
21947 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
21948
21949 /*
21950 ** If we are to be thread-safe, include the pthreads header and define
21951 ** the SQLITE_UNIX_THREADS macro.
21952 */
21953 #if SQLITE_THREADSAFE
21954 # define SQLITE_UNIX_THREADS 1
21955 #endif
21956
21957 /*
21958 ** Default permissions when creating a new file
21959 */
21960 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
21961 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
21962 #endif
21963
21964 /*
21965  ** Default permissions when creating auto proxy dir
21966  */
21967 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
21968 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
21969 #endif
21970
21971 /*
21972 ** Maximum supported path-length.
21973 */
21974 #define MAX_PATHNAME 512
21975
21976 /*
21977 ** Only set the lastErrno if the error code is a real error and not 
21978 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
21979 */
21980 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
21981
21982
21983 /*
21984 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
21985 ** cannot be closed immediately. In these cases, instances of the following
21986 ** structure are used to store the file descriptor while waiting for an
21987 ** opportunity to either close or reuse it.
21988 */
21989 typedef struct UnixUnusedFd UnixUnusedFd;
21990 struct UnixUnusedFd {
21991   int fd;                   /* File descriptor to close */
21992   int flags;                /* Flags this file descriptor was opened with */
21993   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
21994 };
21995
21996 /*
21997 ** The unixFile structure is subclass of sqlite3_file specific to the unix
21998 ** VFS implementations.
21999 */
22000 typedef struct unixFile unixFile;
22001 struct unixFile {
22002   sqlite3_io_methods const *pMethod;  /* Always the first entry */
22003   struct unixOpenCnt *pOpen;       /* Info about all open fd's on this inode */
22004   struct unixLockInfo *pLock;      /* Info about locks on this inode */
22005   int h;                           /* The file descriptor */
22006   int dirfd;                       /* File descriptor for the directory */
22007   unsigned char locktype;          /* The type of lock held on this fd */
22008   int lastErrno;                   /* The unix errno from the last I/O error */
22009   void *lockingContext;            /* Locking style specific state */
22010   UnixUnusedFd *pUnused;           /* Pre-allocated UnixUnusedFd */
22011   int fileFlags;                   /* Miscellanous flags */
22012 #if SQLITE_ENABLE_LOCKING_STYLE
22013   int openFlags;                   /* The flags specified at open() */
22014 #endif
22015 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
22016   unsigned fsFlags;                 /* cached details from statfs() */
22017 #endif
22018 #if SQLITE_THREADSAFE && defined(__linux__)
22019   pthread_t tid;                   /* The thread that "owns" this unixFile */
22020 #endif
22021 #if OS_VXWORKS
22022   int isDelete;                    /* Delete on close if true */
22023   struct vxworksFileId *pId;       /* Unique file ID */
22024 #endif
22025 #ifndef NDEBUG
22026   /* The next group of variables are used to track whether or not the
22027   ** transaction counter in bytes 24-27 of database files are updated
22028   ** whenever any part of the database changes.  An assertion fault will
22029   ** occur if a file is updated without also updating the transaction
22030   ** counter.  This test is made to avoid new problems similar to the
22031   ** one described by ticket #3584. 
22032   */
22033   unsigned char transCntrChng;   /* True if the transaction counter changed */
22034   unsigned char dbUpdate;        /* True if any part of database file changed */
22035   unsigned char inNormalWrite;   /* True if in a normal write operation */
22036 #endif
22037 #ifdef SQLITE_TEST
22038   /* In test mode, increase the size of this structure a bit so that 
22039   ** it is larger than the struct CrashFile defined in test6.c.
22040   */
22041   char aPadding[32];
22042 #endif
22043 };
22044
22045 /*
22046 ** The following macros define bits in unixFile.fileFlags
22047 */
22048 #define SQLITE_WHOLE_FILE_LOCKING  0x0001   /* Use whole-file locking */
22049
22050 /*
22051 ** Include code that is common to all os_*.c files
22052 */
22053 /************** Include os_common.h in the middle of os_unix.c ***************/
22054 /************** Begin file os_common.h ***************************************/
22055 /*
22056 ** 2004 May 22
22057 **
22058 ** The author disclaims copyright to this source code.  In place of
22059 ** a legal notice, here is a blessing:
22060 **
22061 **    May you do good and not evil.
22062 **    May you find forgiveness for yourself and forgive others.
22063 **    May you share freely, never taking more than you give.
22064 **
22065 ******************************************************************************
22066 **
22067 ** This file contains macros and a little bit of code that is common to
22068 ** all of the platform-specific files (os_*.c) and is #included into those
22069 ** files.
22070 **
22071 ** This file should be #included by the os_*.c files only.  It is not a
22072 ** general purpose header file.
22073 */
22074 #ifndef _OS_COMMON_H_
22075 #define _OS_COMMON_H_
22076
22077 /*
22078 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
22079 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
22080 ** switch.  The following code should catch this problem at compile-time.
22081 */
22082 #ifdef MEMORY_DEBUG
22083 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
22084 #endif
22085
22086 #ifdef SQLITE_DEBUG
22087 SQLITE_PRIVATE int sqlite3OSTrace = 0;
22088 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
22089 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
22090 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
22091 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
22092 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
22093 #define OSTRACE6(X,Y,Z,A,B,C) \
22094     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
22095 #define OSTRACE7(X,Y,Z,A,B,C,D) \
22096     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
22097 #else
22098 #define OSTRACE1(X)
22099 #define OSTRACE2(X,Y)
22100 #define OSTRACE3(X,Y,Z)
22101 #define OSTRACE4(X,Y,Z,A)
22102 #define OSTRACE5(X,Y,Z,A,B)
22103 #define OSTRACE6(X,Y,Z,A,B,C)
22104 #define OSTRACE7(X,Y,Z,A,B,C,D)
22105 #endif
22106
22107 /*
22108 ** Macros for performance tracing.  Normally turned off.  Only works
22109 ** on i486 hardware.
22110 */
22111 #ifdef SQLITE_PERFORMANCE_TRACE
22112
22113 /* 
22114 ** hwtime.h contains inline assembler code for implementing 
22115 ** high-performance timing routines.
22116 */
22117 /************** Include hwtime.h in the middle of os_common.h ****************/
22118 /************** Begin file hwtime.h ******************************************/
22119 /*
22120 ** 2008 May 27
22121 **
22122 ** The author disclaims copyright to this source code.  In place of
22123 ** a legal notice, here is a blessing:
22124 **
22125 **    May you do good and not evil.
22126 **    May you find forgiveness for yourself and forgive others.
22127 **    May you share freely, never taking more than you give.
22128 **
22129 ******************************************************************************
22130 **
22131 ** This file contains inline asm code for retrieving "high-performance"
22132 ** counters for x86 class CPUs.
22133 */
22134 #ifndef _HWTIME_H_
22135 #define _HWTIME_H_
22136
22137 /*
22138 ** The following routine only works on pentium-class (or newer) processors.
22139 ** It uses the RDTSC opcode to read the cycle count value out of the
22140 ** processor and returns that value.  This can be used for high-res
22141 ** profiling.
22142 */
22143 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
22144       (defined(i386) || defined(__i386__) || defined(_M_IX86))
22145
22146   #if defined(__GNUC__)
22147
22148   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22149      unsigned int lo, hi;
22150      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
22151      return (sqlite_uint64)hi << 32 | lo;
22152   }
22153
22154   #elif defined(_MSC_VER)
22155
22156   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
22157      __asm {
22158         rdtsc
22159         ret       ; return value at EDX:EAX
22160      }
22161   }
22162
22163   #endif
22164
22165 #elif (defined(__GNUC__) && defined(__x86_64__))
22166
22167   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22168       unsigned long val;
22169       __asm__ __volatile__ ("rdtsc" : "=A" (val));
22170       return val;
22171   }
22172  
22173 #elif (defined(__GNUC__) && defined(__ppc__))
22174
22175   __inline__ sqlite_uint64 sqlite3Hwtime(void){
22176       unsigned long long retval;
22177       unsigned long junk;
22178       __asm__ __volatile__ ("\n\
22179           1:      mftbu   %1\n\
22180                   mftb    %L0\n\
22181                   mftbu   %0\n\
22182                   cmpw    %0,%1\n\
22183                   bne     1b"
22184                   : "=r" (retval), "=r" (junk));
22185       return retval;
22186   }
22187
22188 #else
22189
22190   #error Need implementation of sqlite3Hwtime() for your platform.
22191
22192   /*
22193   ** To compile without implementing sqlite3Hwtime() for your platform,
22194   ** you can remove the above #error and use the following
22195   ** stub function.  You will lose timing support for many
22196   ** of the debugging and testing utilities, but it should at
22197   ** least compile and run.
22198   */
22199 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
22200
22201 #endif
22202
22203 #endif /* !defined(_HWTIME_H_) */
22204
22205 /************** End of hwtime.h **********************************************/
22206 /************** Continuing where we left off in os_common.h ******************/
22207
22208 static sqlite_uint64 g_start;
22209 static sqlite_uint64 g_elapsed;
22210 #define TIMER_START       g_start=sqlite3Hwtime()
22211 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
22212 #define TIMER_ELAPSED     g_elapsed
22213 #else
22214 #define TIMER_START
22215 #define TIMER_END
22216 #define TIMER_ELAPSED     ((sqlite_uint64)0)
22217 #endif
22218
22219 /*
22220 ** If we compile with the SQLITE_TEST macro set, then the following block
22221 ** of code will give us the ability to simulate a disk I/O error.  This
22222 ** is used for testing the I/O recovery logic.
22223 */
22224 #ifdef SQLITE_TEST
22225 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
22226 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
22227 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
22228 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
22229 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
22230 SQLITE_API int sqlite3_diskfull_pending = 0;
22231 SQLITE_API int sqlite3_diskfull = 0;
22232 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
22233 #define SimulateIOError(CODE)  \
22234   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
22235        || sqlite3_io_error_pending-- == 1 )  \
22236               { local_ioerr(); CODE; }
22237 static void local_ioerr(){
22238   IOTRACE(("IOERR\n"));
22239   sqlite3_io_error_hit++;
22240   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
22241 }
22242 #define SimulateDiskfullError(CODE) \
22243    if( sqlite3_diskfull_pending ){ \
22244      if( sqlite3_diskfull_pending == 1 ){ \
22245        local_ioerr(); \
22246        sqlite3_diskfull = 1; \
22247        sqlite3_io_error_hit = 1; \
22248        CODE; \
22249      }else{ \
22250        sqlite3_diskfull_pending--; \
22251      } \
22252    }
22253 #else
22254 #define SimulateIOErrorBenign(X)
22255 #define SimulateIOError(A)
22256 #define SimulateDiskfullError(A)
22257 #endif
22258
22259 /*
22260 ** When testing, keep a count of the number of open files.
22261 */
22262 #ifdef SQLITE_TEST
22263 SQLITE_API int sqlite3_open_file_count = 0;
22264 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
22265 #else
22266 #define OpenCounter(X)
22267 #endif
22268
22269 #endif /* !defined(_OS_COMMON_H_) */
22270
22271 /************** End of os_common.h *******************************************/
22272 /************** Continuing where we left off in os_unix.c ********************/
22273
22274 /*
22275 ** Define various macros that are missing from some systems.
22276 */
22277 #ifndef O_LARGEFILE
22278 # define O_LARGEFILE 0
22279 #endif
22280 #ifdef SQLITE_DISABLE_LFS
22281 # undef O_LARGEFILE
22282 # define O_LARGEFILE 0
22283 #endif
22284 #ifndef O_NOFOLLOW
22285 # define O_NOFOLLOW 0
22286 #endif
22287 #ifndef O_BINARY
22288 # define O_BINARY 0
22289 #endif
22290
22291 /*
22292 ** The DJGPP compiler environment looks mostly like Unix, but it
22293 ** lacks the fcntl() system call.  So redefine fcntl() to be something
22294 ** that always succeeds.  This means that locking does not occur under
22295 ** DJGPP.  But it is DOS - what did you expect?
22296 */
22297 #ifdef __DJGPP__
22298 # define fcntl(A,B,C) 0
22299 #endif
22300
22301 /*
22302 ** The threadid macro resolves to the thread-id or to 0.  Used for
22303 ** testing and debugging only.
22304 */
22305 #if SQLITE_THREADSAFE
22306 #define threadid pthread_self()
22307 #else
22308 #define threadid 0
22309 #endif
22310
22311
22312 /*
22313 ** Helper functions to obtain and relinquish the global mutex. The
22314 ** global mutex is used to protect the unixOpenCnt, unixLockInfo and
22315 ** vxworksFileId objects used by this file, all of which may be 
22316 ** shared by multiple threads.
22317 **
22318 ** Function unixMutexHeld() is used to assert() that the global mutex 
22319 ** is held when required. This function is only used as part of assert() 
22320 ** statements. e.g.
22321 **
22322 **   unixEnterMutex()
22323 **     assert( unixMutexHeld() );
22324 **   unixEnterLeave()
22325 */
22326 static void unixEnterMutex(void){
22327   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22328 }
22329 static void unixLeaveMutex(void){
22330   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22331 }
22332 #ifdef SQLITE_DEBUG
22333 static int unixMutexHeld(void) {
22334   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
22335 }
22336 #endif
22337
22338
22339 #ifdef SQLITE_DEBUG
22340 /*
22341 ** Helper function for printing out trace information from debugging
22342 ** binaries. This returns the string represetation of the supplied
22343 ** integer lock-type.
22344 */
22345 static const char *locktypeName(int locktype){
22346   switch( locktype ){
22347     case NO_LOCK: return "NONE";
22348     case SHARED_LOCK: return "SHARED";
22349     case RESERVED_LOCK: return "RESERVED";
22350     case PENDING_LOCK: return "PENDING";
22351     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
22352   }
22353   return "ERROR";
22354 }
22355 #endif
22356
22357 #ifdef SQLITE_LOCK_TRACE
22358 /*
22359 ** Print out information about all locking operations.
22360 **
22361 ** This routine is used for troubleshooting locks on multithreaded
22362 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
22363 ** command-line option on the compiler.  This code is normally
22364 ** turned off.
22365 */
22366 static int lockTrace(int fd, int op, struct flock *p){
22367   char *zOpName, *zType;
22368   int s;
22369   int savedErrno;
22370   if( op==F_GETLK ){
22371     zOpName = "GETLK";
22372   }else if( op==F_SETLK ){
22373     zOpName = "SETLK";
22374   }else{
22375     s = fcntl(fd, op, p);
22376     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
22377     return s;
22378   }
22379   if( p->l_type==F_RDLCK ){
22380     zType = "RDLCK";
22381   }else if( p->l_type==F_WRLCK ){
22382     zType = "WRLCK";
22383   }else if( p->l_type==F_UNLCK ){
22384     zType = "UNLCK";
22385   }else{
22386     assert( 0 );
22387   }
22388   assert( p->l_whence==SEEK_SET );
22389   s = fcntl(fd, op, p);
22390   savedErrno = errno;
22391   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
22392      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
22393      (int)p->l_pid, s);
22394   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
22395     struct flock l2;
22396     l2 = *p;
22397     fcntl(fd, F_GETLK, &l2);
22398     if( l2.l_type==F_RDLCK ){
22399       zType = "RDLCK";
22400     }else if( l2.l_type==F_WRLCK ){
22401       zType = "WRLCK";
22402     }else if( l2.l_type==F_UNLCK ){
22403       zType = "UNLCK";
22404     }else{
22405       assert( 0 );
22406     }
22407     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
22408        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
22409   }
22410   errno = savedErrno;
22411   return s;
22412 }
22413 #define fcntl lockTrace
22414 #endif /* SQLITE_LOCK_TRACE */
22415
22416
22417
22418 /*
22419 ** This routine translates a standard POSIX errno code into something
22420 ** useful to the clients of the sqlite3 functions.  Specifically, it is
22421 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
22422 ** and a variety of "please close the file descriptor NOW" errors into 
22423 ** SQLITE_IOERR
22424 ** 
22425 ** Errors during initialization of locks, or file system support for locks,
22426 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
22427 */
22428 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
22429   switch (posixError) {
22430   case 0: 
22431     return SQLITE_OK;
22432     
22433   case EAGAIN:
22434   case ETIMEDOUT:
22435   case EBUSY:
22436   case EINTR:
22437   case ENOLCK:  
22438     /* random NFS retry error, unless during file system support 
22439      * introspection, in which it actually means what it says */
22440     return SQLITE_BUSY;
22441     
22442   case EACCES: 
22443     /* EACCES is like EAGAIN during locking operations, but not any other time*/
22444     if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
22445         (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
22446         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
22447         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
22448       return SQLITE_BUSY;
22449     }
22450     /* else fall through */
22451   case EPERM: 
22452     return SQLITE_PERM;
22453     
22454   case EDEADLK:
22455     return SQLITE_IOERR_BLOCKED;
22456     
22457 #if EOPNOTSUPP!=ENOTSUP
22458   case EOPNOTSUPP: 
22459     /* something went terribly awry, unless during file system support 
22460      * introspection, in which it actually means what it says */
22461 #endif
22462 #ifdef ENOTSUP
22463   case ENOTSUP: 
22464     /* invalid fd, unless during file system support introspection, in which 
22465      * it actually means what it says */
22466 #endif
22467   case EIO:
22468   case EBADF:
22469   case EINVAL:
22470   case ENOTCONN:
22471   case ENODEV:
22472   case ENXIO:
22473   case ENOENT:
22474   case ESTALE:
22475   case ENOSYS:
22476     /* these should force the client to close the file and reconnect */
22477     
22478   default: 
22479     return sqliteIOErr;
22480   }
22481 }
22482
22483
22484
22485 /******************************************************************************
22486 ****************** Begin Unique File ID Utility Used By VxWorks ***************
22487 **
22488 ** On most versions of unix, we can get a unique ID for a file by concatenating
22489 ** the device number and the inode number.  But this does not work on VxWorks.
22490 ** On VxWorks, a unique file id must be based on the canonical filename.
22491 **
22492 ** A pointer to an instance of the following structure can be used as a
22493 ** unique file ID in VxWorks.  Each instance of this structure contains
22494 ** a copy of the canonical filename.  There is also a reference count.  
22495 ** The structure is reclaimed when the number of pointers to it drops to
22496 ** zero.
22497 **
22498 ** There are never very many files open at one time and lookups are not
22499 ** a performance-critical path, so it is sufficient to put these
22500 ** structures on a linked list.
22501 */
22502 struct vxworksFileId {
22503   struct vxworksFileId *pNext;  /* Next in a list of them all */
22504   int nRef;                     /* Number of references to this one */
22505   int nName;                    /* Length of the zCanonicalName[] string */
22506   char *zCanonicalName;         /* Canonical filename */
22507 };
22508
22509 #if OS_VXWORKS
22510 /* 
22511 ** All unique filenames are held on a linked list headed by this
22512 ** variable:
22513 */
22514 static struct vxworksFileId *vxworksFileList = 0;
22515
22516 /*
22517 ** Simplify a filename into its canonical form
22518 ** by making the following changes:
22519 **
22520 **  * removing any trailing and duplicate /
22521 **  * convert /./ into just /
22522 **  * convert /A/../ where A is any simple name into just /
22523 **
22524 ** Changes are made in-place.  Return the new name length.
22525 **
22526 ** The original filename is in z[0..n-1].  Return the number of
22527 ** characters in the simplified name.
22528 */
22529 static int vxworksSimplifyName(char *z, int n){
22530   int i, j;
22531   while( n>1 && z[n-1]=='/' ){ n--; }
22532   for(i=j=0; i<n; i++){
22533     if( z[i]=='/' ){
22534       if( z[i+1]=='/' ) continue;
22535       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
22536         i += 1;
22537         continue;
22538       }
22539       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
22540         while( j>0 && z[j-1]!='/' ){ j--; }
22541         if( j>0 ){ j--; }
22542         i += 2;
22543         continue;
22544       }
22545     }
22546     z[j++] = z[i];
22547   }
22548   z[j] = 0;
22549   return j;
22550 }
22551
22552 /*
22553 ** Find a unique file ID for the given absolute pathname.  Return
22554 ** a pointer to the vxworksFileId object.  This pointer is the unique
22555 ** file ID.
22556 **
22557 ** The nRef field of the vxworksFileId object is incremented before
22558 ** the object is returned.  A new vxworksFileId object is created
22559 ** and added to the global list if necessary.
22560 **
22561 ** If a memory allocation error occurs, return NULL.
22562 */
22563 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
22564   struct vxworksFileId *pNew;         /* search key and new file ID */
22565   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
22566   int n;                              /* Length of zAbsoluteName string */
22567
22568   assert( zAbsoluteName[0]=='/' );
22569   n = (int)strlen(zAbsoluteName);
22570   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
22571   if( pNew==0 ) return 0;
22572   pNew->zCanonicalName = (char*)&pNew[1];
22573   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
22574   n = vxworksSimplifyName(pNew->zCanonicalName, n);
22575
22576   /* Search for an existing entry that matching the canonical name.
22577   ** If found, increment the reference count and return a pointer to
22578   ** the existing file ID.
22579   */
22580   unixEnterMutex();
22581   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
22582     if( pCandidate->nName==n 
22583      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
22584     ){
22585        sqlite3_free(pNew);
22586        pCandidate->nRef++;
22587        unixLeaveMutex();
22588        return pCandidate;
22589     }
22590   }
22591
22592   /* No match was found.  We will make a new file ID */
22593   pNew->nRef = 1;
22594   pNew->nName = n;
22595   pNew->pNext = vxworksFileList;
22596   vxworksFileList = pNew;
22597   unixLeaveMutex();
22598   return pNew;
22599 }
22600
22601 /*
22602 ** Decrement the reference count on a vxworksFileId object.  Free
22603 ** the object when the reference count reaches zero.
22604 */
22605 static void vxworksReleaseFileId(struct vxworksFileId *pId){
22606   unixEnterMutex();
22607   assert( pId->nRef>0 );
22608   pId->nRef--;
22609   if( pId->nRef==0 ){
22610     struct vxworksFileId **pp;
22611     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
22612     assert( *pp==pId );
22613     *pp = pId->pNext;
22614     sqlite3_free(pId);
22615   }
22616   unixLeaveMutex();
22617 }
22618 #endif /* OS_VXWORKS */
22619 /*************** End of Unique File ID Utility Used By VxWorks ****************
22620 ******************************************************************************/
22621
22622
22623 /******************************************************************************
22624 *************************** Posix Advisory Locking ****************************
22625 **
22626 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
22627 ** section 6.5.2.2 lines 483 through 490 specify that when a process
22628 ** sets or clears a lock, that operation overrides any prior locks set
22629 ** by the same process.  It does not explicitly say so, but this implies
22630 ** that it overrides locks set by the same process using a different
22631 ** file descriptor.  Consider this test case:
22632 **
22633 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
22634 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
22635 **
22636 ** Suppose ./file1 and ./file2 are really the same file (because
22637 ** one is a hard or symbolic link to the other) then if you set
22638 ** an exclusive lock on fd1, then try to get an exclusive lock
22639 ** on fd2, it works.  I would have expected the second lock to
22640 ** fail since there was already a lock on the file due to fd1.
22641 ** But not so.  Since both locks came from the same process, the
22642 ** second overrides the first, even though they were on different
22643 ** file descriptors opened on different file names.
22644 **
22645 ** This means that we cannot use POSIX locks to synchronize file access
22646 ** among competing threads of the same process.  POSIX locks will work fine
22647 ** to synchronize access for threads in separate processes, but not
22648 ** threads within the same process.
22649 **
22650 ** To work around the problem, SQLite has to manage file locks internally
22651 ** on its own.  Whenever a new database is opened, we have to find the
22652 ** specific inode of the database file (the inode is determined by the
22653 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
22654 ** and check for locks already existing on that inode.  When locks are
22655 ** created or removed, we have to look at our own internal record of the
22656 ** locks to see if another thread has previously set a lock on that same
22657 ** inode.
22658 **
22659 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
22660 ** For VxWorks, we have to use the alternative unique ID system based on
22661 ** canonical filename and implemented in the previous division.)
22662 **
22663 ** The sqlite3_file structure for POSIX is no longer just an integer file
22664 ** descriptor.  It is now a structure that holds the integer file
22665 ** descriptor and a pointer to a structure that describes the internal
22666 ** locks on the corresponding inode.  There is one locking structure
22667 ** per inode, so if the same inode is opened twice, both unixFile structures
22668 ** point to the same locking structure.  The locking structure keeps
22669 ** a reference count (so we will know when to delete it) and a "cnt"
22670 ** field that tells us its internal lock status.  cnt==0 means the
22671 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
22672 ** cnt>0 means there are cnt shared locks on the file.
22673 **
22674 ** Any attempt to lock or unlock a file first checks the locking
22675 ** structure.  The fcntl() system call is only invoked to set a 
22676 ** POSIX lock if the internal lock structure transitions between
22677 ** a locked and an unlocked state.
22678 **
22679 ** But wait:  there are yet more problems with POSIX advisory locks.
22680 **
22681 ** If you close a file descriptor that points to a file that has locks,
22682 ** all locks on that file that are owned by the current process are
22683 ** released.  To work around this problem, each unixFile structure contains
22684 ** a pointer to an unixOpenCnt structure.  There is one unixOpenCnt structure
22685 ** per open inode, which means that multiple unixFile can point to a single
22686 ** unixOpenCnt.  When an attempt is made to close an unixFile, if there are
22687 ** other unixFile open on the same inode that are holding locks, the call
22688 ** to close() the file descriptor is deferred until all of the locks clear.
22689 ** The unixOpenCnt structure keeps a list of file descriptors that need to
22690 ** be closed and that list is walked (and cleared) when the last lock
22691 ** clears.
22692 **
22693 ** Yet another problem:  LinuxThreads do not play well with posix locks.
22694 **
22695 ** Many older versions of linux use the LinuxThreads library which is
22696 ** not posix compliant.  Under LinuxThreads, a lock created by thread
22697 ** A cannot be modified or overridden by a different thread B.
22698 ** Only thread A can modify the lock.  Locking behavior is correct
22699 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
22700 ** on linux - with NPTL a lock created by thread A can override locks
22701 ** in thread B.  But there is no way to know at compile-time which
22702 ** threading library is being used.  So there is no way to know at
22703 ** compile-time whether or not thread A can override locks on thread B.
22704 ** We have to do a run-time check to discover the behavior of the
22705 ** current process.
22706 **
22707 ** On systems where thread A is unable to modify locks created by
22708 ** thread B, we have to keep track of which thread created each
22709 ** lock.  Hence there is an extra field in the key to the unixLockInfo
22710 ** structure to record this information.  And on those systems it
22711 ** is illegal to begin a transaction in one thread and finish it
22712 ** in another.  For this latter restriction, there is no work-around.
22713 ** It is a limitation of LinuxThreads.
22714 */
22715
22716 /*
22717 ** Set or check the unixFile.tid field.  This field is set when an unixFile
22718 ** is first opened.  All subsequent uses of the unixFile verify that the
22719 ** same thread is operating on the unixFile.  Some operating systems do
22720 ** not allow locks to be overridden by other threads and that restriction
22721 ** means that sqlite3* database handles cannot be moved from one thread
22722 ** to another while locks are held.
22723 **
22724 ** Version 3.3.1 (2006-01-15):  unixFile can be moved from one thread to
22725 ** another as long as we are running on a system that supports threads
22726 ** overriding each others locks (which is now the most common behavior)
22727 ** or if no locks are held.  But the unixFile.pLock field needs to be
22728 ** recomputed because its key includes the thread-id.  See the 
22729 ** transferOwnership() function below for additional information
22730 */
22731 #if SQLITE_THREADSAFE && defined(__linux__)
22732 # define SET_THREADID(X)   (X)->tid = pthread_self()
22733 # define CHECK_THREADID(X) (threadsOverrideEachOthersLocks==0 && \
22734                             !pthread_equal((X)->tid, pthread_self()))
22735 #else
22736 # define SET_THREADID(X)
22737 # define CHECK_THREADID(X) 0
22738 #endif
22739
22740 /*
22741 ** An instance of the following structure serves as the key used
22742 ** to locate a particular unixOpenCnt structure given its inode.  This
22743 ** is the same as the unixLockKey except that the thread ID is omitted.
22744 */
22745 struct unixFileId {
22746   dev_t dev;                  /* Device number */
22747 #if OS_VXWORKS
22748   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
22749 #else
22750   ino_t ino;                  /* Inode number */
22751 #endif
22752 };
22753
22754 /*
22755 ** An instance of the following structure serves as the key used
22756 ** to locate a particular unixLockInfo structure given its inode.
22757 **
22758 ** If threads cannot override each others locks (LinuxThreads), then we
22759 ** set the unixLockKey.tid field to the thread ID.  If threads can override
22760 ** each others locks (Posix and NPTL) then tid is always set to zero.
22761 ** tid is omitted if we compile without threading support or on an OS
22762 ** other than linux.
22763 */
22764 struct unixLockKey {
22765   struct unixFileId fid;  /* Unique identifier for the file */
22766 #if SQLITE_THREADSAFE && defined(__linux__)
22767   pthread_t tid;  /* Thread ID of lock owner. Zero if not using LinuxThreads */
22768 #endif
22769 };
22770
22771 /*
22772 ** An instance of the following structure is allocated for each open
22773 ** inode.  Or, on LinuxThreads, there is one of these structures for
22774 ** each inode opened by each thread.
22775 **
22776 ** A single inode can have multiple file descriptors, so each unixFile
22777 ** structure contains a pointer to an instance of this object and this
22778 ** object keeps a count of the number of unixFile pointing to it.
22779 */
22780 struct unixLockInfo {
22781   struct unixLockKey lockKey;     /* The lookup key */
22782   int cnt;                        /* Number of SHARED locks held */
22783   int locktype;                   /* One of SHARED_LOCK, RESERVED_LOCK etc. */
22784   int nRef;                       /* Number of pointers to this structure */
22785 #if defined(SQLITE_ENABLE_LOCKING_STYLE)
22786   unsigned long long sharedByte;  /* for AFP simulated shared lock */
22787 #endif
22788   struct unixLockInfo *pNext;     /* List of all unixLockInfo objects */
22789   struct unixLockInfo *pPrev;     /*    .... doubly linked */
22790 };
22791
22792 /*
22793 ** An instance of the following structure is allocated for each open
22794 ** inode.  This structure keeps track of the number of locks on that
22795 ** inode.  If a close is attempted against an inode that is holding
22796 ** locks, the close is deferred until all locks clear by adding the
22797 ** file descriptor to be closed to the pending list.
22798 **
22799 ** TODO:  Consider changing this so that there is only a single file
22800 ** descriptor for each open file, even when it is opened multiple times.
22801 ** The close() system call would only occur when the last database
22802 ** using the file closes.
22803 */
22804 struct unixOpenCnt {
22805   struct unixFileId fileId;   /* The lookup key */
22806   int nRef;                   /* Number of pointers to this structure */
22807   int nLock;                  /* Number of outstanding locks */
22808   UnixUnusedFd *pUnused;      /* Unused file descriptors to close */
22809 #if OS_VXWORKS
22810   sem_t *pSem;                     /* Named POSIX semaphore */
22811   char aSemName[MAX_PATHNAME+2];   /* Name of that semaphore */
22812 #endif
22813   struct unixOpenCnt *pNext, *pPrev;   /* List of all unixOpenCnt objects */
22814 };
22815
22816 /*
22817 ** Lists of all unixLockInfo and unixOpenCnt objects.  These used to be hash
22818 ** tables.  But the number of objects is rarely more than a dozen and
22819 ** never exceeds a few thousand.  And lookup is not on a critical
22820 ** path so a simple linked list will suffice.
22821 */
22822 static struct unixLockInfo *lockList = 0;
22823 static struct unixOpenCnt *openList = 0;
22824
22825 /*
22826 ** This variable remembers whether or not threads can override each others
22827 ** locks.
22828 **
22829 **    0:  No.  Threads cannot override each others locks.  (LinuxThreads)
22830 **    1:  Yes.  Threads can override each others locks.  (Posix & NLPT)
22831 **   -1:  We don't know yet.
22832 **
22833 ** On some systems, we know at compile-time if threads can override each
22834 ** others locks.  On those systems, the SQLITE_THREAD_OVERRIDE_LOCK macro
22835 ** will be set appropriately.  On other systems, we have to check at
22836 ** runtime.  On these latter systems, SQLTIE_THREAD_OVERRIDE_LOCK is
22837 ** undefined.
22838 **
22839 ** This variable normally has file scope only.  But during testing, we make
22840 ** it a global so that the test code can change its value in order to verify
22841 ** that the right stuff happens in either case.
22842 */
22843 #if SQLITE_THREADSAFE && defined(__linux__)
22844 #  ifndef SQLITE_THREAD_OVERRIDE_LOCK
22845 #    define SQLITE_THREAD_OVERRIDE_LOCK -1
22846 #  endif
22847 #  ifdef SQLITE_TEST
22848 int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
22849 #  else
22850 static int threadsOverrideEachOthersLocks = SQLITE_THREAD_OVERRIDE_LOCK;
22851 #  endif
22852 #endif
22853
22854 /*
22855 ** This structure holds information passed into individual test
22856 ** threads by the testThreadLockingBehavior() routine.
22857 */
22858 struct threadTestData {
22859   int fd;                /* File to be locked */
22860   struct flock lock;     /* The locking operation */
22861   int result;            /* Result of the locking operation */
22862 };
22863
22864 #if SQLITE_THREADSAFE && defined(__linux__)
22865 /*
22866 ** This function is used as the main routine for a thread launched by
22867 ** testThreadLockingBehavior(). It tests whether the shared-lock obtained
22868 ** by the main thread in testThreadLockingBehavior() conflicts with a
22869 ** hypothetical write-lock obtained by this thread on the same file.
22870 **
22871 ** The write-lock is not actually acquired, as this is not possible if 
22872 ** the file is open in read-only mode (see ticket #3472).
22873 */ 
22874 static void *threadLockingTest(void *pArg){
22875   struct threadTestData *pData = (struct threadTestData*)pArg;
22876   pData->result = fcntl(pData->fd, F_GETLK, &pData->lock);
22877   return pArg;
22878 }
22879 #endif /* SQLITE_THREADSAFE && defined(__linux__) */
22880
22881
22882 #if SQLITE_THREADSAFE && defined(__linux__)
22883 /*
22884 ** This procedure attempts to determine whether or not threads
22885 ** can override each others locks then sets the 
22886 ** threadsOverrideEachOthersLocks variable appropriately.
22887 */
22888 static void testThreadLockingBehavior(int fd_orig){
22889   int fd;
22890   int rc;
22891   struct threadTestData d;
22892   struct flock l;
22893   pthread_t t;
22894
22895   fd = dup(fd_orig);
22896   if( fd<0 ) return;
22897   memset(&l, 0, sizeof(l));
22898   l.l_type = F_RDLCK;
22899   l.l_len = 1;
22900   l.l_start = 0;
22901   l.l_whence = SEEK_SET;
22902   rc = fcntl(fd_orig, F_SETLK, &l);
22903   if( rc!=0 ) return;
22904   memset(&d, 0, sizeof(d));
22905   d.fd = fd;
22906   d.lock = l;
22907   d.lock.l_type = F_WRLCK;
22908   if( pthread_create(&t, 0, threadLockingTest, &d)==0 ){
22909     pthread_join(t, 0);
22910   }
22911   close(fd);
22912   if( d.result!=0 ) return;
22913   threadsOverrideEachOthersLocks = (d.lock.l_type==F_UNLCK);
22914 }
22915 #endif /* SQLITE_THREADSAFE && defined(__linux__) */
22916
22917 /*
22918 ** Release a unixLockInfo structure previously allocated by findLockInfo().
22919 **
22920 ** The mutex entered using the unixEnterMutex() function must be held
22921 ** when this function is called.
22922 */
22923 static void releaseLockInfo(struct unixLockInfo *pLock){
22924   assert( unixMutexHeld() );
22925   if( pLock ){
22926     pLock->nRef--;
22927     if( pLock->nRef==0 ){
22928       if( pLock->pPrev ){
22929         assert( pLock->pPrev->pNext==pLock );
22930         pLock->pPrev->pNext = pLock->pNext;
22931       }else{
22932         assert( lockList==pLock );
22933         lockList = pLock->pNext;
22934       }
22935       if( pLock->pNext ){
22936         assert( pLock->pNext->pPrev==pLock );
22937         pLock->pNext->pPrev = pLock->pPrev;
22938       }
22939       sqlite3_free(pLock);
22940     }
22941   }
22942 }
22943
22944 /*
22945 ** Release a unixOpenCnt structure previously allocated by findLockInfo().
22946 **
22947 ** The mutex entered using the unixEnterMutex() function must be held
22948 ** when this function is called.
22949 */
22950 static void releaseOpenCnt(struct unixOpenCnt *pOpen){
22951   assert( unixMutexHeld() );
22952   if( pOpen ){
22953     pOpen->nRef--;
22954     if( pOpen->nRef==0 ){
22955       if( pOpen->pPrev ){
22956         assert( pOpen->pPrev->pNext==pOpen );
22957         pOpen->pPrev->pNext = pOpen->pNext;
22958       }else{
22959         assert( openList==pOpen );
22960         openList = pOpen->pNext;
22961       }
22962       if( pOpen->pNext ){
22963         assert( pOpen->pNext->pPrev==pOpen );
22964         pOpen->pNext->pPrev = pOpen->pPrev;
22965       }
22966 #if SQLITE_THREADSAFE && defined(__linux__)
22967       assert( !pOpen->pUnused || threadsOverrideEachOthersLocks==0 );
22968 #endif
22969
22970       /* If pOpen->pUnused is not null, then memory and file-descriptors
22971       ** are leaked.
22972       **
22973       ** This will only happen if, under Linuxthreads, the user has opened
22974       ** a transaction in one thread, then attempts to close the database
22975       ** handle from another thread (without first unlocking the db file).
22976       ** This is a misuse.  */
22977       sqlite3_free(pOpen);
22978     }
22979   }
22980 }
22981
22982 /*
22983 ** Given a file descriptor, locate unixLockInfo and unixOpenCnt structures that
22984 ** describes that file descriptor.  Create new ones if necessary.  The
22985 ** return values might be uninitialized if an error occurs.
22986 **
22987 ** The mutex entered using the unixEnterMutex() function must be held
22988 ** when this function is called.
22989 **
22990 ** Return an appropriate error code.
22991 */
22992 static int findLockInfo(
22993   unixFile *pFile,               /* Unix file with file desc used in the key */
22994   struct unixLockInfo **ppLock,  /* Return the unixLockInfo structure here */
22995   struct unixOpenCnt **ppOpen    /* Return the unixOpenCnt structure here */
22996 ){
22997   int rc;                        /* System call return code */
22998   int fd;                        /* The file descriptor for pFile */
22999   struct unixLockKey lockKey;    /* Lookup key for the unixLockInfo structure */
23000   struct unixFileId fileId;      /* Lookup key for the unixOpenCnt struct */
23001   struct stat statbuf;           /* Low-level file information */
23002   struct unixLockInfo *pLock = 0;/* Candidate unixLockInfo object */
23003   struct unixOpenCnt *pOpen;     /* Candidate unixOpenCnt object */
23004
23005   assert( unixMutexHeld() );
23006
23007   /* Get low-level information about the file that we can used to
23008   ** create a unique name for the file.
23009   */
23010   fd = pFile->h;
23011   rc = fstat(fd, &statbuf);
23012   if( rc!=0 ){
23013     pFile->lastErrno = errno;
23014 #ifdef EOVERFLOW
23015     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
23016 #endif
23017     return SQLITE_IOERR;
23018   }
23019
23020 #ifdef __APPLE__
23021   /* On OS X on an msdos filesystem, the inode number is reported
23022   ** incorrectly for zero-size files.  See ticket #3260.  To work
23023   ** around this problem (we consider it a bug in OS X, not SQLite)
23024   ** we always increase the file size to 1 by writing a single byte
23025   ** prior to accessing the inode number.  The one byte written is
23026   ** an ASCII 'S' character which also happens to be the first byte
23027   ** in the header of every SQLite database.  In this way, if there
23028   ** is a race condition such that another thread has already populated
23029   ** the first page of the database, no damage is done.
23030   */
23031   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
23032     rc = write(fd, "S", 1);
23033     if( rc!=1 ){
23034       pFile->lastErrno = errno;
23035       return SQLITE_IOERR;
23036     }
23037     rc = fstat(fd, &statbuf);
23038     if( rc!=0 ){
23039       pFile->lastErrno = errno;
23040       return SQLITE_IOERR;
23041     }
23042   }
23043 #endif
23044
23045   memset(&lockKey, 0, sizeof(lockKey));
23046   lockKey.fid.dev = statbuf.st_dev;
23047 #if OS_VXWORKS
23048   lockKey.fid.pId = pFile->pId;
23049 #else
23050   lockKey.fid.ino = statbuf.st_ino;
23051 #endif
23052 #if SQLITE_THREADSAFE && defined(__linux__)
23053   if( threadsOverrideEachOthersLocks<0 ){
23054     testThreadLockingBehavior(fd);
23055   }
23056   lockKey.tid = threadsOverrideEachOthersLocks ? 0 : pthread_self();
23057 #endif
23058   fileId = lockKey.fid;
23059   if( ppLock!=0 ){
23060     pLock = lockList;
23061     while( pLock && memcmp(&lockKey, &pLock->lockKey, sizeof(lockKey)) ){
23062       pLock = pLock->pNext;
23063     }
23064     if( pLock==0 ){
23065       pLock = sqlite3_malloc( sizeof(*pLock) );
23066       if( pLock==0 ){
23067         rc = SQLITE_NOMEM;
23068         goto exit_findlockinfo;
23069       }
23070       memcpy(&pLock->lockKey,&lockKey,sizeof(lockKey));
23071       pLock->nRef = 1;
23072       pLock->cnt = 0;
23073       pLock->locktype = 0;
23074 #if defined(SQLITE_ENABLE_LOCKING_STYLE)
23075       pLock->sharedByte = 0;
23076 #endif
23077       pLock->pNext = lockList;
23078       pLock->pPrev = 0;
23079       if( lockList ) lockList->pPrev = pLock;
23080       lockList = pLock;
23081     }else{
23082       pLock->nRef++;
23083     }
23084     *ppLock = pLock;
23085   }
23086   if( ppOpen!=0 ){
23087     pOpen = openList;
23088     while( pOpen && memcmp(&fileId, &pOpen->fileId, sizeof(fileId)) ){
23089       pOpen = pOpen->pNext;
23090     }
23091     if( pOpen==0 ){
23092       pOpen = sqlite3_malloc( sizeof(*pOpen) );
23093       if( pOpen==0 ){
23094         releaseLockInfo(pLock);
23095         rc = SQLITE_NOMEM;
23096         goto exit_findlockinfo;
23097       }
23098       memset(pOpen, 0, sizeof(*pOpen));
23099       pOpen->fileId = fileId;
23100       pOpen->nRef = 1;
23101       pOpen->pNext = openList;
23102       if( openList ) openList->pPrev = pOpen;
23103       openList = pOpen;
23104     }else{
23105       pOpen->nRef++;
23106     }
23107     *ppOpen = pOpen;
23108   }
23109
23110 exit_findlockinfo:
23111   return rc;
23112 }
23113
23114 /*
23115 ** If we are currently in a different thread than the thread that the
23116 ** unixFile argument belongs to, then transfer ownership of the unixFile
23117 ** over to the current thread.
23118 **
23119 ** A unixFile is only owned by a thread on systems that use LinuxThreads.
23120 **
23121 ** Ownership transfer is only allowed if the unixFile is currently unlocked.
23122 ** If the unixFile is locked and an ownership is wrong, then return
23123 ** SQLITE_MISUSE.  SQLITE_OK is returned if everything works.
23124 */
23125 #if SQLITE_THREADSAFE && defined(__linux__)
23126 static int transferOwnership(unixFile *pFile){
23127   int rc;
23128   pthread_t hSelf;
23129   if( threadsOverrideEachOthersLocks ){
23130     /* Ownership transfers not needed on this system */
23131     return SQLITE_OK;
23132   }
23133   hSelf = pthread_self();
23134   if( pthread_equal(pFile->tid, hSelf) ){
23135     /* We are still in the same thread */
23136     OSTRACE1("No-transfer, same thread\n");
23137     return SQLITE_OK;
23138   }
23139   if( pFile->locktype!=NO_LOCK ){
23140     /* We cannot change ownership while we are holding a lock! */
23141     return SQLITE_MISUSE_BKPT;
23142   }
23143   OSTRACE4("Transfer ownership of %d from %d to %d\n",
23144             pFile->h, pFile->tid, hSelf);
23145   pFile->tid = hSelf;
23146   if (pFile->pLock != NULL) {
23147     releaseLockInfo(pFile->pLock);
23148     rc = findLockInfo(pFile, &pFile->pLock, 0);
23149     OSTRACE5("LOCK    %d is now %s(%s,%d)\n", pFile->h,
23150            locktypeName(pFile->locktype),
23151            locktypeName(pFile->pLock->locktype), pFile->pLock->cnt);
23152     return rc;
23153   } else {
23154     return SQLITE_OK;
23155   }
23156 }
23157 #else  /* if not SQLITE_THREADSAFE */
23158   /* On single-threaded builds, ownership transfer is a no-op */
23159 # define transferOwnership(X) SQLITE_OK
23160 #endif /* SQLITE_THREADSAFE */
23161
23162
23163 /*
23164 ** This routine checks if there is a RESERVED lock held on the specified
23165 ** file by this or any other process. If such a lock is held, set *pResOut
23166 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
23167 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23168 */
23169 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
23170   int rc = SQLITE_OK;
23171   int reserved = 0;
23172   unixFile *pFile = (unixFile*)id;
23173
23174   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23175
23176   assert( pFile );
23177   unixEnterMutex(); /* Because pFile->pLock is shared across threads */
23178
23179   /* Check if a thread in this process holds such a lock */
23180   if( pFile->pLock->locktype>SHARED_LOCK ){
23181     reserved = 1;
23182   }
23183
23184   /* Otherwise see if some other process holds it.
23185   */
23186 #ifndef __DJGPP__
23187   if( !reserved ){
23188     struct flock lock;
23189     lock.l_whence = SEEK_SET;
23190     lock.l_start = RESERVED_BYTE;
23191     lock.l_len = 1;
23192     lock.l_type = F_WRLCK;
23193     if (-1 == fcntl(pFile->h, F_GETLK, &lock)) {
23194       int tErrno = errno;
23195       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
23196       pFile->lastErrno = tErrno;
23197     } else if( lock.l_type!=F_UNLCK ){
23198       reserved = 1;
23199     }
23200   }
23201 #endif
23202   
23203   unixLeaveMutex();
23204   OSTRACE4("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved);
23205
23206   *pResOut = reserved;
23207   return rc;
23208 }
23209
23210 /*
23211 ** Lock the file with the lock specified by parameter locktype - one
23212 ** of the following:
23213 **
23214 **     (1) SHARED_LOCK
23215 **     (2) RESERVED_LOCK
23216 **     (3) PENDING_LOCK
23217 **     (4) EXCLUSIVE_LOCK
23218 **
23219 ** Sometimes when requesting one lock state, additional lock states
23220 ** are inserted in between.  The locking might fail on one of the later
23221 ** transitions leaving the lock state different from what it started but
23222 ** still short of its goal.  The following chart shows the allowed
23223 ** transitions and the inserted intermediate states:
23224 **
23225 **    UNLOCKED -> SHARED
23226 **    SHARED -> RESERVED
23227 **    SHARED -> (PENDING) -> EXCLUSIVE
23228 **    RESERVED -> (PENDING) -> EXCLUSIVE
23229 **    PENDING -> EXCLUSIVE
23230 **
23231 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23232 ** routine to lower a locking level.
23233 */
23234 static int unixLock(sqlite3_file *id, int locktype){
23235   /* The following describes the implementation of the various locks and
23236   ** lock transitions in terms of the POSIX advisory shared and exclusive
23237   ** lock primitives (called read-locks and write-locks below, to avoid
23238   ** confusion with SQLite lock names). The algorithms are complicated
23239   ** slightly in order to be compatible with windows systems simultaneously
23240   ** accessing the same database file, in case that is ever required.
23241   **
23242   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
23243   ** byte', each single bytes at well known offsets, and the 'shared byte
23244   ** range', a range of 510 bytes at a well known offset.
23245   **
23246   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
23247   ** byte'.  If this is successful, a random byte from the 'shared byte
23248   ** range' is read-locked and the lock on the 'pending byte' released.
23249   **
23250   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
23251   ** A RESERVED lock is implemented by grabbing a write-lock on the
23252   ** 'reserved byte'. 
23253   **
23254   ** A process may only obtain a PENDING lock after it has obtained a
23255   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
23256   ** on the 'pending byte'. This ensures that no new SHARED locks can be
23257   ** obtained, but existing SHARED locks are allowed to persist. A process
23258   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
23259   ** This property is used by the algorithm for rolling back a journal file
23260   ** after a crash.
23261   **
23262   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
23263   ** implemented by obtaining a write-lock on the entire 'shared byte
23264   ** range'. Since all other locks require a read-lock on one of the bytes
23265   ** within this range, this ensures that no other locks are held on the
23266   ** database. 
23267   **
23268   ** The reason a single byte cannot be used instead of the 'shared byte
23269   ** range' is that some versions of windows do not support read-locks. By
23270   ** locking a random byte from a range, concurrent SHARED locks may exist
23271   ** even if the locking primitive used is always a write-lock.
23272   */
23273   int rc = SQLITE_OK;
23274   unixFile *pFile = (unixFile*)id;
23275   struct unixLockInfo *pLock = pFile->pLock;
23276   struct flock lock;
23277   int s = 0;
23278   int tErrno = 0;
23279
23280   assert( pFile );
23281   OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
23282       locktypeName(locktype), locktypeName(pFile->locktype),
23283       locktypeName(pLock->locktype), pLock->cnt , getpid());
23284
23285   /* If there is already a lock of this type or more restrictive on the
23286   ** unixFile, do nothing. Don't use the end_lock: exit path, as
23287   ** unixEnterMutex() hasn't been called yet.
23288   */
23289   if( pFile->locktype>=locktype ){
23290     OSTRACE3("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
23291             locktypeName(locktype));
23292     return SQLITE_OK;
23293   }
23294
23295   /* Make sure the locking sequence is correct.
23296   **  (1) We never move from unlocked to anything higher than shared lock.
23297   **  (2) SQLite never explicitly requests a pendig lock.
23298   **  (3) A shared lock is always held when a reserve lock is requested.
23299   */
23300   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
23301   assert( locktype!=PENDING_LOCK );
23302   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
23303
23304   /* This mutex is needed because pFile->pLock is shared across threads
23305   */
23306   unixEnterMutex();
23307
23308   /* Make sure the current thread owns the pFile.
23309   */
23310   rc = transferOwnership(pFile);
23311   if( rc!=SQLITE_OK ){
23312     unixLeaveMutex();
23313     return rc;
23314   }
23315   pLock = pFile->pLock;
23316
23317   /* If some thread using this PID has a lock via a different unixFile*
23318   ** handle that precludes the requested lock, return BUSY.
23319   */
23320   if( (pFile->locktype!=pLock->locktype && 
23321           (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
23322   ){
23323     rc = SQLITE_BUSY;
23324     goto end_lock;
23325   }
23326
23327   /* If a SHARED lock is requested, and some thread using this PID already
23328   ** has a SHARED or RESERVED lock, then increment reference counts and
23329   ** return SQLITE_OK.
23330   */
23331   if( locktype==SHARED_LOCK && 
23332       (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
23333     assert( locktype==SHARED_LOCK );
23334     assert( pFile->locktype==0 );
23335     assert( pLock->cnt>0 );
23336     pFile->locktype = SHARED_LOCK;
23337     pLock->cnt++;
23338     pFile->pOpen->nLock++;
23339     goto end_lock;
23340   }
23341
23342
23343   /* A PENDING lock is needed before acquiring a SHARED lock and before
23344   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
23345   ** be released.
23346   */
23347   lock.l_len = 1L;
23348   lock.l_whence = SEEK_SET;
23349   if( locktype==SHARED_LOCK 
23350       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
23351   ){
23352     lock.l_type = (locktype==SHARED_LOCK?F_RDLCK:F_WRLCK);
23353     lock.l_start = PENDING_BYTE;
23354     s = fcntl(pFile->h, F_SETLK, &lock);
23355     if( s==(-1) ){
23356       tErrno = errno;
23357       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23358       if( IS_LOCK_ERROR(rc) ){
23359         pFile->lastErrno = tErrno;
23360       }
23361       goto end_lock;
23362     }
23363   }
23364
23365
23366   /* If control gets to this point, then actually go ahead and make
23367   ** operating system calls for the specified lock.
23368   */
23369   if( locktype==SHARED_LOCK ){
23370     assert( pLock->cnt==0 );
23371     assert( pLock->locktype==0 );
23372
23373     /* Now get the read-lock */
23374     lock.l_start = SHARED_FIRST;
23375     lock.l_len = SHARED_SIZE;
23376     if( (s = fcntl(pFile->h, F_SETLK, &lock))==(-1) ){
23377       tErrno = errno;
23378     }
23379     /* Drop the temporary PENDING lock */
23380     lock.l_start = PENDING_BYTE;
23381     lock.l_len = 1L;
23382     lock.l_type = F_UNLCK;
23383     if( fcntl(pFile->h, F_SETLK, &lock)!=0 ){
23384       if( s != -1 ){
23385         /* This could happen with a network mount */
23386         tErrno = errno; 
23387         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
23388         if( IS_LOCK_ERROR(rc) ){
23389           pFile->lastErrno = tErrno;
23390         }
23391         goto end_lock;
23392       }
23393     }
23394     if( s==(-1) ){
23395       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23396       if( IS_LOCK_ERROR(rc) ){
23397         pFile->lastErrno = tErrno;
23398       }
23399     }else{
23400       pFile->locktype = SHARED_LOCK;
23401       pFile->pOpen->nLock++;
23402       pLock->cnt = 1;
23403     }
23404   }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
23405     /* We are trying for an exclusive lock but another thread in this
23406     ** same process is still holding a shared lock. */
23407     rc = SQLITE_BUSY;
23408   }else{
23409     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
23410     ** assumed that there is a SHARED or greater lock on the file
23411     ** already.
23412     */
23413     assert( 0!=pFile->locktype );
23414     lock.l_type = F_WRLCK;
23415     switch( locktype ){
23416       case RESERVED_LOCK:
23417         lock.l_start = RESERVED_BYTE;
23418         break;
23419       case EXCLUSIVE_LOCK:
23420         lock.l_start = SHARED_FIRST;
23421         lock.l_len = SHARED_SIZE;
23422         break;
23423       default:
23424         assert(0);
23425     }
23426     s = fcntl(pFile->h, F_SETLK, &lock);
23427     if( s==(-1) ){
23428       tErrno = errno;
23429       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23430       if( IS_LOCK_ERROR(rc) ){
23431         pFile->lastErrno = tErrno;
23432       }
23433     }
23434   }
23435   
23436
23437 #ifndef NDEBUG
23438   /* Set up the transaction-counter change checking flags when
23439   ** transitioning from a SHARED to a RESERVED lock.  The change
23440   ** from SHARED to RESERVED marks the beginning of a normal
23441   ** write operation (not a hot journal rollback).
23442   */
23443   if( rc==SQLITE_OK
23444    && pFile->locktype<=SHARED_LOCK
23445    && locktype==RESERVED_LOCK
23446   ){
23447     pFile->transCntrChng = 0;
23448     pFile->dbUpdate = 0;
23449     pFile->inNormalWrite = 1;
23450   }
23451 #endif
23452
23453
23454   if( rc==SQLITE_OK ){
23455     pFile->locktype = locktype;
23456     pLock->locktype = locktype;
23457   }else if( locktype==EXCLUSIVE_LOCK ){
23458     pFile->locktype = PENDING_LOCK;
23459     pLock->locktype = PENDING_LOCK;
23460   }
23461
23462 end_lock:
23463   unixLeaveMutex();
23464   OSTRACE4("LOCK    %d %s %s (unix)\n", pFile->h, locktypeName(locktype), 
23465       rc==SQLITE_OK ? "ok" : "failed");
23466   return rc;
23467 }
23468
23469 /*
23470 ** Close all file descriptors accumuated in the unixOpenCnt->pUnused list.
23471 ** If all such file descriptors are closed without error, the list is
23472 ** cleared and SQLITE_OK returned.
23473 **
23474 ** Otherwise, if an error occurs, then successfully closed file descriptor
23475 ** entries are removed from the list, and SQLITE_IOERR_CLOSE returned. 
23476 ** not deleted and SQLITE_IOERR_CLOSE returned.
23477 */ 
23478 static int closePendingFds(unixFile *pFile){
23479   int rc = SQLITE_OK;
23480   struct unixOpenCnt *pOpen = pFile->pOpen;
23481   UnixUnusedFd *pError = 0;
23482   UnixUnusedFd *p;
23483   UnixUnusedFd *pNext;
23484   for(p=pOpen->pUnused; p; p=pNext){
23485     pNext = p->pNext;
23486     if( close(p->fd) ){
23487       pFile->lastErrno = errno;
23488       rc = SQLITE_IOERR_CLOSE;
23489       p->pNext = pError;
23490       pError = p;
23491     }else{
23492       sqlite3_free(p);
23493     }
23494   }
23495   pOpen->pUnused = pError;
23496   return rc;
23497 }
23498
23499 /*
23500 ** Add the file descriptor used by file handle pFile to the corresponding
23501 ** pUnused list.
23502 */
23503 static void setPendingFd(unixFile *pFile){
23504   struct unixOpenCnt *pOpen = pFile->pOpen;
23505   UnixUnusedFd *p = pFile->pUnused;
23506   p->pNext = pOpen->pUnused;
23507   pOpen->pUnused = p;
23508   pFile->h = -1;
23509   pFile->pUnused = 0;
23510 }
23511
23512 /*
23513 ** Lower the locking level on file descriptor pFile to locktype.  locktype
23514 ** must be either NO_LOCK or SHARED_LOCK.
23515 **
23516 ** If the locking level of the file descriptor is already at or below
23517 ** the requested locking level, this routine is a no-op.
23518 ** 
23519 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
23520 ** the byte range is divided into 2 parts and the first part is unlocked then
23521 ** set to a read lock, then the other part is simply unlocked.  This works 
23522 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
23523 ** remove the write lock on a region when a read lock is set.
23524 */
23525 static int _posixUnlock(sqlite3_file *id, int locktype, int handleNFSUnlock){
23526   unixFile *pFile = (unixFile*)id;
23527   struct unixLockInfo *pLock;
23528   struct flock lock;
23529   int rc = SQLITE_OK;
23530   int h;
23531   int tErrno;                      /* Error code from system call errors */
23532
23533   assert( pFile );
23534   OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, locktype,
23535       pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
23536
23537   assert( locktype<=SHARED_LOCK );
23538   if( pFile->locktype<=locktype ){
23539     return SQLITE_OK;
23540   }
23541   if( CHECK_THREADID(pFile) ){
23542     return SQLITE_MISUSE_BKPT;
23543   }
23544   unixEnterMutex();
23545   h = pFile->h;
23546   pLock = pFile->pLock;
23547   assert( pLock->cnt!=0 );
23548   if( pFile->locktype>SHARED_LOCK ){
23549     assert( pLock->locktype==pFile->locktype );
23550     SimulateIOErrorBenign(1);
23551     SimulateIOError( h=(-1) )
23552     SimulateIOErrorBenign(0);
23553
23554 #ifndef NDEBUG
23555     /* When reducing a lock such that other processes can start
23556     ** reading the database file again, make sure that the
23557     ** transaction counter was updated if any part of the database
23558     ** file changed.  If the transaction counter is not updated,
23559     ** other connections to the same file might not realize that
23560     ** the file has changed and hence might not know to flush their
23561     ** cache.  The use of a stale cache can lead to database corruption.
23562     */
23563     assert( pFile->inNormalWrite==0
23564          || pFile->dbUpdate==0
23565          || pFile->transCntrChng==1 );
23566     pFile->inNormalWrite = 0;
23567 #endif
23568
23569     /* downgrading to a shared lock on NFS involves clearing the write lock
23570     ** before establishing the readlock - to avoid a race condition we downgrade
23571     ** the lock in 2 blocks, so that part of the range will be covered by a 
23572     ** write lock until the rest is covered by a read lock:
23573     **  1:   [WWWWW]
23574     **  2:   [....W]
23575     **  3:   [RRRRW]
23576     **  4:   [RRRR.]
23577     */
23578     if( locktype==SHARED_LOCK ){
23579       if( handleNFSUnlock ){
23580         off_t divSize = SHARED_SIZE - 1;
23581         
23582         lock.l_type = F_UNLCK;
23583         lock.l_whence = SEEK_SET;
23584         lock.l_start = SHARED_FIRST;
23585         lock.l_len = divSize;
23586         if( fcntl(h, F_SETLK, &lock)==(-1) ){
23587           tErrno = errno;
23588           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23589           if( IS_LOCK_ERROR(rc) ){
23590             pFile->lastErrno = tErrno;
23591           }
23592           goto end_unlock;
23593         }
23594         lock.l_type = F_RDLCK;
23595         lock.l_whence = SEEK_SET;
23596         lock.l_start = SHARED_FIRST;
23597         lock.l_len = divSize;
23598         if( fcntl(h, F_SETLK, &lock)==(-1) ){
23599           tErrno = errno;
23600           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
23601           if( IS_LOCK_ERROR(rc) ){
23602             pFile->lastErrno = tErrno;
23603           }
23604           goto end_unlock;
23605         }
23606         lock.l_type = F_UNLCK;
23607         lock.l_whence = SEEK_SET;
23608         lock.l_start = SHARED_FIRST+divSize;
23609         lock.l_len = SHARED_SIZE-divSize;
23610         if( fcntl(h, F_SETLK, &lock)==(-1) ){
23611           tErrno = errno;
23612           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23613           if( IS_LOCK_ERROR(rc) ){
23614             pFile->lastErrno = tErrno;
23615           }
23616           goto end_unlock;
23617         }
23618       }else{
23619         lock.l_type = F_RDLCK;
23620         lock.l_whence = SEEK_SET;
23621         lock.l_start = SHARED_FIRST;
23622         lock.l_len = SHARED_SIZE;
23623         if( fcntl(h, F_SETLK, &lock)==(-1) ){
23624           tErrno = errno;
23625           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
23626           if( IS_LOCK_ERROR(rc) ){
23627             pFile->lastErrno = tErrno;
23628           }
23629           goto end_unlock;
23630         }
23631       }
23632     }
23633     lock.l_type = F_UNLCK;
23634     lock.l_whence = SEEK_SET;
23635     lock.l_start = PENDING_BYTE;
23636     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
23637     if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23638       pLock->locktype = SHARED_LOCK;
23639     }else{
23640       tErrno = errno;
23641       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23642       if( IS_LOCK_ERROR(rc) ){
23643         pFile->lastErrno = tErrno;
23644       }
23645       goto end_unlock;
23646     }
23647   }
23648   if( locktype==NO_LOCK ){
23649     struct unixOpenCnt *pOpen;
23650
23651     /* Decrement the shared lock counter.  Release the lock using an
23652     ** OS call only when all threads in this same process have released
23653     ** the lock.
23654     */
23655     pLock->cnt--;
23656     if( pLock->cnt==0 ){
23657       lock.l_type = F_UNLCK;
23658       lock.l_whence = SEEK_SET;
23659       lock.l_start = lock.l_len = 0L;
23660       SimulateIOErrorBenign(1);
23661       SimulateIOError( h=(-1) )
23662       SimulateIOErrorBenign(0);
23663       if( fcntl(h, F_SETLK, &lock)!=(-1) ){
23664         pLock->locktype = NO_LOCK;
23665       }else{
23666         tErrno = errno;
23667         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23668         if( IS_LOCK_ERROR(rc) ){
23669           pFile->lastErrno = tErrno;
23670         }
23671         pLock->locktype = NO_LOCK;
23672         pFile->locktype = NO_LOCK;
23673       }
23674     }
23675
23676     /* Decrement the count of locks against this same file.  When the
23677     ** count reaches zero, close any other file descriptors whose close
23678     ** was deferred because of outstanding locks.
23679     */
23680     pOpen = pFile->pOpen;
23681     pOpen->nLock--;
23682     assert( pOpen->nLock>=0 );
23683     if( pOpen->nLock==0 ){
23684       int rc2 = closePendingFds(pFile);
23685       if( rc==SQLITE_OK ){
23686         rc = rc2;
23687       }
23688     }
23689   }
23690         
23691 end_unlock:
23692   unixLeaveMutex();
23693   if( rc==SQLITE_OK ) pFile->locktype = locktype;
23694   return rc;
23695 }
23696
23697 /*
23698 ** Lower the locking level on file descriptor pFile to locktype.  locktype
23699 ** must be either NO_LOCK or SHARED_LOCK.
23700 **
23701 ** If the locking level of the file descriptor is already at or below
23702 ** the requested locking level, this routine is a no-op.
23703 */
23704 static int unixUnlock(sqlite3_file *id, int locktype){
23705   return _posixUnlock(id, locktype, 0);
23706 }
23707
23708 /*
23709 ** This function performs the parts of the "close file" operation 
23710 ** common to all locking schemes. It closes the directory and file
23711 ** handles, if they are valid, and sets all fields of the unixFile
23712 ** structure to 0.
23713 **
23714 ** It is *not* necessary to hold the mutex when this routine is called,
23715 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
23716 ** vxworksReleaseFileId() routine.
23717 */
23718 static int closeUnixFile(sqlite3_file *id){
23719   unixFile *pFile = (unixFile*)id;
23720   if( pFile ){
23721     if( pFile->dirfd>=0 ){
23722       int err = close(pFile->dirfd);
23723       if( err ){
23724         pFile->lastErrno = errno;
23725         return SQLITE_IOERR_DIR_CLOSE;
23726       }else{
23727         pFile->dirfd=-1;
23728       }
23729     }
23730     if( pFile->h>=0 ){
23731       int err = close(pFile->h);
23732       if( err ){
23733         pFile->lastErrno = errno;
23734         return SQLITE_IOERR_CLOSE;
23735       }
23736     }
23737 #if OS_VXWORKS
23738     if( pFile->pId ){
23739       if( pFile->isDelete ){
23740         unlink(pFile->pId->zCanonicalName);
23741       }
23742       vxworksReleaseFileId(pFile->pId);
23743       pFile->pId = 0;
23744     }
23745 #endif
23746     OSTRACE2("CLOSE   %-3d\n", pFile->h);
23747     OpenCounter(-1);
23748     sqlite3_free(pFile->pUnused);
23749     memset(pFile, 0, sizeof(unixFile));
23750   }
23751   return SQLITE_OK;
23752 }
23753
23754 /*
23755 ** Close a file.
23756 */
23757 static int unixClose(sqlite3_file *id){
23758   int rc = SQLITE_OK;
23759   if( id ){
23760     unixFile *pFile = (unixFile *)id;
23761     unixUnlock(id, NO_LOCK);
23762     unixEnterMutex();
23763     if( pFile->pOpen && pFile->pOpen->nLock ){
23764       /* If there are outstanding locks, do not actually close the file just
23765       ** yet because that would clear those locks.  Instead, add the file
23766       ** descriptor to pOpen->pUnused list.  It will be automatically closed 
23767       ** when the last lock is cleared.
23768       */
23769       setPendingFd(pFile);
23770     }
23771     releaseLockInfo(pFile->pLock);
23772     releaseOpenCnt(pFile->pOpen);
23773     rc = closeUnixFile(id);
23774     unixLeaveMutex();
23775   }
23776   return rc;
23777 }
23778
23779 /************** End of the posix advisory lock implementation *****************
23780 ******************************************************************************/
23781
23782 /******************************************************************************
23783 ****************************** No-op Locking **********************************
23784 **
23785 ** Of the various locking implementations available, this is by far the
23786 ** simplest:  locking is ignored.  No attempt is made to lock the database
23787 ** file for reading or writing.
23788 **
23789 ** This locking mode is appropriate for use on read-only databases
23790 ** (ex: databases that are burned into CD-ROM, for example.)  It can
23791 ** also be used if the application employs some external mechanism to
23792 ** prevent simultaneous access of the same database by two or more
23793 ** database connections.  But there is a serious risk of database
23794 ** corruption if this locking mode is used in situations where multiple
23795 ** database connections are accessing the same database file at the same
23796 ** time and one or more of those connections are writing.
23797 */
23798
23799 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
23800   UNUSED_PARAMETER(NotUsed);
23801   *pResOut = 0;
23802   return SQLITE_OK;
23803 }
23804 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
23805   UNUSED_PARAMETER2(NotUsed, NotUsed2);
23806   return SQLITE_OK;
23807 }
23808 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
23809   UNUSED_PARAMETER2(NotUsed, NotUsed2);
23810   return SQLITE_OK;
23811 }
23812
23813 /*
23814 ** Close the file.
23815 */
23816 static int nolockClose(sqlite3_file *id) {
23817   return closeUnixFile(id);
23818 }
23819
23820 /******************* End of the no-op lock implementation *********************
23821 ******************************************************************************/
23822
23823 /******************************************************************************
23824 ************************* Begin dot-file Locking ******************************
23825 **
23826 ** The dotfile locking implementation uses the existance of separate lock
23827 ** files in order to control access to the database.  This works on just
23828 ** about every filesystem imaginable.  But there are serious downsides:
23829 **
23830 **    (1)  There is zero concurrency.  A single reader blocks all other
23831 **         connections from reading or writing the database.
23832 **
23833 **    (2)  An application crash or power loss can leave stale lock files
23834 **         sitting around that need to be cleared manually.
23835 **
23836 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
23837 ** other locking strategy is available.
23838 **
23839 ** Dotfile locking works by creating a file in the same directory as the
23840 ** database and with the same name but with a ".lock" extension added.
23841 ** The existance of a lock file implies an EXCLUSIVE lock.  All other lock
23842 ** types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
23843 */
23844
23845 /*
23846 ** The file suffix added to the data base filename in order to create the
23847 ** lock file.
23848 */
23849 #define DOTLOCK_SUFFIX ".lock"
23850
23851 /*
23852 ** This routine checks if there is a RESERVED lock held on the specified
23853 ** file by this or any other process. If such a lock is held, set *pResOut
23854 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
23855 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
23856 **
23857 ** In dotfile locking, either a lock exists or it does not.  So in this
23858 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
23859 ** is held on the file and false if the file is unlocked.
23860 */
23861 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
23862   int rc = SQLITE_OK;
23863   int reserved = 0;
23864   unixFile *pFile = (unixFile*)id;
23865
23866   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
23867   
23868   assert( pFile );
23869
23870   /* Check if a thread in this process holds such a lock */
23871   if( pFile->locktype>SHARED_LOCK ){
23872     /* Either this connection or some other connection in the same process
23873     ** holds a lock on the file.  No need to check further. */
23874     reserved = 1;
23875   }else{
23876     /* The lock is held if and only if the lockfile exists */
23877     const char *zLockFile = (const char*)pFile->lockingContext;
23878     reserved = access(zLockFile, 0)==0;
23879   }
23880   OSTRACE4("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved);
23881   *pResOut = reserved;
23882   return rc;
23883 }
23884
23885 /*
23886 ** Lock the file with the lock specified by parameter locktype - one
23887 ** of the following:
23888 **
23889 **     (1) SHARED_LOCK
23890 **     (2) RESERVED_LOCK
23891 **     (3) PENDING_LOCK
23892 **     (4) EXCLUSIVE_LOCK
23893 **
23894 ** Sometimes when requesting one lock state, additional lock states
23895 ** are inserted in between.  The locking might fail on one of the later
23896 ** transitions leaving the lock state different from what it started but
23897 ** still short of its goal.  The following chart shows the allowed
23898 ** transitions and the inserted intermediate states:
23899 **
23900 **    UNLOCKED -> SHARED
23901 **    SHARED -> RESERVED
23902 **    SHARED -> (PENDING) -> EXCLUSIVE
23903 **    RESERVED -> (PENDING) -> EXCLUSIVE
23904 **    PENDING -> EXCLUSIVE
23905 **
23906 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
23907 ** routine to lower a locking level.
23908 **
23909 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
23910 ** But we track the other locking levels internally.
23911 */
23912 static int dotlockLock(sqlite3_file *id, int locktype) {
23913   unixFile *pFile = (unixFile*)id;
23914   int fd;
23915   char *zLockFile = (char *)pFile->lockingContext;
23916   int rc = SQLITE_OK;
23917
23918
23919   /* If we have any lock, then the lock file already exists.  All we have
23920   ** to do is adjust our internal record of the lock level.
23921   */
23922   if( pFile->locktype > NO_LOCK ){
23923     pFile->locktype = locktype;
23924 #if !OS_VXWORKS
23925     /* Always update the timestamp on the old file */
23926     utimes(zLockFile, NULL);
23927 #endif
23928     return SQLITE_OK;
23929   }
23930   
23931   /* grab an exclusive lock */
23932   fd = open(zLockFile,O_RDONLY|O_CREAT|O_EXCL,0600);
23933   if( fd<0 ){
23934     /* failed to open/create the file, someone else may have stolen the lock */
23935     int tErrno = errno;
23936     if( EEXIST == tErrno ){
23937       rc = SQLITE_BUSY;
23938     } else {
23939       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
23940       if( IS_LOCK_ERROR(rc) ){
23941         pFile->lastErrno = tErrno;
23942       }
23943     }
23944     return rc;
23945   } 
23946   if( close(fd) ){
23947     pFile->lastErrno = errno;
23948     rc = SQLITE_IOERR_CLOSE;
23949   }
23950   
23951   /* got it, set the type and return ok */
23952   pFile->locktype = locktype;
23953   return rc;
23954 }
23955
23956 /*
23957 ** Lower the locking level on file descriptor pFile to locktype.  locktype
23958 ** must be either NO_LOCK or SHARED_LOCK.
23959 **
23960 ** If the locking level of the file descriptor is already at or below
23961 ** the requested locking level, this routine is a no-op.
23962 **
23963 ** When the locking level reaches NO_LOCK, delete the lock file.
23964 */
23965 static int dotlockUnlock(sqlite3_file *id, int locktype) {
23966   unixFile *pFile = (unixFile*)id;
23967   char *zLockFile = (char *)pFile->lockingContext;
23968
23969   assert( pFile );
23970   OSTRACE5("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, locktype,
23971            pFile->locktype, getpid());
23972   assert( locktype<=SHARED_LOCK );
23973   
23974   /* no-op if possible */
23975   if( pFile->locktype==locktype ){
23976     return SQLITE_OK;
23977   }
23978
23979   /* To downgrade to shared, simply update our internal notion of the
23980   ** lock state.  No need to mess with the file on disk.
23981   */
23982   if( locktype==SHARED_LOCK ){
23983     pFile->locktype = SHARED_LOCK;
23984     return SQLITE_OK;
23985   }
23986   
23987   /* To fully unlock the database, delete the lock file */
23988   assert( locktype==NO_LOCK );
23989   if( unlink(zLockFile) ){
23990     int rc = 0;
23991     int tErrno = errno;
23992     if( ENOENT != tErrno ){
23993       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
23994     }
23995     if( IS_LOCK_ERROR(rc) ){
23996       pFile->lastErrno = tErrno;
23997     }
23998     return rc; 
23999   }
24000   pFile->locktype = NO_LOCK;
24001   return SQLITE_OK;
24002 }
24003
24004 /*
24005 ** Close a file.  Make sure the lock has been released before closing.
24006 */
24007 static int dotlockClose(sqlite3_file *id) {
24008   int rc;
24009   if( id ){
24010     unixFile *pFile = (unixFile*)id;
24011     dotlockUnlock(id, NO_LOCK);
24012     sqlite3_free(pFile->lockingContext);
24013   }
24014   rc = closeUnixFile(id);
24015   return rc;
24016 }
24017 /****************** End of the dot-file lock implementation *******************
24018 ******************************************************************************/
24019
24020 /******************************************************************************
24021 ************************** Begin flock Locking ********************************
24022 **
24023 ** Use the flock() system call to do file locking.
24024 **
24025 ** flock() locking is like dot-file locking in that the various
24026 ** fine-grain locking levels supported by SQLite are collapsed into
24027 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
24028 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
24029 ** still works when you do this, but concurrency is reduced since
24030 ** only a single process can be reading the database at a time.
24031 **
24032 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
24033 ** compiling for VXWORKS.
24034 */
24035 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
24036
24037 /*
24038 ** This routine checks if there is a RESERVED lock held on the specified
24039 ** file by this or any other process. If such a lock is held, set *pResOut
24040 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24041 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24042 */
24043 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
24044   int rc = SQLITE_OK;
24045   int reserved = 0;
24046   unixFile *pFile = (unixFile*)id;
24047   
24048   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24049   
24050   assert( pFile );
24051   
24052   /* Check if a thread in this process holds such a lock */
24053   if( pFile->locktype>SHARED_LOCK ){
24054     reserved = 1;
24055   }
24056   
24057   /* Otherwise see if some other process holds it. */
24058   if( !reserved ){
24059     /* attempt to get the lock */
24060     int lrc = flock(pFile->h, LOCK_EX | LOCK_NB);
24061     if( !lrc ){
24062       /* got the lock, unlock it */
24063       lrc = flock(pFile->h, LOCK_UN);
24064       if ( lrc ) {
24065         int tErrno = errno;
24066         /* unlock failed with an error */
24067         lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK); 
24068         if( IS_LOCK_ERROR(lrc) ){
24069           pFile->lastErrno = tErrno;
24070           rc = lrc;
24071         }
24072       }
24073     } else {
24074       int tErrno = errno;
24075       reserved = 1;
24076       /* someone else might have it reserved */
24077       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
24078       if( IS_LOCK_ERROR(lrc) ){
24079         pFile->lastErrno = tErrno;
24080         rc = lrc;
24081       }
24082     }
24083   }
24084   OSTRACE4("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved);
24085
24086 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24087   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
24088     rc = SQLITE_OK;
24089     reserved=1;
24090   }
24091 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24092   *pResOut = reserved;
24093   return rc;
24094 }
24095
24096 /*
24097 ** Lock the file with the lock specified by parameter locktype - one
24098 ** of the following:
24099 **
24100 **     (1) SHARED_LOCK
24101 **     (2) RESERVED_LOCK
24102 **     (3) PENDING_LOCK
24103 **     (4) EXCLUSIVE_LOCK
24104 **
24105 ** Sometimes when requesting one lock state, additional lock states
24106 ** are inserted in between.  The locking might fail on one of the later
24107 ** transitions leaving the lock state different from what it started but
24108 ** still short of its goal.  The following chart shows the allowed
24109 ** transitions and the inserted intermediate states:
24110 **
24111 **    UNLOCKED -> SHARED
24112 **    SHARED -> RESERVED
24113 **    SHARED -> (PENDING) -> EXCLUSIVE
24114 **    RESERVED -> (PENDING) -> EXCLUSIVE
24115 **    PENDING -> EXCLUSIVE
24116 **
24117 ** flock() only really support EXCLUSIVE locks.  We track intermediate
24118 ** lock states in the sqlite3_file structure, but all locks SHARED or
24119 ** above are really EXCLUSIVE locks and exclude all other processes from
24120 ** access the file.
24121 **
24122 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24123 ** routine to lower a locking level.
24124 */
24125 static int flockLock(sqlite3_file *id, int locktype) {
24126   int rc = SQLITE_OK;
24127   unixFile *pFile = (unixFile*)id;
24128
24129   assert( pFile );
24130
24131   /* if we already have a lock, it is exclusive.  
24132   ** Just adjust level and punt on outta here. */
24133   if (pFile->locktype > NO_LOCK) {
24134     pFile->locktype = locktype;
24135     return SQLITE_OK;
24136   }
24137   
24138   /* grab an exclusive lock */
24139   
24140   if (flock(pFile->h, LOCK_EX | LOCK_NB)) {
24141     int tErrno = errno;
24142     /* didn't get, must be busy */
24143     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
24144     if( IS_LOCK_ERROR(rc) ){
24145       pFile->lastErrno = tErrno;
24146     }
24147   } else {
24148     /* got it, set the type and return ok */
24149     pFile->locktype = locktype;
24150   }
24151   OSTRACE4("LOCK    %d %s %s (flock)\n", pFile->h, locktypeName(locktype), 
24152            rc==SQLITE_OK ? "ok" : "failed");
24153 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24154   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
24155     rc = SQLITE_BUSY;
24156   }
24157 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24158   return rc;
24159 }
24160
24161
24162 /*
24163 ** Lower the locking level on file descriptor pFile to locktype.  locktype
24164 ** must be either NO_LOCK or SHARED_LOCK.
24165 **
24166 ** If the locking level of the file descriptor is already at or below
24167 ** the requested locking level, this routine is a no-op.
24168 */
24169 static int flockUnlock(sqlite3_file *id, int locktype) {
24170   unixFile *pFile = (unixFile*)id;
24171   
24172   assert( pFile );
24173   OSTRACE5("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, locktype,
24174            pFile->locktype, getpid());
24175   assert( locktype<=SHARED_LOCK );
24176   
24177   /* no-op if possible */
24178   if( pFile->locktype==locktype ){
24179     return SQLITE_OK;
24180   }
24181   
24182   /* shared can just be set because we always have an exclusive */
24183   if (locktype==SHARED_LOCK) {
24184     pFile->locktype = locktype;
24185     return SQLITE_OK;
24186   }
24187   
24188   /* no, really, unlock. */
24189   int rc = flock(pFile->h, LOCK_UN);
24190   if (rc) {
24191     int r, tErrno = errno;
24192     r = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24193     if( IS_LOCK_ERROR(r) ){
24194       pFile->lastErrno = tErrno;
24195     }
24196 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
24197     if( (r & SQLITE_IOERR) == SQLITE_IOERR ){
24198       r = SQLITE_BUSY;
24199     }
24200 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
24201     
24202     return r;
24203   } else {
24204     pFile->locktype = NO_LOCK;
24205     return SQLITE_OK;
24206   }
24207 }
24208
24209 /*
24210 ** Close a file.
24211 */
24212 static int flockClose(sqlite3_file *id) {
24213   if( id ){
24214     flockUnlock(id, NO_LOCK);
24215   }
24216   return closeUnixFile(id);
24217 }
24218
24219 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
24220
24221 /******************* End of the flock lock implementation *********************
24222 ******************************************************************************/
24223
24224 /******************************************************************************
24225 ************************ Begin Named Semaphore Locking ************************
24226 **
24227 ** Named semaphore locking is only supported on VxWorks.
24228 **
24229 ** Semaphore locking is like dot-lock and flock in that it really only
24230 ** supports EXCLUSIVE locking.  Only a single process can read or write
24231 ** the database file at a time.  This reduces potential concurrency, but
24232 ** makes the lock implementation much easier.
24233 */
24234 #if OS_VXWORKS
24235
24236 /*
24237 ** This routine checks if there is a RESERVED lock held on the specified
24238 ** file by this or any other process. If such a lock is held, set *pResOut
24239 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24240 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24241 */
24242 static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
24243   int rc = SQLITE_OK;
24244   int reserved = 0;
24245   unixFile *pFile = (unixFile*)id;
24246
24247   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24248   
24249   assert( pFile );
24250
24251   /* Check if a thread in this process holds such a lock */
24252   if( pFile->locktype>SHARED_LOCK ){
24253     reserved = 1;
24254   }
24255   
24256   /* Otherwise see if some other process holds it. */
24257   if( !reserved ){
24258     sem_t *pSem = pFile->pOpen->pSem;
24259     struct stat statBuf;
24260
24261     if( sem_trywait(pSem)==-1 ){
24262       int tErrno = errno;
24263       if( EAGAIN != tErrno ){
24264         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
24265         pFile->lastErrno = tErrno;
24266       } else {
24267         /* someone else has the lock when we are in NO_LOCK */
24268         reserved = (pFile->locktype < SHARED_LOCK);
24269       }
24270     }else{
24271       /* we could have it if we want it */
24272       sem_post(pSem);
24273     }
24274   }
24275   OSTRACE4("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved);
24276
24277   *pResOut = reserved;
24278   return rc;
24279 }
24280
24281 /*
24282 ** Lock the file with the lock specified by parameter locktype - one
24283 ** of the following:
24284 **
24285 **     (1) SHARED_LOCK
24286 **     (2) RESERVED_LOCK
24287 **     (3) PENDING_LOCK
24288 **     (4) EXCLUSIVE_LOCK
24289 **
24290 ** Sometimes when requesting one lock state, additional lock states
24291 ** are inserted in between.  The locking might fail on one of the later
24292 ** transitions leaving the lock state different from what it started but
24293 ** still short of its goal.  The following chart shows the allowed
24294 ** transitions and the inserted intermediate states:
24295 **
24296 **    UNLOCKED -> SHARED
24297 **    SHARED -> RESERVED
24298 **    SHARED -> (PENDING) -> EXCLUSIVE
24299 **    RESERVED -> (PENDING) -> EXCLUSIVE
24300 **    PENDING -> EXCLUSIVE
24301 **
24302 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
24303 ** lock states in the sqlite3_file structure, but all locks SHARED or
24304 ** above are really EXCLUSIVE locks and exclude all other processes from
24305 ** access the file.
24306 **
24307 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24308 ** routine to lower a locking level.
24309 */
24310 static int semLock(sqlite3_file *id, int locktype) {
24311   unixFile *pFile = (unixFile*)id;
24312   int fd;
24313   sem_t *pSem = pFile->pOpen->pSem;
24314   int rc = SQLITE_OK;
24315
24316   /* if we already have a lock, it is exclusive.  
24317   ** Just adjust level and punt on outta here. */
24318   if (pFile->locktype > NO_LOCK) {
24319     pFile->locktype = locktype;
24320     rc = SQLITE_OK;
24321     goto sem_end_lock;
24322   }
24323   
24324   /* lock semaphore now but bail out when already locked. */
24325   if( sem_trywait(pSem)==-1 ){
24326     rc = SQLITE_BUSY;
24327     goto sem_end_lock;
24328   }
24329
24330   /* got it, set the type and return ok */
24331   pFile->locktype = locktype;
24332
24333  sem_end_lock:
24334   return rc;
24335 }
24336
24337 /*
24338 ** Lower the locking level on file descriptor pFile to locktype.  locktype
24339 ** must be either NO_LOCK or SHARED_LOCK.
24340 **
24341 ** If the locking level of the file descriptor is already at or below
24342 ** the requested locking level, this routine is a no-op.
24343 */
24344 static int semUnlock(sqlite3_file *id, int locktype) {
24345   unixFile *pFile = (unixFile*)id;
24346   sem_t *pSem = pFile->pOpen->pSem;
24347
24348   assert( pFile );
24349   assert( pSem );
24350   OSTRACE5("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, locktype,
24351            pFile->locktype, getpid());
24352   assert( locktype<=SHARED_LOCK );
24353   
24354   /* no-op if possible */
24355   if( pFile->locktype==locktype ){
24356     return SQLITE_OK;
24357   }
24358   
24359   /* shared can just be set because we always have an exclusive */
24360   if (locktype==SHARED_LOCK) {
24361     pFile->locktype = locktype;
24362     return SQLITE_OK;
24363   }
24364   
24365   /* no, really unlock. */
24366   if ( sem_post(pSem)==-1 ) {
24367     int rc, tErrno = errno;
24368     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
24369     if( IS_LOCK_ERROR(rc) ){
24370       pFile->lastErrno = tErrno;
24371     }
24372     return rc; 
24373   }
24374   pFile->locktype = NO_LOCK;
24375   return SQLITE_OK;
24376 }
24377
24378 /*
24379  ** Close a file.
24380  */
24381 static int semClose(sqlite3_file *id) {
24382   if( id ){
24383     unixFile *pFile = (unixFile*)id;
24384     semUnlock(id, NO_LOCK);
24385     assert( pFile );
24386     unixEnterMutex();
24387     releaseLockInfo(pFile->pLock);
24388     releaseOpenCnt(pFile->pOpen);
24389     unixLeaveMutex();
24390     closeUnixFile(id);
24391   }
24392   return SQLITE_OK;
24393 }
24394
24395 #endif /* OS_VXWORKS */
24396 /*
24397 ** Named semaphore locking is only available on VxWorks.
24398 **
24399 *************** End of the named semaphore lock implementation ****************
24400 ******************************************************************************/
24401
24402
24403 /******************************************************************************
24404 *************************** Begin AFP Locking *********************************
24405 **
24406 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
24407 ** on Apple Macintosh computers - both OS9 and OSX.
24408 **
24409 ** Third-party implementations of AFP are available.  But this code here
24410 ** only works on OSX.
24411 */
24412
24413 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24414 /*
24415 ** The afpLockingContext structure contains all afp lock specific state
24416 */
24417 typedef struct afpLockingContext afpLockingContext;
24418 struct afpLockingContext {
24419   int reserved;
24420   const char *dbPath;             /* Name of the open file */
24421 };
24422
24423 struct ByteRangeLockPB2
24424 {
24425   unsigned long long offset;        /* offset to first byte to lock */
24426   unsigned long long length;        /* nbr of bytes to lock */
24427   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
24428   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
24429   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
24430   int fd;                           /* file desc to assoc this lock with */
24431 };
24432
24433 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
24434
24435 /*
24436 ** This is a utility for setting or clearing a bit-range lock on an
24437 ** AFP filesystem.
24438 ** 
24439 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
24440 */
24441 static int afpSetLock(
24442   const char *path,              /* Name of the file to be locked or unlocked */
24443   unixFile *pFile,               /* Open file descriptor on path */
24444   unsigned long long offset,     /* First byte to be locked */
24445   unsigned long long length,     /* Number of bytes to lock */
24446   int setLockFlag                /* True to set lock.  False to clear lock */
24447 ){
24448   struct ByteRangeLockPB2 pb;
24449   int err;
24450   
24451   pb.unLockFlag = setLockFlag ? 0 : 1;
24452   pb.startEndFlag = 0;
24453   pb.offset = offset;
24454   pb.length = length; 
24455   pb.fd = pFile->h;
24456   
24457   OSTRACE6("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
24458     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
24459     offset, length);
24460   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
24461   if ( err==-1 ) {
24462     int rc;
24463     int tErrno = errno;
24464     OSTRACE4("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
24465              path, tErrno, strerror(tErrno));
24466 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
24467     rc = SQLITE_BUSY;
24468 #else
24469     rc = sqliteErrorFromPosixError(tErrno,
24470                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
24471 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
24472     if( IS_LOCK_ERROR(rc) ){
24473       pFile->lastErrno = tErrno;
24474     }
24475     return rc;
24476   } else {
24477     return SQLITE_OK;
24478   }
24479 }
24480
24481 /*
24482 ** This routine checks if there is a RESERVED lock held on the specified
24483 ** file by this or any other process. If such a lock is held, set *pResOut
24484 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
24485 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
24486 */
24487 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
24488   int rc = SQLITE_OK;
24489   int reserved = 0;
24490   unixFile *pFile = (unixFile*)id;
24491   
24492   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
24493   
24494   assert( pFile );
24495   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
24496   if( context->reserved ){
24497     *pResOut = 1;
24498     return SQLITE_OK;
24499   }
24500   unixEnterMutex(); /* Because pFile->pLock is shared across threads */
24501   
24502   /* Check if a thread in this process holds such a lock */
24503   if( pFile->pLock->locktype>SHARED_LOCK ){
24504     reserved = 1;
24505   }
24506   
24507   /* Otherwise see if some other process holds it.
24508    */
24509   if( !reserved ){
24510     /* lock the RESERVED byte */
24511     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
24512     if( SQLITE_OK==lrc ){
24513       /* if we succeeded in taking the reserved lock, unlock it to restore
24514       ** the original state */
24515       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
24516     } else {
24517       /* if we failed to get the lock then someone else must have it */
24518       reserved = 1;
24519     }
24520     if( IS_LOCK_ERROR(lrc) ){
24521       rc=lrc;
24522     }
24523   }
24524   
24525   unixLeaveMutex();
24526   OSTRACE4("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved);
24527   
24528   *pResOut = reserved;
24529   return rc;
24530 }
24531
24532 /*
24533 ** Lock the file with the lock specified by parameter locktype - one
24534 ** of the following:
24535 **
24536 **     (1) SHARED_LOCK
24537 **     (2) RESERVED_LOCK
24538 **     (3) PENDING_LOCK
24539 **     (4) EXCLUSIVE_LOCK
24540 **
24541 ** Sometimes when requesting one lock state, additional lock states
24542 ** are inserted in between.  The locking might fail on one of the later
24543 ** transitions leaving the lock state different from what it started but
24544 ** still short of its goal.  The following chart shows the allowed
24545 ** transitions and the inserted intermediate states:
24546 **
24547 **    UNLOCKED -> SHARED
24548 **    SHARED -> RESERVED
24549 **    SHARED -> (PENDING) -> EXCLUSIVE
24550 **    RESERVED -> (PENDING) -> EXCLUSIVE
24551 **    PENDING -> EXCLUSIVE
24552 **
24553 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
24554 ** routine to lower a locking level.
24555 */
24556 static int afpLock(sqlite3_file *id, int locktype){
24557   int rc = SQLITE_OK;
24558   unixFile *pFile = (unixFile*)id;
24559   struct unixLockInfo *pLock = pFile->pLock;
24560   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
24561   
24562   assert( pFile );
24563   OSTRACE7("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
24564            locktypeName(locktype), locktypeName(pFile->locktype),
24565            locktypeName(pLock->locktype), pLock->cnt , getpid());
24566
24567   /* If there is already a lock of this type or more restrictive on the
24568   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
24569   ** unixEnterMutex() hasn't been called yet.
24570   */
24571   if( pFile->locktype>=locktype ){
24572     OSTRACE3("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
24573            locktypeName(locktype));
24574     return SQLITE_OK;
24575   }
24576
24577   /* Make sure the locking sequence is correct
24578   **  (1) We never move from unlocked to anything higher than shared lock.
24579   **  (2) SQLite never explicitly requests a pendig lock.
24580   **  (3) A shared lock is always held when a reserve lock is requested.
24581   */
24582   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
24583   assert( locktype!=PENDING_LOCK );
24584   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
24585   
24586   /* This mutex is needed because pFile->pLock is shared across threads
24587   */
24588   unixEnterMutex();
24589
24590   /* Make sure the current thread owns the pFile.
24591   */
24592   rc = transferOwnership(pFile);
24593   if( rc!=SQLITE_OK ){
24594     unixLeaveMutex();
24595     return rc;
24596   }
24597   pLock = pFile->pLock;
24598
24599   /* If some thread using this PID has a lock via a different unixFile*
24600   ** handle that precludes the requested lock, return BUSY.
24601   */
24602   if( (pFile->locktype!=pLock->locktype && 
24603        (pLock->locktype>=PENDING_LOCK || locktype>SHARED_LOCK))
24604      ){
24605     rc = SQLITE_BUSY;
24606     goto afp_end_lock;
24607   }
24608   
24609   /* If a SHARED lock is requested, and some thread using this PID already
24610   ** has a SHARED or RESERVED lock, then increment reference counts and
24611   ** return SQLITE_OK.
24612   */
24613   if( locktype==SHARED_LOCK && 
24614      (pLock->locktype==SHARED_LOCK || pLock->locktype==RESERVED_LOCK) ){
24615     assert( locktype==SHARED_LOCK );
24616     assert( pFile->locktype==0 );
24617     assert( pLock->cnt>0 );
24618     pFile->locktype = SHARED_LOCK;
24619     pLock->cnt++;
24620     pFile->pOpen->nLock++;
24621     goto afp_end_lock;
24622   }
24623     
24624   /* A PENDING lock is needed before acquiring a SHARED lock and before
24625   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
24626   ** be released.
24627   */
24628   if( locktype==SHARED_LOCK 
24629       || (locktype==EXCLUSIVE_LOCK && pFile->locktype<PENDING_LOCK)
24630   ){
24631     int failed;
24632     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
24633     if (failed) {
24634       rc = failed;
24635       goto afp_end_lock;
24636     }
24637   }
24638   
24639   /* If control gets to this point, then actually go ahead and make
24640   ** operating system calls for the specified lock.
24641   */
24642   if( locktype==SHARED_LOCK ){
24643     int lrc1, lrc2, lrc1Errno;
24644     long lk, mask;
24645     
24646     assert( pLock->cnt==0 );
24647     assert( pLock->locktype==0 );
24648         
24649     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
24650     /* Now get the read-lock SHARED_LOCK */
24651     /* note that the quality of the randomness doesn't matter that much */
24652     lk = random(); 
24653     pLock->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
24654     lrc1 = afpSetLock(context->dbPath, pFile, 
24655           SHARED_FIRST+pLock->sharedByte, 1, 1);
24656     if( IS_LOCK_ERROR(lrc1) ){
24657       lrc1Errno = pFile->lastErrno;
24658     }
24659     /* Drop the temporary PENDING lock */
24660     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
24661     
24662     if( IS_LOCK_ERROR(lrc1) ) {
24663       pFile->lastErrno = lrc1Errno;
24664       rc = lrc1;
24665       goto afp_end_lock;
24666     } else if( IS_LOCK_ERROR(lrc2) ){
24667       rc = lrc2;
24668       goto afp_end_lock;
24669     } else if( lrc1 != SQLITE_OK ) {
24670       rc = lrc1;
24671     } else {
24672       pFile->locktype = SHARED_LOCK;
24673       pFile->pOpen->nLock++;
24674       pLock->cnt = 1;
24675     }
24676   }else if( locktype==EXCLUSIVE_LOCK && pLock->cnt>1 ){
24677     /* We are trying for an exclusive lock but another thread in this
24678      ** same process is still holding a shared lock. */
24679     rc = SQLITE_BUSY;
24680   }else{
24681     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
24682     ** assumed that there is a SHARED or greater lock on the file
24683     ** already.
24684     */
24685     int failed = 0;
24686     assert( 0!=pFile->locktype );
24687     if (locktype >= RESERVED_LOCK && pFile->locktype < RESERVED_LOCK) {
24688         /* Acquire a RESERVED lock */
24689         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
24690       if( !failed ){
24691         context->reserved = 1;
24692       }
24693     }
24694     if (!failed && locktype == EXCLUSIVE_LOCK) {
24695       /* Acquire an EXCLUSIVE lock */
24696         
24697       /* Remove the shared lock before trying the range.  we'll need to 
24698       ** reestablish the shared lock if we can't get the  afpUnlock
24699       */
24700       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
24701                          pLock->sharedByte, 1, 0)) ){
24702         int failed2 = SQLITE_OK;
24703         /* now attemmpt to get the exclusive lock range */
24704         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
24705                                SHARED_SIZE, 1);
24706         if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
24707                        SHARED_FIRST + pLock->sharedByte, 1, 1)) ){
24708           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
24709           ** a critical I/O error
24710           */
24711           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 
24712                SQLITE_IOERR_LOCK;
24713           goto afp_end_lock;
24714         } 
24715       }else{
24716         rc = failed; 
24717       }
24718     }
24719     if( failed ){
24720       rc = failed;
24721     }
24722   }
24723   
24724   if( rc==SQLITE_OK ){
24725     pFile->locktype = locktype;
24726     pLock->locktype = locktype;
24727   }else if( locktype==EXCLUSIVE_LOCK ){
24728     pFile->locktype = PENDING_LOCK;
24729     pLock->locktype = PENDING_LOCK;
24730   }
24731   
24732 afp_end_lock:
24733   unixLeaveMutex();
24734   OSTRACE4("LOCK    %d %s %s (afp)\n", pFile->h, locktypeName(locktype), 
24735          rc==SQLITE_OK ? "ok" : "failed");
24736   return rc;
24737 }
24738
24739 /*
24740 ** Lower the locking level on file descriptor pFile to locktype.  locktype
24741 ** must be either NO_LOCK or SHARED_LOCK.
24742 **
24743 ** If the locking level of the file descriptor is already at or below
24744 ** the requested locking level, this routine is a no-op.
24745 */
24746 static int afpUnlock(sqlite3_file *id, int locktype) {
24747   int rc = SQLITE_OK;
24748   unixFile *pFile = (unixFile*)id;
24749   struct unixLockInfo *pLock;
24750   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
24751   int skipShared = 0;
24752 #ifdef SQLITE_TEST
24753   int h = pFile->h;
24754 #endif
24755
24756   assert( pFile );
24757   OSTRACE7("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, locktype,
24758            pFile->locktype, pFile->pLock->locktype, pFile->pLock->cnt, getpid());
24759
24760   assert( locktype<=SHARED_LOCK );
24761   if( pFile->locktype<=locktype ){
24762     return SQLITE_OK;
24763   }
24764   if( CHECK_THREADID(pFile) ){
24765     return SQLITE_MISUSE_BKPT;
24766   }
24767   unixEnterMutex();
24768   pLock = pFile->pLock;
24769   assert( pLock->cnt!=0 );
24770   if( pFile->locktype>SHARED_LOCK ){
24771     assert( pLock->locktype==pFile->locktype );
24772     SimulateIOErrorBenign(1);
24773     SimulateIOError( h=(-1) )
24774     SimulateIOErrorBenign(0);
24775     
24776 #ifndef NDEBUG
24777     /* When reducing a lock such that other processes can start
24778     ** reading the database file again, make sure that the
24779     ** transaction counter was updated if any part of the database
24780     ** file changed.  If the transaction counter is not updated,
24781     ** other connections to the same file might not realize that
24782     ** the file has changed and hence might not know to flush their
24783     ** cache.  The use of a stale cache can lead to database corruption.
24784     */
24785     assert( pFile->inNormalWrite==0
24786            || pFile->dbUpdate==0
24787            || pFile->transCntrChng==1 );
24788     pFile->inNormalWrite = 0;
24789 #endif
24790     
24791     if( pFile->locktype==EXCLUSIVE_LOCK ){
24792       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
24793       if( rc==SQLITE_OK && (locktype==SHARED_LOCK || pLock->cnt>1) ){
24794         /* only re-establish the shared lock if necessary */
24795         int sharedLockByte = SHARED_FIRST+pLock->sharedByte;
24796         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
24797       } else {
24798         skipShared = 1;
24799       }
24800     }
24801     if( rc==SQLITE_OK && pFile->locktype>=PENDING_LOCK ){
24802       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
24803     } 
24804     if( rc==SQLITE_OK && pFile->locktype>=RESERVED_LOCK && context->reserved ){
24805       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
24806       if( !rc ){ 
24807         context->reserved = 0; 
24808       }
24809     }
24810     if( rc==SQLITE_OK && (locktype==SHARED_LOCK || pLock->cnt>1)){
24811       pLock->locktype = SHARED_LOCK;
24812     }
24813   }
24814   if( rc==SQLITE_OK && locktype==NO_LOCK ){
24815
24816     /* Decrement the shared lock counter.  Release the lock using an
24817     ** OS call only when all threads in this same process have released
24818     ** the lock.
24819     */
24820     unsigned long long sharedLockByte = SHARED_FIRST+pLock->sharedByte;
24821     pLock->cnt--;
24822     if( pLock->cnt==0 ){
24823       SimulateIOErrorBenign(1);
24824       SimulateIOError( h=(-1) )
24825       SimulateIOErrorBenign(0);
24826       if( !skipShared ){
24827         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
24828       }
24829       if( !rc ){
24830         pLock->locktype = NO_LOCK;
24831         pFile->locktype = NO_LOCK;
24832       }
24833     }
24834     if( rc==SQLITE_OK ){
24835       struct unixOpenCnt *pOpen = pFile->pOpen;
24836         
24837       pOpen->nLock--;
24838       assert( pOpen->nLock>=0 );
24839       if( pOpen->nLock==0 ){
24840         rc = closePendingFds(pFile);
24841       }
24842     }
24843   }
24844   
24845   unixLeaveMutex();
24846   if( rc==SQLITE_OK ) pFile->locktype = locktype;
24847   return rc;
24848 }
24849
24850 /*
24851 ** Close a file & cleanup AFP specific locking context 
24852 */
24853 static int afpClose(sqlite3_file *id) {
24854   int rc = SQLITE_OK;
24855   if( id ){
24856     unixFile *pFile = (unixFile*)id;
24857     afpUnlock(id, NO_LOCK);
24858     unixEnterMutex();
24859     if( pFile->pOpen && pFile->pOpen->nLock ){
24860       /* If there are outstanding locks, do not actually close the file just
24861       ** yet because that would clear those locks.  Instead, add the file
24862       ** descriptor to pOpen->aPending.  It will be automatically closed when
24863       ** the last lock is cleared.
24864       */
24865       setPendingFd(pFile);
24866     }
24867     releaseLockInfo(pFile->pLock);
24868     releaseOpenCnt(pFile->pOpen);
24869     sqlite3_free(pFile->lockingContext);
24870     rc = closeUnixFile(id);
24871     unixLeaveMutex();
24872   }
24873   return rc;
24874 }
24875
24876 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24877 /*
24878 ** The code above is the AFP lock implementation.  The code is specific
24879 ** to MacOSX and does not work on other unix platforms.  No alternative
24880 ** is available.  If you don't compile for a mac, then the "unix-afp"
24881 ** VFS is not available.
24882 **
24883 ********************* End of the AFP lock implementation **********************
24884 ******************************************************************************/
24885
24886 /******************************************************************************
24887 *************************** Begin NFS Locking ********************************/
24888
24889 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
24890 /*
24891  ** Lower the locking level on file descriptor pFile to locktype.  locktype
24892  ** must be either NO_LOCK or SHARED_LOCK.
24893  **
24894  ** If the locking level of the file descriptor is already at or below
24895  ** the requested locking level, this routine is a no-op.
24896  */
24897 static int nfsUnlock(sqlite3_file *id, int locktype){
24898   return _posixUnlock(id, locktype, 1);
24899 }
24900
24901 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
24902 /*
24903 ** The code above is the NFS lock implementation.  The code is specific
24904 ** to MacOSX and does not work on other unix platforms.  No alternative
24905 ** is available.  
24906 **
24907 ********************* End of the NFS lock implementation **********************
24908 ******************************************************************************/
24909
24910 /******************************************************************************
24911 **************** Non-locking sqlite3_file methods *****************************
24912 **
24913 ** The next division contains implementations for all methods of the 
24914 ** sqlite3_file object other than the locking methods.  The locking
24915 ** methods were defined in divisions above (one locking method per
24916 ** division).  Those methods that are common to all locking modes
24917 ** are gather together into this division.
24918 */
24919
24920 /*
24921 ** Seek to the offset passed as the second argument, then read cnt 
24922 ** bytes into pBuf. Return the number of bytes actually read.
24923 **
24924 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
24925 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
24926 ** one system to another.  Since SQLite does not define USE_PREAD
24927 ** any any form by default, we will not attempt to define _XOPEN_SOURCE.
24928 ** See tickets #2741 and #2681.
24929 **
24930 ** To avoid stomping the errno value on a failed read the lastErrno value
24931 ** is set before returning.
24932 */
24933 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
24934   int got;
24935 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
24936   i64 newOffset;
24937 #endif
24938   TIMER_START;
24939 #if defined(USE_PREAD)
24940   got = pread(id->h, pBuf, cnt, offset);
24941   SimulateIOError( got = -1 );
24942 #elif defined(USE_PREAD64)
24943   got = pread64(id->h, pBuf, cnt, offset);
24944   SimulateIOError( got = -1 );
24945 #else
24946   newOffset = lseek(id->h, offset, SEEK_SET);
24947   SimulateIOError( newOffset-- );
24948   if( newOffset!=offset ){
24949     if( newOffset == -1 ){
24950       ((unixFile*)id)->lastErrno = errno;
24951     }else{
24952       ((unixFile*)id)->lastErrno = 0;                   
24953     }
24954     return -1;
24955   }
24956   got = read(id->h, pBuf, cnt);
24957 #endif
24958   TIMER_END;
24959   if( got<0 ){
24960     ((unixFile*)id)->lastErrno = errno;
24961   }
24962   OSTRACE5("READ    %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
24963   return got;
24964 }
24965
24966 /*
24967 ** Read data from a file into a buffer.  Return SQLITE_OK if all
24968 ** bytes were read successfully and SQLITE_IOERR if anything goes
24969 ** wrong.
24970 */
24971 static int unixRead(
24972   sqlite3_file *id, 
24973   void *pBuf, 
24974   int amt,
24975   sqlite3_int64 offset
24976 ){
24977   unixFile *pFile = (unixFile *)id;
24978   int got;
24979   assert( id );
24980
24981   /* If this is a database file (not a journal, master-journal or temp
24982   ** file), the bytes in the locking range should never be read or written. */
24983   assert( pFile->pUnused==0
24984        || offset>=PENDING_BYTE+512
24985        || offset+amt<=PENDING_BYTE 
24986   );
24987
24988   got = seekAndRead(pFile, offset, pBuf, amt);
24989   if( got==amt ){
24990     return SQLITE_OK;
24991   }else if( got<0 ){
24992     /* lastErrno set by seekAndRead */
24993     return SQLITE_IOERR_READ;
24994   }else{
24995     pFile->lastErrno = 0; /* not a system error */
24996     /* Unread parts of the buffer must be zero-filled */
24997     memset(&((char*)pBuf)[got], 0, amt-got);
24998     return SQLITE_IOERR_SHORT_READ;
24999   }
25000 }
25001
25002 /*
25003 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
25004 ** Return the number of bytes actually read.  Update the offset.
25005 **
25006 ** To avoid stomping the errno value on a failed write the lastErrno value
25007 ** is set before returning.
25008 */
25009 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
25010   int got;
25011 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
25012   i64 newOffset;
25013 #endif
25014   TIMER_START;
25015 #if defined(USE_PREAD)
25016   got = pwrite(id->h, pBuf, cnt, offset);
25017 #elif defined(USE_PREAD64)
25018   got = pwrite64(id->h, pBuf, cnt, offset);
25019 #else
25020   newOffset = lseek(id->h, offset, SEEK_SET);
25021   if( newOffset!=offset ){
25022     if( newOffset == -1 ){
25023       ((unixFile*)id)->lastErrno = errno;
25024     }else{
25025       ((unixFile*)id)->lastErrno = 0;                   
25026     }
25027     return -1;
25028   }
25029   got = write(id->h, pBuf, cnt);
25030 #endif
25031   TIMER_END;
25032   if( got<0 ){
25033     ((unixFile*)id)->lastErrno = errno;
25034   }
25035
25036   OSTRACE5("WRITE   %-3d %5d %7lld %llu\n", id->h, got, offset, TIMER_ELAPSED);
25037   return got;
25038 }
25039
25040
25041 /*
25042 ** Write data from a buffer into a file.  Return SQLITE_OK on success
25043 ** or some other error code on failure.
25044 */
25045 static int unixWrite(
25046   sqlite3_file *id, 
25047   const void *pBuf, 
25048   int amt,
25049   sqlite3_int64 offset 
25050 ){
25051   unixFile *pFile = (unixFile*)id;
25052   int wrote = 0;
25053   assert( id );
25054   assert( amt>0 );
25055
25056   /* If this is a database file (not a journal, master-journal or temp
25057   ** file), the bytes in the locking range should never be read or written. */
25058   assert( pFile->pUnused==0
25059        || offset>=PENDING_BYTE+512
25060        || offset+amt<=PENDING_BYTE 
25061   );
25062
25063 #ifndef NDEBUG
25064   /* If we are doing a normal write to a database file (as opposed to
25065   ** doing a hot-journal rollback or a write to some file other than a
25066   ** normal database file) then record the fact that the database
25067   ** has changed.  If the transaction counter is modified, record that
25068   ** fact too.
25069   */
25070   if( pFile->inNormalWrite ){
25071     pFile->dbUpdate = 1;  /* The database has been modified */
25072     if( offset<=24 && offset+amt>=27 ){
25073       int rc;
25074       char oldCntr[4];
25075       SimulateIOErrorBenign(1);
25076       rc = seekAndRead(pFile, 24, oldCntr, 4);
25077       SimulateIOErrorBenign(0);
25078       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
25079         pFile->transCntrChng = 1;  /* The transaction counter has changed */
25080       }
25081     }
25082   }
25083 #endif
25084
25085   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
25086     amt -= wrote;
25087     offset += wrote;
25088     pBuf = &((char*)pBuf)[wrote];
25089   }
25090   SimulateIOError(( wrote=(-1), amt=1 ));
25091   SimulateDiskfullError(( wrote=0, amt=1 ));
25092   if( amt>0 ){
25093     if( wrote<0 ){
25094       /* lastErrno set by seekAndWrite */
25095       return SQLITE_IOERR_WRITE;
25096     }else{
25097       pFile->lastErrno = 0; /* not a system error */
25098       return SQLITE_FULL;
25099     }
25100   }
25101   return SQLITE_OK;
25102 }
25103
25104 #ifdef SQLITE_TEST
25105 /*
25106 ** Count the number of fullsyncs and normal syncs.  This is used to test
25107 ** that syncs and fullsyncs are occurring at the right times.
25108 */
25109 SQLITE_API int sqlite3_sync_count = 0;
25110 SQLITE_API int sqlite3_fullsync_count = 0;
25111 #endif
25112
25113 /*
25114 ** We do not trust systems to provide a working fdatasync().  Some do.
25115 ** Others do no.  To be safe, we will stick with the (slower) fsync().
25116 ** If you know that your system does support fdatasync() correctly,
25117 ** then simply compile with -Dfdatasync=fdatasync
25118 */
25119 #if !defined(fdatasync) && !defined(__linux__)
25120 # define fdatasync fsync
25121 #endif
25122
25123 /*
25124 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
25125 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
25126 ** only available on Mac OS X.  But that could change.
25127 */
25128 #ifdef F_FULLFSYNC
25129 # define HAVE_FULLFSYNC 1
25130 #else
25131 # define HAVE_FULLFSYNC 0
25132 #endif
25133
25134
25135 /*
25136 ** The fsync() system call does not work as advertised on many
25137 ** unix systems.  The following procedure is an attempt to make
25138 ** it work better.
25139 **
25140 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
25141 ** for testing when we want to run through the test suite quickly.
25142 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
25143 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
25144 ** or power failure will likely corrupt the database file.
25145 **
25146 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
25147 ** The idea behind dataOnly is that it should only write the file content
25148 ** to disk, not the inode.  We only set dataOnly if the file size is 
25149 ** unchanged since the file size is part of the inode.  However, 
25150 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
25151 ** file size has changed.  The only real difference between fdatasync()
25152 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
25153 ** inode if the mtime or owner or other inode attributes have changed.
25154 ** We only care about the file size, not the other file attributes, so
25155 ** as far as SQLite is concerned, an fdatasync() is always adequate.
25156 ** So, we always use fdatasync() if it is available, regardless of
25157 ** the value of the dataOnly flag.
25158 */
25159 static int full_fsync(int fd, int fullSync, int dataOnly){
25160   int rc;
25161
25162   /* The following "ifdef/elif/else/" block has the same structure as
25163   ** the one below. It is replicated here solely to avoid cluttering 
25164   ** up the real code with the UNUSED_PARAMETER() macros.
25165   */
25166 #ifdef SQLITE_NO_SYNC
25167   UNUSED_PARAMETER(fd);
25168   UNUSED_PARAMETER(fullSync);
25169   UNUSED_PARAMETER(dataOnly);
25170 #elif HAVE_FULLFSYNC
25171   UNUSED_PARAMETER(dataOnly);
25172 #else
25173   UNUSED_PARAMETER(fullSync);
25174   UNUSED_PARAMETER(dataOnly);
25175 #endif
25176
25177   /* Record the number of times that we do a normal fsync() and 
25178   ** FULLSYNC.  This is used during testing to verify that this procedure
25179   ** gets called with the correct arguments.
25180   */
25181 #ifdef SQLITE_TEST
25182   if( fullSync ) sqlite3_fullsync_count++;
25183   sqlite3_sync_count++;
25184 #endif
25185
25186   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
25187   ** no-op
25188   */
25189 #ifdef SQLITE_NO_SYNC
25190   rc = SQLITE_OK;
25191 #elif HAVE_FULLFSYNC
25192   if( fullSync ){
25193     rc = fcntl(fd, F_FULLFSYNC, 0);
25194   }else{
25195     rc = 1;
25196   }
25197   /* If the FULLFSYNC failed, fall back to attempting an fsync().
25198   ** It shouldn't be possible for fullfsync to fail on the local 
25199   ** file system (on OSX), so failure indicates that FULLFSYNC
25200   ** isn't supported for this file system. So, attempt an fsync 
25201   ** and (for now) ignore the overhead of a superfluous fcntl call.  
25202   ** It'd be better to detect fullfsync support once and avoid 
25203   ** the fcntl call every time sync is called.
25204   */
25205   if( rc ) rc = fsync(fd);
25206
25207 #elif defined(__APPLE__)
25208   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
25209   ** so currently we default to the macro that redefines fdatasync to fsync
25210   */
25211   rc = fsync(fd);
25212 #else 
25213   rc = fdatasync(fd);
25214 #if OS_VXWORKS
25215   if( rc==-1 && errno==ENOTSUP ){
25216     rc = fsync(fd);
25217   }
25218 #endif /* OS_VXWORKS */
25219 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
25220
25221   if( OS_VXWORKS && rc!= -1 ){
25222     rc = 0;
25223   }
25224   return rc;
25225 }
25226
25227 /*
25228 ** Make sure all writes to a particular file are committed to disk.
25229 **
25230 ** If dataOnly==0 then both the file itself and its metadata (file
25231 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
25232 ** file data is synced.
25233 **
25234 ** Under Unix, also make sure that the directory entry for the file
25235 ** has been created by fsync-ing the directory that contains the file.
25236 ** If we do not do this and we encounter a power failure, the directory
25237 ** entry for the journal might not exist after we reboot.  The next
25238 ** SQLite to access the file will not know that the journal exists (because
25239 ** the directory entry for the journal was never created) and the transaction
25240 ** will not roll back - possibly leading to database corruption.
25241 */
25242 static int unixSync(sqlite3_file *id, int flags){
25243   int rc;
25244   unixFile *pFile = (unixFile*)id;
25245
25246   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
25247   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
25248
25249   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
25250   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
25251       || (flags&0x0F)==SQLITE_SYNC_FULL
25252   );
25253
25254   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
25255   ** line is to test that doing so does not cause any problems.
25256   */
25257   SimulateDiskfullError( return SQLITE_FULL );
25258
25259   assert( pFile );
25260   OSTRACE2("SYNC    %-3d\n", pFile->h);
25261   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
25262   SimulateIOError( rc=1 );
25263   if( rc ){
25264     pFile->lastErrno = errno;
25265     return SQLITE_IOERR_FSYNC;
25266   }
25267   if( pFile->dirfd>=0 ){
25268     int err;
25269     OSTRACE4("DIRSYNC %-3d (have_fullfsync=%d fullsync=%d)\n", pFile->dirfd,
25270             HAVE_FULLFSYNC, isFullsync);
25271 #ifndef SQLITE_DISABLE_DIRSYNC
25272     /* The directory sync is only attempted if full_fsync is
25273     ** turned off or unavailable.  If a full_fsync occurred above,
25274     ** then the directory sync is superfluous.
25275     */
25276     if( (!HAVE_FULLFSYNC || !isFullsync) && full_fsync(pFile->dirfd,0,0) ){
25277        /*
25278        ** We have received multiple reports of fsync() returning
25279        ** errors when applied to directories on certain file systems.
25280        ** A failed directory sync is not a big deal.  So it seems
25281        ** better to ignore the error.  Ticket #1657
25282        */
25283        /* pFile->lastErrno = errno; */
25284        /* return SQLITE_IOERR; */
25285     }
25286 #endif
25287     err = close(pFile->dirfd); /* Only need to sync once, so close the */
25288     if( err==0 ){              /* directory when we are done */
25289       pFile->dirfd = -1;
25290     }else{
25291       pFile->lastErrno = errno;
25292       rc = SQLITE_IOERR_DIR_CLOSE;
25293     }
25294   }
25295   return rc;
25296 }
25297
25298 /*
25299 ** Truncate an open file to a specified size
25300 */
25301 static int unixTruncate(sqlite3_file *id, i64 nByte){
25302   int rc;
25303   assert( id );
25304   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
25305   rc = ftruncate(((unixFile*)id)->h, (off_t)nByte);
25306   if( rc ){
25307     ((unixFile*)id)->lastErrno = errno;
25308     return SQLITE_IOERR_TRUNCATE;
25309   }else{
25310 #ifndef NDEBUG
25311     /* If we are doing a normal write to a database file (as opposed to
25312     ** doing a hot-journal rollback or a write to some file other than a
25313     ** normal database file) and we truncate the file to zero length,
25314     ** that effectively updates the change counter.  This might happen
25315     ** when restoring a database using the backup API from a zero-length
25316     ** source.
25317     */
25318     if( ((unixFile*)id)->inNormalWrite && nByte==0 ){
25319       ((unixFile*)id)->transCntrChng = 1;
25320     }
25321 #endif
25322
25323     return SQLITE_OK;
25324   }
25325 }
25326
25327 /*
25328 ** Determine the current size of a file in bytes
25329 */
25330 static int unixFileSize(sqlite3_file *id, i64 *pSize){
25331   int rc;
25332   struct stat buf;
25333   assert( id );
25334   rc = fstat(((unixFile*)id)->h, &buf);
25335   SimulateIOError( rc=1 );
25336   if( rc!=0 ){
25337     ((unixFile*)id)->lastErrno = errno;
25338     return SQLITE_IOERR_FSTAT;
25339   }
25340   *pSize = buf.st_size;
25341
25342   /* When opening a zero-size database, the findLockInfo() procedure
25343   ** writes a single byte into that file in order to work around a bug
25344   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
25345   ** layers, we need to report this file size as zero even though it is
25346   ** really 1.   Ticket #3260.
25347   */
25348   if( *pSize==1 ) *pSize = 0;
25349
25350
25351   return SQLITE_OK;
25352 }
25353
25354 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25355 /*
25356 ** Handler for proxy-locking file-control verbs.  Defined below in the
25357 ** proxying locking division.
25358 */
25359 static int proxyFileControl(sqlite3_file*,int,void*);
25360 #endif
25361
25362
25363 /*
25364 ** Information and control of an open file handle.
25365 */
25366 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
25367   switch( op ){
25368     case SQLITE_FCNTL_LOCKSTATE: {
25369       *(int*)pArg = ((unixFile*)id)->locktype;
25370       return SQLITE_OK;
25371     }
25372     case SQLITE_LAST_ERRNO: {
25373       *(int*)pArg = ((unixFile*)id)->lastErrno;
25374       return SQLITE_OK;
25375     }
25376 #ifndef NDEBUG
25377     /* The pager calls this method to signal that it has done
25378     ** a rollback and that the database is therefore unchanged and
25379     ** it hence it is OK for the transaction change counter to be
25380     ** unchanged.
25381     */
25382     case SQLITE_FCNTL_DB_UNCHANGED: {
25383       ((unixFile*)id)->dbUpdate = 0;
25384       return SQLITE_OK;
25385     }
25386 #endif
25387 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25388     case SQLITE_SET_LOCKPROXYFILE:
25389     case SQLITE_GET_LOCKPROXYFILE: {
25390       return proxyFileControl(id,op,pArg);
25391     }
25392 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
25393   }
25394   return SQLITE_ERROR;
25395 }
25396
25397 /*
25398 ** Return the sector size in bytes of the underlying block device for
25399 ** the specified file. This is almost always 512 bytes, but may be
25400 ** larger for some devices.
25401 **
25402 ** SQLite code assumes this function cannot fail. It also assumes that
25403 ** if two files are created in the same file-system directory (i.e.
25404 ** a database and its journal file) that the sector size will be the
25405 ** same for both.
25406 */
25407 static int unixSectorSize(sqlite3_file *NotUsed){
25408   UNUSED_PARAMETER(NotUsed);
25409   return SQLITE_DEFAULT_SECTOR_SIZE;
25410 }
25411
25412 /*
25413 ** Return the device characteristics for the file. This is always 0 for unix.
25414 */
25415 static int unixDeviceCharacteristics(sqlite3_file *NotUsed){
25416   UNUSED_PARAMETER(NotUsed);
25417   return 0;
25418 }
25419
25420 /*
25421 ** Here ends the implementation of all sqlite3_file methods.
25422 **
25423 ********************** End sqlite3_file Methods *******************************
25424 ******************************************************************************/
25425
25426 /*
25427 ** This division contains definitions of sqlite3_io_methods objects that
25428 ** implement various file locking strategies.  It also contains definitions
25429 ** of "finder" functions.  A finder-function is used to locate the appropriate
25430 ** sqlite3_io_methods object for a particular database file.  The pAppData
25431 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
25432 ** the correct finder-function for that VFS.
25433 **
25434 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
25435 ** object.  The only interesting finder-function is autolockIoFinder, which
25436 ** looks at the filesystem type and tries to guess the best locking
25437 ** strategy from that.
25438 **
25439 ** For finder-funtion F, two objects are created:
25440 **
25441 **    (1) The real finder-function named "FImpt()".
25442 **
25443 **    (2) A constant pointer to this function named just "F".
25444 **
25445 **
25446 ** A pointer to the F pointer is used as the pAppData value for VFS
25447 ** objects.  We have to do this instead of letting pAppData point
25448 ** directly at the finder-function since C90 rules prevent a void*
25449 ** from be cast into a function pointer.
25450 **
25451 **
25452 ** Each instance of this macro generates two objects:
25453 **
25454 **   *  A constant sqlite3_io_methods object call METHOD that has locking
25455 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
25456 **
25457 **   *  An I/O method finder function called FINDER that returns a pointer
25458 **      to the METHOD object in the previous bullet.
25459 */
25460 #define IOMETHODS(FINDER, METHOD, CLOSE, LOCK, UNLOCK, CKLOCK)               \
25461 static const sqlite3_io_methods METHOD = {                                   \
25462    1,                          /* iVersion */                                \
25463    CLOSE,                      /* xClose */                                  \
25464    unixRead,                   /* xRead */                                   \
25465    unixWrite,                  /* xWrite */                                  \
25466    unixTruncate,               /* xTruncate */                               \
25467    unixSync,                   /* xSync */                                   \
25468    unixFileSize,               /* xFileSize */                               \
25469    LOCK,                       /* xLock */                                   \
25470    UNLOCK,                     /* xUnlock */                                 \
25471    CKLOCK,                     /* xCheckReservedLock */                      \
25472    unixFileControl,            /* xFileControl */                            \
25473    unixSectorSize,             /* xSectorSize */                             \
25474    unixDeviceCharacteristics   /* xDeviceCapabilities */                     \
25475 };                                                                           \
25476 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
25477   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
25478   return &METHOD;                                                            \
25479 }                                                                            \
25480 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
25481     = FINDER##Impl;
25482
25483 /*
25484 ** Here are all of the sqlite3_io_methods objects for each of the
25485 ** locking strategies.  Functions that return pointers to these methods
25486 ** are also created.
25487 */
25488 IOMETHODS(
25489   posixIoFinder,            /* Finder function name */
25490   posixIoMethods,           /* sqlite3_io_methods object name */
25491   unixClose,                /* xClose method */
25492   unixLock,                 /* xLock method */
25493   unixUnlock,               /* xUnlock method */
25494   unixCheckReservedLock     /* xCheckReservedLock method */
25495 )
25496 IOMETHODS(
25497   nolockIoFinder,           /* Finder function name */
25498   nolockIoMethods,          /* sqlite3_io_methods object name */
25499   nolockClose,              /* xClose method */
25500   nolockLock,               /* xLock method */
25501   nolockUnlock,             /* xUnlock method */
25502   nolockCheckReservedLock   /* xCheckReservedLock method */
25503 )
25504 IOMETHODS(
25505   dotlockIoFinder,          /* Finder function name */
25506   dotlockIoMethods,         /* sqlite3_io_methods object name */
25507   dotlockClose,             /* xClose method */
25508   dotlockLock,              /* xLock method */
25509   dotlockUnlock,            /* xUnlock method */
25510   dotlockCheckReservedLock  /* xCheckReservedLock method */
25511 )
25512
25513 #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
25514 IOMETHODS(
25515   flockIoFinder,            /* Finder function name */
25516   flockIoMethods,           /* sqlite3_io_methods object name */
25517   flockClose,               /* xClose method */
25518   flockLock,                /* xLock method */
25519   flockUnlock,              /* xUnlock method */
25520   flockCheckReservedLock    /* xCheckReservedLock method */
25521 )
25522 #endif
25523
25524 #if OS_VXWORKS
25525 IOMETHODS(
25526   semIoFinder,              /* Finder function name */
25527   semIoMethods,             /* sqlite3_io_methods object name */
25528   semClose,                 /* xClose method */
25529   semLock,                  /* xLock method */
25530   semUnlock,                /* xUnlock method */
25531   semCheckReservedLock      /* xCheckReservedLock method */
25532 )
25533 #endif
25534
25535 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25536 IOMETHODS(
25537   afpIoFinder,              /* Finder function name */
25538   afpIoMethods,             /* sqlite3_io_methods object name */
25539   afpClose,                 /* xClose method */
25540   afpLock,                  /* xLock method */
25541   afpUnlock,                /* xUnlock method */
25542   afpCheckReservedLock      /* xCheckReservedLock method */
25543 )
25544 #endif
25545
25546 /*
25547 ** The proxy locking method is a "super-method" in the sense that it
25548 ** opens secondary file descriptors for the conch and lock files and
25549 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
25550 ** secondary files.  For this reason, the division that implements
25551 ** proxy locking is located much further down in the file.  But we need
25552 ** to go ahead and define the sqlite3_io_methods and finder function
25553 ** for proxy locking here.  So we forward declare the I/O methods.
25554 */
25555 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25556 static int proxyClose(sqlite3_file*);
25557 static int proxyLock(sqlite3_file*, int);
25558 static int proxyUnlock(sqlite3_file*, int);
25559 static int proxyCheckReservedLock(sqlite3_file*, int*);
25560 IOMETHODS(
25561   proxyIoFinder,            /* Finder function name */
25562   proxyIoMethods,           /* sqlite3_io_methods object name */
25563   proxyClose,               /* xClose method */
25564   proxyLock,                /* xLock method */
25565   proxyUnlock,              /* xUnlock method */
25566   proxyCheckReservedLock    /* xCheckReservedLock method */
25567 )
25568 #endif
25569
25570 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
25571 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25572 IOMETHODS(
25573   nfsIoFinder,               /* Finder function name */
25574   nfsIoMethods,              /* sqlite3_io_methods object name */
25575   unixClose,                 /* xClose method */
25576   unixLock,                  /* xLock method */
25577   nfsUnlock,                 /* xUnlock method */
25578   unixCheckReservedLock      /* xCheckReservedLock method */
25579 )
25580 #endif
25581
25582 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25583 /* 
25584 ** This "finder" function attempts to determine the best locking strategy 
25585 ** for the database file "filePath".  It then returns the sqlite3_io_methods
25586 ** object that implements that strategy.
25587 **
25588 ** This is for MacOSX only.
25589 */
25590 static const sqlite3_io_methods *autolockIoFinderImpl(
25591   const char *filePath,    /* name of the database file */
25592   unixFile *pNew           /* open file object for the database file */
25593 ){
25594   static const struct Mapping {
25595     const char *zFilesystem;              /* Filesystem type name */
25596     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
25597   } aMap[] = {
25598     { "hfs",    &posixIoMethods },
25599     { "ufs",    &posixIoMethods },
25600     { "afpfs",  &afpIoMethods },
25601     { "smbfs",  &afpIoMethods },
25602     { "webdav", &nolockIoMethods },
25603     { 0, 0 }
25604   };
25605   int i;
25606   struct statfs fsInfo;
25607   struct flock lockInfo;
25608
25609   if( !filePath ){
25610     /* If filePath==NULL that means we are dealing with a transient file
25611     ** that does not need to be locked. */
25612     return &nolockIoMethods;
25613   }
25614   if( statfs(filePath, &fsInfo) != -1 ){
25615     if( fsInfo.f_flags & MNT_RDONLY ){
25616       return &nolockIoMethods;
25617     }
25618     for(i=0; aMap[i].zFilesystem; i++){
25619       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
25620         return aMap[i].pMethods;
25621       }
25622     }
25623   }
25624
25625   /* Default case. Handles, amongst others, "nfs".
25626   ** Test byte-range lock using fcntl(). If the call succeeds, 
25627   ** assume that the file-system supports POSIX style locks. 
25628   */
25629   lockInfo.l_len = 1;
25630   lockInfo.l_start = 0;
25631   lockInfo.l_whence = SEEK_SET;
25632   lockInfo.l_type = F_RDLCK;
25633   if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
25634     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
25635       return &nfsIoMethods;
25636     } else {
25637       return &posixIoMethods;
25638     }
25639   }else{
25640     return &dotlockIoMethods;
25641   }
25642 }
25643 static const sqlite3_io_methods 
25644   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
25645
25646 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
25647
25648 #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
25649 /* 
25650 ** This "finder" function attempts to determine the best locking strategy 
25651 ** for the database file "filePath".  It then returns the sqlite3_io_methods
25652 ** object that implements that strategy.
25653 **
25654 ** This is for VXWorks only.
25655 */
25656 static const sqlite3_io_methods *autolockIoFinderImpl(
25657   const char *filePath,    /* name of the database file */
25658   unixFile *pNew           /* the open file object */
25659 ){
25660   struct flock lockInfo;
25661
25662   if( !filePath ){
25663     /* If filePath==NULL that means we are dealing with a transient file
25664     ** that does not need to be locked. */
25665     return &nolockIoMethods;
25666   }
25667
25668   /* Test if fcntl() is supported and use POSIX style locks.
25669   ** Otherwise fall back to the named semaphore method.
25670   */
25671   lockInfo.l_len = 1;
25672   lockInfo.l_start = 0;
25673   lockInfo.l_whence = SEEK_SET;
25674   lockInfo.l_type = F_RDLCK;
25675   if( fcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
25676     return &posixIoMethods;
25677   }else{
25678     return &semIoMethods;
25679   }
25680 }
25681 static const sqlite3_io_methods 
25682   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
25683
25684 #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
25685
25686 /*
25687 ** An abstract type for a pointer to a IO method finder function:
25688 */
25689 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
25690
25691
25692 /****************************************************************************
25693 **************************** sqlite3_vfs methods ****************************
25694 **
25695 ** This division contains the implementation of methods on the
25696 ** sqlite3_vfs object.
25697 */
25698
25699 /*
25700 ** Initialize the contents of the unixFile structure pointed to by pId.
25701 */
25702 static int fillInUnixFile(
25703   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
25704   int h,                  /* Open file descriptor of file being opened */
25705   int dirfd,              /* Directory file descriptor */
25706   sqlite3_file *pId,      /* Write to the unixFile structure here */
25707   const char *zFilename,  /* Name of the file being opened */
25708   int noLock,             /* Omit locking if true */
25709   int isDelete            /* Delete on close if true */
25710 ){
25711   const sqlite3_io_methods *pLockingStyle;
25712   unixFile *pNew = (unixFile *)pId;
25713   int rc = SQLITE_OK;
25714
25715   assert( pNew->pLock==NULL );
25716   assert( pNew->pOpen==NULL );
25717
25718   /* Parameter isDelete is only used on vxworks. Express this explicitly 
25719   ** here to prevent compiler warnings about unused parameters.
25720   */
25721   UNUSED_PARAMETER(isDelete);
25722
25723   OSTRACE3("OPEN    %-3d %s\n", h, zFilename);    
25724   pNew->h = h;
25725   pNew->dirfd = dirfd;
25726   SET_THREADID(pNew);
25727   pNew->fileFlags = 0;
25728
25729 #if OS_VXWORKS
25730   pNew->pId = vxworksFindFileId(zFilename);
25731   if( pNew->pId==0 ){
25732     noLock = 1;
25733     rc = SQLITE_NOMEM;
25734   }
25735 #endif
25736
25737   if( noLock ){
25738     pLockingStyle = &nolockIoMethods;
25739   }else{
25740     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
25741 #if SQLITE_ENABLE_LOCKING_STYLE
25742     /* Cache zFilename in the locking context (AFP and dotlock override) for
25743     ** proxyLock activation is possible (remote proxy is based on db name)
25744     ** zFilename remains valid until file is closed, to support */
25745     pNew->lockingContext = (void*)zFilename;
25746 #endif
25747   }
25748
25749   if( pLockingStyle == &posixIoMethods
25750 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
25751     || pLockingStyle == &nfsIoMethods
25752 #endif
25753   ){
25754     unixEnterMutex();
25755     rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
25756     if( rc!=SQLITE_OK ){
25757       /* If an error occured in findLockInfo(), close the file descriptor
25758       ** immediately, before releasing the mutex. findLockInfo() may fail
25759       ** in two scenarios:
25760       **
25761       **   (a) A call to fstat() failed.
25762       **   (b) A malloc failed.
25763       **
25764       ** Scenario (b) may only occur if the process is holding no other
25765       ** file descriptors open on the same file. If there were other file
25766       ** descriptors on this file, then no malloc would be required by
25767       ** findLockInfo(). If this is the case, it is quite safe to close
25768       ** handle h - as it is guaranteed that no posix locks will be released
25769       ** by doing so.
25770       **
25771       ** If scenario (a) caused the error then things are not so safe. The
25772       ** implicit assumption here is that if fstat() fails, things are in
25773       ** such bad shape that dropping a lock or two doesn't matter much.
25774       */
25775       close(h);
25776       h = -1;
25777     }
25778     unixLeaveMutex();
25779   }
25780
25781 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25782   else if( pLockingStyle == &afpIoMethods ){
25783     /* AFP locking uses the file path so it needs to be included in
25784     ** the afpLockingContext.
25785     */
25786     afpLockingContext *pCtx;
25787     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
25788     if( pCtx==0 ){
25789       rc = SQLITE_NOMEM;
25790     }else{
25791       /* NB: zFilename exists and remains valid until the file is closed
25792       ** according to requirement F11141.  So we do not need to make a
25793       ** copy of the filename. */
25794       pCtx->dbPath = zFilename;
25795       pCtx->reserved = 0;
25796       srandomdev();
25797       unixEnterMutex();
25798       rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
25799       if( rc!=SQLITE_OK ){
25800         sqlite3_free(pNew->lockingContext);
25801         close(h);
25802         h = -1;
25803       }
25804       unixLeaveMutex();        
25805     }
25806   }
25807 #endif
25808
25809   else if( pLockingStyle == &dotlockIoMethods ){
25810     /* Dotfile locking uses the file path so it needs to be included in
25811     ** the dotlockLockingContext 
25812     */
25813     char *zLockFile;
25814     int nFilename;
25815     nFilename = (int)strlen(zFilename) + 6;
25816     zLockFile = (char *)sqlite3_malloc(nFilename);
25817     if( zLockFile==0 ){
25818       rc = SQLITE_NOMEM;
25819     }else{
25820       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
25821     }
25822     pNew->lockingContext = zLockFile;
25823   }
25824
25825 #if OS_VXWORKS
25826   else if( pLockingStyle == &semIoMethods ){
25827     /* Named semaphore locking uses the file path so it needs to be
25828     ** included in the semLockingContext
25829     */
25830     unixEnterMutex();
25831     rc = findLockInfo(pNew, &pNew->pLock, &pNew->pOpen);
25832     if( (rc==SQLITE_OK) && (pNew->pOpen->pSem==NULL) ){
25833       char *zSemName = pNew->pOpen->aSemName;
25834       int n;
25835       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
25836                        pNew->pId->zCanonicalName);
25837       for( n=1; zSemName[n]; n++ )
25838         if( zSemName[n]=='/' ) zSemName[n] = '_';
25839       pNew->pOpen->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
25840       if( pNew->pOpen->pSem == SEM_FAILED ){
25841         rc = SQLITE_NOMEM;
25842         pNew->pOpen->aSemName[0] = '\0';
25843       }
25844     }
25845     unixLeaveMutex();
25846   }
25847 #endif
25848   
25849   pNew->lastErrno = 0;
25850 #if OS_VXWORKS
25851   if( rc!=SQLITE_OK ){
25852     if( h>=0 ) close(h);
25853     h = -1;
25854     unlink(zFilename);
25855     isDelete = 0;
25856   }
25857   pNew->isDelete = isDelete;
25858 #endif
25859   if( rc!=SQLITE_OK ){
25860     if( dirfd>=0 ) close(dirfd); /* silent leak if fail, already in error */
25861     if( h>=0 ) close(h);
25862   }else{
25863     pNew->pMethod = pLockingStyle;
25864     OpenCounter(+1);
25865   }
25866   return rc;
25867 }
25868
25869 /*
25870 ** Open a file descriptor to the directory containing file zFilename.
25871 ** If successful, *pFd is set to the opened file descriptor and
25872 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
25873 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
25874 ** value.
25875 **
25876 ** If SQLITE_OK is returned, the caller is responsible for closing
25877 ** the file descriptor *pFd using close().
25878 */
25879 static int openDirectory(const char *zFilename, int *pFd){
25880   int ii;
25881   int fd = -1;
25882   char zDirname[MAX_PATHNAME+1];
25883
25884   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
25885   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
25886   if( ii>0 ){
25887     zDirname[ii] = '\0';
25888     fd = open(zDirname, O_RDONLY|O_BINARY, 0);
25889     if( fd>=0 ){
25890 #ifdef FD_CLOEXEC
25891       fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
25892 #endif
25893       OSTRACE3("OPENDIR %-3d %s\n", fd, zDirname);
25894     }
25895   }
25896   *pFd = fd;
25897   return (fd>=0?SQLITE_OK:SQLITE_CANTOPEN_BKPT);
25898 }
25899
25900 /*
25901 ** Create a temporary file name in zBuf.  zBuf must be allocated
25902 ** by the calling process and must be big enough to hold at least
25903 ** pVfs->mxPathname bytes.
25904 */
25905 static int getTempname(int nBuf, char *zBuf){
25906   static const char *azDirs[] = {
25907      0,
25908      0,
25909      "/var/tmp",
25910      "/usr/tmp",
25911      "/tmp",
25912      ".",
25913   };
25914   static const unsigned char zChars[] =
25915     "abcdefghijklmnopqrstuvwxyz"
25916     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
25917     "0123456789";
25918   unsigned int i, j;
25919   struct stat buf;
25920   const char *zDir = ".";
25921
25922   /* It's odd to simulate an io-error here, but really this is just
25923   ** using the io-error infrastructure to test that SQLite handles this
25924   ** function failing. 
25925   */
25926   SimulateIOError( return SQLITE_IOERR );
25927
25928   azDirs[0] = sqlite3_temp_directory;
25929   if (NULL == azDirs[1]) {
25930     azDirs[1] = getenv("TMPDIR");
25931   }
25932   
25933   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); i++){
25934     if( azDirs[i]==0 ) continue;
25935     if( stat(azDirs[i], &buf) ) continue;
25936     if( !S_ISDIR(buf.st_mode) ) continue;
25937     if( access(azDirs[i], 07) ) continue;
25938     zDir = azDirs[i];
25939     break;
25940   }
25941
25942   /* Check that the output buffer is large enough for the temporary file 
25943   ** name. If it is not, return SQLITE_ERROR.
25944   */
25945   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 17) >= (size_t)nBuf ){
25946     return SQLITE_ERROR;
25947   }
25948
25949   do{
25950     sqlite3_snprintf(nBuf-17, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
25951     j = (int)strlen(zBuf);
25952     sqlite3_randomness(15, &zBuf[j]);
25953     for(i=0; i<15; i++, j++){
25954       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
25955     }
25956     zBuf[j] = 0;
25957   }while( access(zBuf,0)==0 );
25958   return SQLITE_OK;
25959 }
25960
25961 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
25962 /*
25963 ** Routine to transform a unixFile into a proxy-locking unixFile.
25964 ** Implementation in the proxy-lock division, but used by unixOpen()
25965 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
25966 */
25967 static int proxyTransformUnixFile(unixFile*, const char*);
25968 #endif
25969
25970 /*
25971 ** Search for an unused file descriptor that was opened on the database 
25972 ** file (not a journal or master-journal file) identified by pathname
25973 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
25974 ** argument to this function.
25975 **
25976 ** Such a file descriptor may exist if a database connection was closed
25977 ** but the associated file descriptor could not be closed because some
25978 ** other file descriptor open on the same file is holding a file-lock.
25979 ** Refer to comments in the unixClose() function and the lengthy comment
25980 ** describing "Posix Advisory Locking" at the start of this file for 
25981 ** further details. Also, ticket #4018.
25982 **
25983 ** If a suitable file descriptor is found, then it is returned. If no
25984 ** such file descriptor is located, -1 is returned.
25985 */
25986 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
25987   UnixUnusedFd *pUnused = 0;
25988
25989   /* Do not search for an unused file descriptor on vxworks. Not because
25990   ** vxworks would not benefit from the change (it might, we're not sure),
25991   ** but because no way to test it is currently available. It is better 
25992   ** not to risk breaking vxworks support for the sake of such an obscure 
25993   ** feature.  */
25994 #if !OS_VXWORKS
25995   struct stat sStat;                   /* Results of stat() call */
25996
25997   /* A stat() call may fail for various reasons. If this happens, it is
25998   ** almost certain that an open() call on the same path will also fail.
25999   ** For this reason, if an error occurs in the stat() call here, it is
26000   ** ignored and -1 is returned. The caller will try to open a new file
26001   ** descriptor on the same path, fail, and return an error to SQLite.
26002   **
26003   ** Even if a subsequent open() call does succeed, the consequences of
26004   ** not searching for a resusable file descriptor are not dire.  */
26005   if( 0==stat(zPath, &sStat) ){
26006     struct unixOpenCnt *pOpen;
26007
26008     unixEnterMutex();
26009     pOpen = openList;
26010     while( pOpen && (pOpen->fileId.dev!=sStat.st_dev
26011                      || pOpen->fileId.ino!=sStat.st_ino) ){
26012        pOpen = pOpen->pNext;
26013     }
26014     if( pOpen ){
26015       UnixUnusedFd **pp;
26016       for(pp=&pOpen->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
26017       pUnused = *pp;
26018       if( pUnused ){
26019         *pp = pUnused->pNext;
26020       }
26021     }
26022     unixLeaveMutex();
26023   }
26024 #endif    /* if !OS_VXWORKS */
26025   return pUnused;
26026 }
26027
26028 /*
26029 ** Open the file zPath.
26030 ** 
26031 ** Previously, the SQLite OS layer used three functions in place of this
26032 ** one:
26033 **
26034 **     sqlite3OsOpenReadWrite();
26035 **     sqlite3OsOpenReadOnly();
26036 **     sqlite3OsOpenExclusive();
26037 **
26038 ** These calls correspond to the following combinations of flags:
26039 **
26040 **     ReadWrite() ->     (READWRITE | CREATE)
26041 **     ReadOnly()  ->     (READONLY) 
26042 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
26043 **
26044 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
26045 ** true, the file was configured to be automatically deleted when the
26046 ** file handle closed. To achieve the same effect using this new 
26047 ** interface, add the DELETEONCLOSE flag to those specified above for 
26048 ** OpenExclusive().
26049 */
26050 static int unixOpen(
26051   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
26052   const char *zPath,           /* Pathname of file to be opened */
26053   sqlite3_file *pFile,         /* The file descriptor to be filled in */
26054   int flags,                   /* Input flags to control the opening */
26055   int *pOutFlags               /* Output flags returned to SQLite core */
26056 ){
26057   unixFile *p = (unixFile *)pFile;
26058   int fd = -1;                   /* File descriptor returned by open() */
26059   int dirfd = -1;                /* Directory file descriptor */
26060   int openFlags = 0;             /* Flags to pass to open() */
26061   int eType = flags&0xFFFFFF00;  /* Type of file to open */
26062   int noLock;                    /* True to omit locking primitives */
26063   int rc = SQLITE_OK;            /* Function Return Code */
26064
26065   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
26066   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
26067   int isCreate     = (flags & SQLITE_OPEN_CREATE);
26068   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
26069   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
26070 #if SQLITE_ENABLE_LOCKING_STYLE
26071   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
26072 #endif
26073
26074   /* If creating a master or main-file journal, this function will open
26075   ** a file-descriptor on the directory too. The first time unixSync()
26076   ** is called the directory file descriptor will be fsync()ed and close()d.
26077   */
26078   int isOpenDirectory = (isCreate && 
26079       (eType==SQLITE_OPEN_MASTER_JOURNAL || eType==SQLITE_OPEN_MAIN_JOURNAL)
26080   );
26081
26082   /* If argument zPath is a NULL pointer, this function is required to open
26083   ** a temporary file. Use this buffer to store the file name in.
26084   */
26085   char zTmpname[MAX_PATHNAME+1];
26086   const char *zName = zPath;
26087
26088   /* Check the following statements are true: 
26089   **
26090   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
26091   **   (b) if CREATE is set, then READWRITE must also be set, and
26092   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
26093   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
26094   */
26095   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
26096   assert(isCreate==0 || isReadWrite);
26097   assert(isExclusive==0 || isCreate);
26098   assert(isDelete==0 || isCreate);
26099
26100   /* The main DB, main journal, and master journal are never automatically
26101   ** deleted. Nor are they ever temporary files.  */
26102   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
26103   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
26104   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
26105
26106   /* Assert that the upper layer has set one of the "file-type" flags. */
26107   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
26108        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
26109        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
26110        || eType==SQLITE_OPEN_TRANSIENT_DB
26111   );
26112
26113   memset(p, 0, sizeof(unixFile));
26114
26115   if( eType==SQLITE_OPEN_MAIN_DB ){
26116     UnixUnusedFd *pUnused;
26117     pUnused = findReusableFd(zName, flags);
26118     if( pUnused ){
26119       fd = pUnused->fd;
26120     }else{
26121       pUnused = sqlite3_malloc(sizeof(*pUnused));
26122       if( !pUnused ){
26123         return SQLITE_NOMEM;
26124       }
26125     }
26126     p->pUnused = pUnused;
26127   }else if( !zName ){
26128     /* If zName is NULL, the upper layer is requesting a temp file. */
26129     assert(isDelete && !isOpenDirectory);
26130     rc = getTempname(MAX_PATHNAME+1, zTmpname);
26131     if( rc!=SQLITE_OK ){
26132       return rc;
26133     }
26134     zName = zTmpname;
26135   }
26136
26137   /* Determine the value of the flags parameter passed to POSIX function
26138   ** open(). These must be calculated even if open() is not called, as
26139   ** they may be stored as part of the file handle and used by the 
26140   ** 'conch file' locking functions later on.  */
26141   if( isReadonly )  openFlags |= O_RDONLY;
26142   if( isReadWrite ) openFlags |= O_RDWR;
26143   if( isCreate )    openFlags |= O_CREAT;
26144   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
26145   openFlags |= (O_LARGEFILE|O_BINARY);
26146
26147   if( fd<0 ){
26148     mode_t openMode = (isDelete?0600:SQLITE_DEFAULT_FILE_PERMISSIONS);
26149     fd = open(zName, openFlags, openMode);
26150     OSTRACE4("OPENX   %-3d %s 0%o\n", fd, zName, openFlags);
26151     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
26152       /* Failed to open the file for read/write access. Try read-only. */
26153       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
26154       openFlags &= ~(O_RDWR|O_CREAT);
26155       flags |= SQLITE_OPEN_READONLY;
26156       openFlags |= O_RDONLY;
26157       fd = open(zName, openFlags, openMode);
26158     }
26159     if( fd<0 ){
26160       rc = SQLITE_CANTOPEN_BKPT;
26161       goto open_finished;
26162     }
26163   }
26164   assert( fd>=0 );
26165   if( pOutFlags ){
26166     *pOutFlags = flags;
26167   }
26168
26169   if( p->pUnused ){
26170     p->pUnused->fd = fd;
26171     p->pUnused->flags = flags;
26172   }
26173
26174   if( isDelete ){
26175 #if OS_VXWORKS
26176     zPath = zName;
26177 #else
26178     unlink(zName);
26179 #endif
26180   }
26181 #if SQLITE_ENABLE_LOCKING_STYLE
26182   else{
26183     p->openFlags = openFlags;
26184   }
26185 #endif
26186
26187   if( isOpenDirectory ){
26188     rc = openDirectory(zPath, &dirfd);
26189     if( rc!=SQLITE_OK ){
26190       /* It is safe to close fd at this point, because it is guaranteed not
26191       ** to be open on a database file. If it were open on a database file,
26192       ** it would not be safe to close as this would release any locks held
26193       ** on the file by this process.  */
26194       assert( eType!=SQLITE_OPEN_MAIN_DB );
26195       close(fd);             /* silently leak if fail, already in error */
26196       goto open_finished;
26197     }
26198   }
26199
26200 #ifdef FD_CLOEXEC
26201   fcntl(fd, F_SETFD, fcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
26202 #endif
26203
26204   noLock = eType!=SQLITE_OPEN_MAIN_DB;
26205
26206   
26207 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
26208   struct statfs fsInfo;
26209   if( fstatfs(fd, &fsInfo) == -1 ){
26210     ((unixFile*)pFile)->lastErrno = errno;
26211     if( dirfd>=0 ) close(dirfd); /* silently leak if fail, in error */
26212     close(fd); /* silently leak if fail, in error */
26213     return SQLITE_IOERR_ACCESS;
26214   }
26215   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
26216     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
26217   }
26218 #endif
26219   
26220 #if SQLITE_ENABLE_LOCKING_STYLE
26221 #if SQLITE_PREFER_PROXY_LOCKING
26222   isAutoProxy = 1;
26223 #endif
26224   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
26225     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
26226     int useProxy = 0;
26227
26228     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
26229     ** never use proxy, NULL means use proxy for non-local files only.  */
26230     if( envforce!=NULL ){
26231       useProxy = atoi(envforce)>0;
26232     }else{
26233       struct statfs fsInfo;
26234       if( statfs(zPath, &fsInfo) == -1 ){
26235         /* In theory, the close(fd) call is sub-optimal. If the file opened
26236         ** with fd is a database file, and there are other connections open
26237         ** on that file that are currently holding advisory locks on it,
26238         ** then the call to close() will cancel those locks. In practice,
26239         ** we're assuming that statfs() doesn't fail very often. At least
26240         ** not while other file descriptors opened by the same process on
26241         ** the same file are working.  */
26242         p->lastErrno = errno;
26243         if( dirfd>=0 ){
26244           close(dirfd); /* silently leak if fail, in error */
26245         }
26246         close(fd); /* silently leak if fail, in error */
26247         rc = SQLITE_IOERR_ACCESS;
26248         goto open_finished;
26249       }
26250       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
26251     }
26252     if( useProxy ){
26253       rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
26254       if( rc==SQLITE_OK ){
26255         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
26256         if( rc!=SQLITE_OK ){
26257           /* Use unixClose to clean up the resources added in fillInUnixFile 
26258           ** and clear all the structure's references.  Specifically, 
26259           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op 
26260           */
26261           unixClose(pFile);
26262           return rc;
26263         }
26264       }
26265       goto open_finished;
26266     }
26267   }
26268 #endif
26269   
26270   rc = fillInUnixFile(pVfs, fd, dirfd, pFile, zPath, noLock, isDelete);
26271 open_finished:
26272   if( rc!=SQLITE_OK ){
26273     sqlite3_free(p->pUnused);
26274   }
26275   return rc;
26276 }
26277
26278
26279 /*
26280 ** Delete the file at zPath. If the dirSync argument is true, fsync()
26281 ** the directory after deleting the file.
26282 */
26283 static int unixDelete(
26284   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
26285   const char *zPath,        /* Name of file to be deleted */
26286   int dirSync               /* If true, fsync() directory after deleting file */
26287 ){
26288   int rc = SQLITE_OK;
26289   UNUSED_PARAMETER(NotUsed);
26290   SimulateIOError(return SQLITE_IOERR_DELETE);
26291   unlink(zPath);
26292 #ifndef SQLITE_DISABLE_DIRSYNC
26293   if( dirSync ){
26294     int fd;
26295     rc = openDirectory(zPath, &fd);
26296     if( rc==SQLITE_OK ){
26297 #if OS_VXWORKS
26298       if( fsync(fd)==-1 )
26299 #else
26300       if( fsync(fd) )
26301 #endif
26302       {
26303         rc = SQLITE_IOERR_DIR_FSYNC;
26304       }
26305       if( close(fd)&&!rc ){
26306         rc = SQLITE_IOERR_DIR_CLOSE;
26307       }
26308     }
26309   }
26310 #endif
26311   return rc;
26312 }
26313
26314 /*
26315 ** Test the existance of or access permissions of file zPath. The
26316 ** test performed depends on the value of flags:
26317 **
26318 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
26319 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
26320 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
26321 **
26322 ** Otherwise return 0.
26323 */
26324 static int unixAccess(
26325   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
26326   const char *zPath,      /* Path of the file to examine */
26327   int flags,              /* What do we want to learn about the zPath file? */
26328   int *pResOut            /* Write result boolean here */
26329 ){
26330   int amode = 0;
26331   UNUSED_PARAMETER(NotUsed);
26332   SimulateIOError( return SQLITE_IOERR_ACCESS; );
26333   switch( flags ){
26334     case SQLITE_ACCESS_EXISTS:
26335       amode = F_OK;
26336       break;
26337     case SQLITE_ACCESS_READWRITE:
26338       amode = W_OK|R_OK;
26339       break;
26340     case SQLITE_ACCESS_READ:
26341       amode = R_OK;
26342       break;
26343
26344     default:
26345       assert(!"Invalid flags argument");
26346   }
26347   *pResOut = (access(zPath, amode)==0);
26348   return SQLITE_OK;
26349 }
26350
26351
26352 /*
26353 ** Turn a relative pathname into a full pathname. The relative path
26354 ** is stored as a nul-terminated string in the buffer pointed to by
26355 ** zPath. 
26356 **
26357 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
26358 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
26359 ** this buffer before returning.
26360 */
26361 static int unixFullPathname(
26362   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
26363   const char *zPath,            /* Possibly relative input path */
26364   int nOut,                     /* Size of output buffer in bytes */
26365   char *zOut                    /* Output buffer */
26366 ){
26367
26368   /* It's odd to simulate an io-error here, but really this is just
26369   ** using the io-error infrastructure to test that SQLite handles this
26370   ** function failing. This function could fail if, for example, the
26371   ** current working directory has been unlinked.
26372   */
26373   SimulateIOError( return SQLITE_ERROR );
26374
26375   assert( pVfs->mxPathname==MAX_PATHNAME );
26376   UNUSED_PARAMETER(pVfs);
26377
26378   zOut[nOut-1] = '\0';
26379   if( zPath[0]=='/' ){
26380     sqlite3_snprintf(nOut, zOut, "%s", zPath);
26381   }else{
26382     int nCwd;
26383     if( getcwd(zOut, nOut-1)==0 ){
26384       return SQLITE_CANTOPEN_BKPT;
26385     }
26386     nCwd = (int)strlen(zOut);
26387     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
26388   }
26389   return SQLITE_OK;
26390 }
26391
26392
26393 #ifndef SQLITE_OMIT_LOAD_EXTENSION
26394 /*
26395 ** Interfaces for opening a shared library, finding entry points
26396 ** within the shared library, and closing the shared library.
26397 */
26398 #include <dlfcn.h>
26399 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
26400   UNUSED_PARAMETER(NotUsed);
26401   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
26402 }
26403
26404 /*
26405 ** SQLite calls this function immediately after a call to unixDlSym() or
26406 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
26407 ** message is available, it is written to zBufOut. If no error message
26408 ** is available, zBufOut is left unmodified and SQLite uses a default
26409 ** error message.
26410 */
26411 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
26412   char *zErr;
26413   UNUSED_PARAMETER(NotUsed);
26414   unixEnterMutex();
26415   zErr = dlerror();
26416   if( zErr ){
26417     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
26418   }
26419   unixLeaveMutex();
26420 }
26421 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
26422   /* 
26423   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
26424   ** cast into a pointer to a function.  And yet the library dlsym() routine
26425   ** returns a void* which is really a pointer to a function.  So how do we
26426   ** use dlsym() with -pedantic-errors?
26427   **
26428   ** Variable x below is defined to be a pointer to a function taking
26429   ** parameters void* and const char* and returning a pointer to a function.
26430   ** We initialize x by assigning it a pointer to the dlsym() function.
26431   ** (That assignment requires a cast.)  Then we call the function that
26432   ** x points to.  
26433   **
26434   ** This work-around is unlikely to work correctly on any system where
26435   ** you really cannot cast a function pointer into void*.  But then, on the
26436   ** other hand, dlsym() will not work on such a system either, so we have
26437   ** not really lost anything.
26438   */
26439   void (*(*x)(void*,const char*))(void);
26440   UNUSED_PARAMETER(NotUsed);
26441   x = (void(*(*)(void*,const char*))(void))dlsym;
26442   return (*x)(p, zSym);
26443 }
26444 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
26445   UNUSED_PARAMETER(NotUsed);
26446   dlclose(pHandle);
26447 }
26448 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
26449   #define unixDlOpen  0
26450   #define unixDlError 0
26451   #define unixDlSym   0
26452   #define unixDlClose 0
26453 #endif
26454
26455 /*
26456 ** Write nBuf bytes of random data to the supplied buffer zBuf.
26457 */
26458 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
26459   UNUSED_PARAMETER(NotUsed);
26460   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
26461
26462   /* We have to initialize zBuf to prevent valgrind from reporting
26463   ** errors.  The reports issued by valgrind are incorrect - we would
26464   ** prefer that the randomness be increased by making use of the
26465   ** uninitialized space in zBuf - but valgrind errors tend to worry
26466   ** some users.  Rather than argue, it seems easier just to initialize
26467   ** the whole array and silence valgrind, even if that means less randomness
26468   ** in the random seed.
26469   **
26470   ** When testing, initializing zBuf[] to zero is all we do.  That means
26471   ** that we always use the same random number sequence.  This makes the
26472   ** tests repeatable.
26473   */
26474   memset(zBuf, 0, nBuf);
26475 #if !defined(SQLITE_TEST)
26476   {
26477     int pid, fd;
26478     fd = open("/dev/urandom", O_RDONLY);
26479     if( fd<0 ){
26480       time_t t;
26481       time(&t);
26482       memcpy(zBuf, &t, sizeof(t));
26483       pid = getpid();
26484       memcpy(&zBuf[sizeof(t)], &pid, sizeof(pid));
26485       assert( sizeof(t)+sizeof(pid)<=(size_t)nBuf );
26486       nBuf = sizeof(t) + sizeof(pid);
26487     }else{
26488       nBuf = read(fd, zBuf, nBuf);
26489       close(fd);
26490     }
26491   }
26492 #endif
26493   return nBuf;
26494 }
26495
26496
26497 /*
26498 ** Sleep for a little while.  Return the amount of time slept.
26499 ** The argument is the number of microseconds we want to sleep.
26500 ** The return value is the number of microseconds of sleep actually
26501 ** requested from the underlying operating system, a number which
26502 ** might be greater than or equal to the argument, but not less
26503 ** than the argument.
26504 */
26505 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
26506 #if OS_VXWORKS
26507   struct timespec sp;
26508
26509   sp.tv_sec = microseconds / 1000000;
26510   sp.tv_nsec = (microseconds % 1000000) * 1000;
26511   nanosleep(&sp, NULL);
26512   UNUSED_PARAMETER(NotUsed);
26513   return microseconds;
26514 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
26515   usleep(microseconds);
26516   UNUSED_PARAMETER(NotUsed);
26517   return microseconds;
26518 #else
26519   int seconds = (microseconds+999999)/1000000;
26520   sleep(seconds);
26521   UNUSED_PARAMETER(NotUsed);
26522   return seconds*1000000;
26523 #endif
26524 }
26525
26526 /*
26527 ** The following variable, if set to a non-zero value, is interpreted as
26528 ** the number of seconds since 1970 and is used to set the result of
26529 ** sqlite3OsCurrentTime() during testing.
26530 */
26531 #ifdef SQLITE_TEST
26532 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
26533 #endif
26534
26535 /*
26536 ** Find the current time (in Universal Coordinated Time).  Write the
26537 ** current time and date as a Julian Day number into *prNow and
26538 ** return 0.  Return 1 if the time and date cannot be found.
26539 */
26540 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
26541 #if defined(SQLITE_OMIT_FLOATING_POINT)
26542   time_t t;
26543   time(&t);
26544   *prNow = (((sqlite3_int64)t)/8640 + 24405875)/10;
26545 #elif defined(NO_GETTOD)
26546   time_t t;
26547   time(&t);
26548   *prNow = t/86400.0 + 2440587.5;
26549 #elif OS_VXWORKS
26550   struct timespec sNow;
26551   clock_gettime(CLOCK_REALTIME, &sNow);
26552   *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_nsec/86400000000000.0;
26553 #else
26554   struct timeval sNow;
26555   gettimeofday(&sNow, 0);
26556   *prNow = 2440587.5 + sNow.tv_sec/86400.0 + sNow.tv_usec/86400000000.0;
26557 #endif
26558
26559 #ifdef SQLITE_TEST
26560   if( sqlite3_current_time ){
26561     *prNow = sqlite3_current_time/86400.0 + 2440587.5;
26562   }
26563 #endif
26564   UNUSED_PARAMETER(NotUsed);
26565   return 0;
26566 }
26567
26568 /*
26569 ** We added the xGetLastError() method with the intention of providing
26570 ** better low-level error messages when operating-system problems come up
26571 ** during SQLite operation.  But so far, none of that has been implemented
26572 ** in the core.  So this routine is never called.  For now, it is merely
26573 ** a place-holder.
26574 */
26575 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
26576   UNUSED_PARAMETER(NotUsed);
26577   UNUSED_PARAMETER(NotUsed2);
26578   UNUSED_PARAMETER(NotUsed3);
26579   return 0;
26580 }
26581
26582 /*
26583 ************************ End of sqlite3_vfs methods ***************************
26584 ******************************************************************************/
26585
26586 /******************************************************************************
26587 ************************** Begin Proxy Locking ********************************
26588 **
26589 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
26590 ** other locking methods on secondary lock files.  Proxy locking is a
26591 ** meta-layer over top of the primitive locking implemented above.  For
26592 ** this reason, the division that implements of proxy locking is deferred
26593 ** until late in the file (here) after all of the other I/O methods have
26594 ** been defined - so that the primitive locking methods are available
26595 ** as services to help with the implementation of proxy locking.
26596 **
26597 ****
26598 **
26599 ** The default locking schemes in SQLite use byte-range locks on the
26600 ** database file to coordinate safe, concurrent access by multiple readers
26601 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
26602 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
26603 ** as POSIX read & write locks over fixed set of locations (via fsctl),
26604 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
26605 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
26606 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
26607 ** address in the shared range is taken for a SHARED lock, the entire
26608 ** shared range is taken for an EXCLUSIVE lock):
26609 **
26610 **      PENDING_BYTE        0x40000000                  
26611 **      RESERVED_BYTE       0x40000001
26612 **      SHARED_RANGE        0x40000002 -> 0x40000200
26613 **
26614 ** This works well on the local file system, but shows a nearly 100x
26615 ** slowdown in read performance on AFP because the AFP client disables
26616 ** the read cache when byte-range locks are present.  Enabling the read
26617 ** cache exposes a cache coherency problem that is present on all OS X
26618 ** supported network file systems.  NFS and AFP both observe the
26619 ** close-to-open semantics for ensuring cache coherency
26620 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
26621 ** address the requirements for concurrent database access by multiple
26622 ** readers and writers
26623 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
26624 **
26625 ** To address the performance and cache coherency issues, proxy file locking
26626 ** changes the way database access is controlled by limiting access to a
26627 ** single host at a time and moving file locks off of the database file
26628 ** and onto a proxy file on the local file system.  
26629 **
26630 **
26631 ** Using proxy locks
26632 ** -----------------
26633 **
26634 ** C APIs
26635 **
26636 **  sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
26637 **                       <proxy_path> | ":auto:");
26638 **  sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
26639 **
26640 **
26641 ** SQL pragmas
26642 **
26643 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
26644 **  PRAGMA [database.]lock_proxy_file
26645 **
26646 ** Specifying ":auto:" means that if there is a conch file with a matching
26647 ** host ID in it, the proxy path in the conch file will be used, otherwise
26648 ** a proxy path based on the user's temp dir
26649 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
26650 ** actual proxy file name is generated from the name and path of the
26651 ** database file.  For example:
26652 **
26653 **       For database path "/Users/me/foo.db" 
26654 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
26655 **
26656 ** Once a lock proxy is configured for a database connection, it can not
26657 ** be removed, however it may be switched to a different proxy path via
26658 ** the above APIs (assuming the conch file is not being held by another
26659 ** connection or process). 
26660 **
26661 **
26662 ** How proxy locking works
26663 ** -----------------------
26664 **
26665 ** Proxy file locking relies primarily on two new supporting files: 
26666 **
26667 **   *  conch file to limit access to the database file to a single host
26668 **      at a time
26669 **
26670 **   *  proxy file to act as a proxy for the advisory locks normally
26671 **      taken on the database
26672 **
26673 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
26674 ** by taking an sqlite-style shared lock on the conch file, reading the
26675 ** contents and comparing the host's unique host ID (see below) and lock
26676 ** proxy path against the values stored in the conch.  The conch file is
26677 ** stored in the same directory as the database file and the file name
26678 ** is patterned after the database file name as ".<databasename>-conch".
26679 ** If the conch file does not exist, or it's contents do not match the
26680 ** host ID and/or proxy path, then the lock is escalated to an exclusive
26681 ** lock and the conch file contents is updated with the host ID and proxy
26682 ** path and the lock is downgraded to a shared lock again.  If the conch
26683 ** is held by another process (with a shared lock), the exclusive lock
26684 ** will fail and SQLITE_BUSY is returned.
26685 **
26686 ** The proxy file - a single-byte file used for all advisory file locks
26687 ** normally taken on the database file.   This allows for safe sharing
26688 ** of the database file for multiple readers and writers on the same
26689 ** host (the conch ensures that they all use the same local lock file).
26690 **
26691 ** Requesting the lock proxy does not immediately take the conch, it is
26692 ** only taken when the first request to lock database file is made.  
26693 ** This matches the semantics of the traditional locking behavior, where
26694 ** opening a connection to a database file does not take a lock on it.
26695 ** The shared lock and an open file descriptor are maintained until 
26696 ** the connection to the database is closed. 
26697 **
26698 ** The proxy file and the lock file are never deleted so they only need
26699 ** to be created the first time they are used.
26700 **
26701 ** Configuration options
26702 ** ---------------------
26703 **
26704 **  SQLITE_PREFER_PROXY_LOCKING
26705 **
26706 **       Database files accessed on non-local file systems are
26707 **       automatically configured for proxy locking, lock files are
26708 **       named automatically using the same logic as
26709 **       PRAGMA lock_proxy_file=":auto:"
26710 **    
26711 **  SQLITE_PROXY_DEBUG
26712 **
26713 **       Enables the logging of error messages during host id file
26714 **       retrieval and creation
26715 **
26716 **  LOCKPROXYDIR
26717 **
26718 **       Overrides the default directory used for lock proxy files that
26719 **       are named automatically via the ":auto:" setting
26720 **
26721 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
26722 **
26723 **       Permissions to use when creating a directory for storing the
26724 **       lock proxy files, only used when LOCKPROXYDIR is not set.
26725 **    
26726 **    
26727 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
26728 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
26729 ** force proxy locking to be used for every database file opened, and 0
26730 ** will force automatic proxy locking to be disabled for all database
26731 ** files (explicity calling the SQLITE_SET_LOCKPROXYFILE pragma or
26732 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
26733 */
26734
26735 /*
26736 ** Proxy locking is only available on MacOSX 
26737 */
26738 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
26739
26740 /*
26741 ** The proxyLockingContext has the path and file structures for the remote 
26742 ** and local proxy files in it
26743 */
26744 typedef struct proxyLockingContext proxyLockingContext;
26745 struct proxyLockingContext {
26746   unixFile *conchFile;         /* Open conch file */
26747   char *conchFilePath;         /* Name of the conch file */
26748   unixFile *lockProxy;         /* Open proxy lock file */
26749   char *lockProxyPath;         /* Name of the proxy lock file */
26750   char *dbPath;                /* Name of the open file */
26751   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
26752   void *oldLockingContext;     /* Original lockingcontext to restore on close */
26753   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
26754 };
26755
26756 /* 
26757 ** The proxy lock file path for the database at dbPath is written into lPath, 
26758 ** which must point to valid, writable memory large enough for a maxLen length
26759 ** file path. 
26760 */
26761 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
26762   int len;
26763   int dbLen;
26764   int i;
26765
26766 #ifdef LOCKPROXYDIR
26767   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
26768 #else
26769 # ifdef _CS_DARWIN_USER_TEMP_DIR
26770   {
26771     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
26772       OSTRACE4("GETLOCKPATH  failed %s errno=%d pid=%d\n",
26773                lPath, errno, getpid());
26774       return SQLITE_IOERR_LOCK;
26775     }
26776     len = strlcat(lPath, "sqliteplocks", maxLen);    
26777   }
26778 # else
26779   len = strlcpy(lPath, "/tmp/", maxLen);
26780 # endif
26781 #endif
26782
26783   if( lPath[len-1]!='/' ){
26784     len = strlcat(lPath, "/", maxLen);
26785   }
26786   
26787   /* transform the db path to a unique cache name */
26788   dbLen = (int)strlen(dbPath);
26789   for( i=0; i<dbLen && (i+len+7)<maxLen; i++){
26790     char c = dbPath[i];
26791     lPath[i+len] = (c=='/')?'_':c;
26792   }
26793   lPath[i+len]='\0';
26794   strlcat(lPath, ":auto:", maxLen);
26795   OSTRACE3("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, getpid());
26796   return SQLITE_OK;
26797 }
26798
26799 /* 
26800  ** Creates the lock file and any missing directories in lockPath
26801  */
26802 static int proxyCreateLockPath(const char *lockPath){
26803   int i, len;
26804   char buf[MAXPATHLEN];
26805   int start = 0;
26806   
26807   assert(lockPath!=NULL);
26808   /* try to create all the intermediate directories */
26809   len = (int)strlen(lockPath);
26810   buf[0] = lockPath[0];
26811   for( i=1; i<len; i++ ){
26812     if( lockPath[i] == '/' && (i - start > 0) ){
26813       /* only mkdir if leaf dir != "." or "/" or ".." */
26814       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
26815          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
26816         buf[i]='\0';
26817         if( mkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
26818           int err=errno;
26819           if( err!=EEXIST ) {
26820             OSTRACE5("CREATELOCKPATH  FAILED creating %s, "
26821                      "'%s' proxy lock path=%s pid=%d\n",
26822                      buf, strerror(err), lockPath, getpid());
26823             return err;
26824           }
26825         }
26826       }
26827       start=i+1;
26828     }
26829     buf[i] = lockPath[i];
26830   }
26831   OSTRACE3("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, getpid());
26832   return 0;
26833 }
26834
26835 /*
26836 ** Create a new VFS file descriptor (stored in memory obtained from
26837 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
26838 **
26839 ** The caller is responsible not only for closing the file descriptor
26840 ** but also for freeing the memory associated with the file descriptor.
26841 */
26842 static int proxyCreateUnixFile(
26843     const char *path,        /* path for the new unixFile */
26844     unixFile **ppFile,       /* unixFile created and returned by ref */
26845     int islockfile           /* if non zero missing dirs will be created */
26846 ) {
26847   int fd = -1;
26848   int dirfd = -1;
26849   unixFile *pNew;
26850   int rc = SQLITE_OK;
26851   int openFlags = O_RDWR | O_CREAT;
26852   sqlite3_vfs dummyVfs;
26853   int terrno = 0;
26854   UnixUnusedFd *pUnused = NULL;
26855
26856   /* 1. first try to open/create the file
26857   ** 2. if that fails, and this is a lock file (not-conch), try creating
26858   ** the parent directories and then try again.
26859   ** 3. if that fails, try to open the file read-only
26860   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
26861   */
26862   pUnused = findReusableFd(path, openFlags);
26863   if( pUnused ){
26864     fd = pUnused->fd;
26865   }else{
26866     pUnused = sqlite3_malloc(sizeof(*pUnused));
26867     if( !pUnused ){
26868       return SQLITE_NOMEM;
26869     }
26870   }
26871   if( fd<0 ){
26872     fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
26873     terrno = errno;
26874     if( fd<0 && errno==ENOENT && islockfile ){
26875       if( proxyCreateLockPath(path) == SQLITE_OK ){
26876         fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
26877       }
26878     }
26879   }
26880   if( fd<0 ){
26881     openFlags = O_RDONLY;
26882     fd = open(path, openFlags, SQLITE_DEFAULT_FILE_PERMISSIONS);
26883     terrno = errno;
26884   }
26885   if( fd<0 ){
26886     if( islockfile ){
26887       return SQLITE_BUSY;
26888     }
26889     switch (terrno) {
26890       case EACCES:
26891         return SQLITE_PERM;
26892       case EIO: 
26893         return SQLITE_IOERR_LOCK; /* even though it is the conch */
26894       default:
26895         return SQLITE_CANTOPEN_BKPT;
26896     }
26897   }
26898   
26899   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
26900   if( pNew==NULL ){
26901     rc = SQLITE_NOMEM;
26902     goto end_create_proxy;
26903   }
26904   memset(pNew, 0, sizeof(unixFile));
26905   pNew->openFlags = openFlags;
26906   dummyVfs.pAppData = (void*)&autolockIoFinder;
26907   pUnused->fd = fd;
26908   pUnused->flags = openFlags;
26909   pNew->pUnused = pUnused;
26910   
26911   rc = fillInUnixFile(&dummyVfs, fd, dirfd, (sqlite3_file*)pNew, path, 0, 0);
26912   if( rc==SQLITE_OK ){
26913     *ppFile = pNew;
26914     return SQLITE_OK;
26915   }
26916 end_create_proxy:    
26917   close(fd); /* silently leak fd if error, we're already in error */
26918   sqlite3_free(pNew);
26919   sqlite3_free(pUnused);
26920   return rc;
26921 }
26922
26923 #ifdef SQLITE_TEST
26924 /* simulate multiple hosts by creating unique hostid file paths */
26925 SQLITE_API int sqlite3_hostid_num = 0;
26926 #endif
26927
26928 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
26929
26930 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
26931 ** bytes of writable memory.
26932 */
26933 static int proxyGetHostID(unsigned char *pHostID, int *pError){
26934   struct timespec timeout = {1, 0}; /* 1 sec timeout */
26935   
26936   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
26937   memset(pHostID, 0, PROXY_HOSTIDLEN);
26938   if( gethostuuid(pHostID, &timeout) ){
26939     int err = errno;
26940     if( pError ){
26941       *pError = err;
26942     }
26943     return SQLITE_IOERR;
26944   }
26945 #ifdef SQLITE_TEST
26946   /* simulate multiple hosts by creating unique hostid file paths */
26947   if( sqlite3_hostid_num != 0){
26948     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
26949   }
26950 #endif
26951   
26952   return SQLITE_OK;
26953 }
26954
26955 /* The conch file contains the header, host id and lock file path
26956  */
26957 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
26958 #define PROXY_HEADERLEN    1   /* conch file header length */
26959 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
26960 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
26961
26962 /* 
26963 ** Takes an open conch file, copies the contents to a new path and then moves 
26964 ** it back.  The newly created file's file descriptor is assigned to the
26965 ** conch file structure and finally the original conch file descriptor is 
26966 ** closed.  Returns zero if successful.
26967 */
26968 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
26969   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
26970   unixFile *conchFile = pCtx->conchFile;
26971   char tPath[MAXPATHLEN];
26972   char buf[PROXY_MAXCONCHLEN];
26973   char *cPath = pCtx->conchFilePath;
26974   size_t readLen = 0;
26975   size_t pathLen = 0;
26976   char errmsg[64] = "";
26977   int fd = -1;
26978   int rc = -1;
26979
26980   /* create a new path by replace the trailing '-conch' with '-break' */
26981   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
26982   if( pathLen>MAXPATHLEN || pathLen<6 || 
26983      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
26984     sprintf(errmsg, "path error (len %d)", (int)pathLen);
26985     goto end_breaklock;
26986   }
26987   /* read the conch content */
26988   readLen = pread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
26989   if( readLen<PROXY_PATHINDEX ){
26990     sprintf(errmsg, "read error (len %d)", (int)readLen);
26991     goto end_breaklock;
26992   }
26993   /* write it out to the temporary break file */
26994   fd = open(tPath, (O_RDWR|O_CREAT|O_EXCL), SQLITE_DEFAULT_FILE_PERMISSIONS);
26995   if( fd<0 ){
26996     sprintf(errmsg, "create failed (%d)", errno);
26997     goto end_breaklock;
26998   }
26999   if( pwrite(fd, buf, readLen, 0) != readLen ){
27000     sprintf(errmsg, "write failed (%d)", errno);
27001     goto end_breaklock;
27002   }
27003   if( rename(tPath, cPath) ){
27004     sprintf(errmsg, "rename failed (%d)", errno);
27005     goto end_breaklock;
27006   }
27007   rc = 0;
27008   fprintf(stderr, "broke stale lock on %s\n", cPath);
27009   close(conchFile->h);
27010   conchFile->h = fd;
27011   conchFile->openFlags = O_RDWR | O_CREAT;
27012
27013 end_breaklock:
27014   if( rc ){
27015     if( fd>=0 ){
27016       unlink(tPath);
27017       close(fd);
27018     }
27019     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
27020   }
27021   return rc;
27022 }
27023
27024 /* Take the requested lock on the conch file and break a stale lock if the 
27025 ** host id matches.
27026 */
27027 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
27028   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
27029   unixFile *conchFile = pCtx->conchFile;
27030   int rc = SQLITE_OK;
27031   int nTries = 0;
27032   struct timespec conchModTime;
27033   
27034   do {
27035     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
27036     nTries ++;
27037     if( rc==SQLITE_BUSY ){
27038       /* If the lock failed (busy):
27039        * 1st try: get the mod time of the conch, wait 0.5s and try again. 
27040        * 2nd try: fail if the mod time changed or host id is different, wait 
27041        *           10 sec and try again
27042        * 3rd try: break the lock unless the mod time has changed.
27043        */
27044       struct stat buf;
27045       if( fstat(conchFile->h, &buf) ){
27046         pFile->lastErrno = errno;
27047         return SQLITE_IOERR_LOCK;
27048       }
27049       
27050       if( nTries==1 ){
27051         conchModTime = buf.st_mtimespec;
27052         usleep(500000); /* wait 0.5 sec and try the lock again*/
27053         continue;  
27054       }
27055
27056       assert( nTries>1 );
27057       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
27058          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
27059         return SQLITE_BUSY;
27060       }
27061       
27062       if( nTries==2 ){  
27063         char tBuf[PROXY_MAXCONCHLEN];
27064         int len = pread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
27065         if( len<0 ){
27066           pFile->lastErrno = errno;
27067           return SQLITE_IOERR_LOCK;
27068         }
27069         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
27070           /* don't break the lock if the host id doesn't match */
27071           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
27072             return SQLITE_BUSY;
27073           }
27074         }else{
27075           /* don't break the lock on short read or a version mismatch */
27076           return SQLITE_BUSY;
27077         }
27078         usleep(10000000); /* wait 10 sec and try the lock again */
27079         continue; 
27080       }
27081       
27082       assert( nTries==3 );
27083       if( 0==proxyBreakConchLock(pFile, myHostID) ){
27084         rc = SQLITE_OK;
27085         if( lockType==EXCLUSIVE_LOCK ){
27086           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);          
27087         }
27088         if( !rc ){
27089           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
27090         }
27091       }
27092     }
27093   } while( rc==SQLITE_BUSY && nTries<3 );
27094   
27095   return rc;
27096 }
27097
27098 /* Takes the conch by taking a shared lock and read the contents conch, if 
27099 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
27100 ** lockPath means that the lockPath in the conch file will be used if the 
27101 ** host IDs match, or a new lock path will be generated automatically 
27102 ** and written to the conch file.
27103 */
27104 static int proxyTakeConch(unixFile *pFile){
27105   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
27106   
27107   if( pCtx->conchHeld!=0 ){
27108     return SQLITE_OK;
27109   }else{
27110     unixFile *conchFile = pCtx->conchFile;
27111     uuid_t myHostID;
27112     int pError = 0;
27113     char readBuf[PROXY_MAXCONCHLEN];
27114     char lockPath[MAXPATHLEN];
27115     char *tempLockPath = NULL;
27116     int rc = SQLITE_OK;
27117     int createConch = 0;
27118     int hostIdMatch = 0;
27119     int readLen = 0;
27120     int tryOldLockPath = 0;
27121     int forceNewLockPath = 0;
27122     
27123     OSTRACE4("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
27124              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid());
27125
27126     rc = proxyGetHostID(myHostID, &pError);
27127     if( (rc&0xff)==SQLITE_IOERR ){
27128       pFile->lastErrno = pError;
27129       goto end_takeconch;
27130     }
27131     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
27132     if( rc!=SQLITE_OK ){
27133       goto end_takeconch;
27134     }
27135     /* read the existing conch file */
27136     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
27137     if( readLen<0 ){
27138       /* I/O error: lastErrno set by seekAndRead */
27139       pFile->lastErrno = conchFile->lastErrno;
27140       rc = SQLITE_IOERR_READ;
27141       goto end_takeconch;
27142     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
27143              readBuf[0]!=(char)PROXY_CONCHVERSION ){
27144       /* a short read or version format mismatch means we need to create a new 
27145       ** conch file. 
27146       */
27147       createConch = 1;
27148     }
27149     /* if the host id matches and the lock path already exists in the conch
27150     ** we'll try to use the path there, if we can't open that path, we'll 
27151     ** retry with a new auto-generated path 
27152     */
27153     do { /* in case we need to try again for an :auto: named lock file */
27154
27155       if( !createConch && !forceNewLockPath ){
27156         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
27157                                   PROXY_HOSTIDLEN);
27158         /* if the conch has data compare the contents */
27159         if( !pCtx->lockProxyPath ){
27160           /* for auto-named local lock file, just check the host ID and we'll
27161            ** use the local lock file path that's already in there
27162            */
27163           if( hostIdMatch ){
27164             size_t pathLen = (readLen - PROXY_PATHINDEX);
27165             
27166             if( pathLen>=MAXPATHLEN ){
27167               pathLen=MAXPATHLEN-1;
27168             }
27169             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
27170             lockPath[pathLen] = 0;
27171             tempLockPath = lockPath;
27172             tryOldLockPath = 1;
27173             /* create a copy of the lock path if the conch is taken */
27174             goto end_takeconch;
27175           }
27176         }else if( hostIdMatch
27177                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
27178                            readLen-PROXY_PATHINDEX)
27179         ){
27180           /* conch host and lock path match */
27181           goto end_takeconch; 
27182         }
27183       }
27184       
27185       /* if the conch isn't writable and doesn't match, we can't take it */
27186       if( (conchFile->openFlags&O_RDWR) == 0 ){
27187         rc = SQLITE_BUSY;
27188         goto end_takeconch;
27189       }
27190       
27191       /* either the conch didn't match or we need to create a new one */
27192       if( !pCtx->lockProxyPath ){
27193         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
27194         tempLockPath = lockPath;
27195         /* create a copy of the lock path _only_ if the conch is taken */
27196       }
27197       
27198       /* update conch with host and path (this will fail if other process
27199       ** has a shared lock already), if the host id matches, use the big
27200       ** stick.
27201       */
27202       futimes(conchFile->h, NULL);
27203       if( hostIdMatch && !createConch ){
27204         if( conchFile->pLock && conchFile->pLock->cnt>1 ){
27205           /* We are trying for an exclusive lock but another thread in this
27206            ** same process is still holding a shared lock. */
27207           rc = SQLITE_BUSY;
27208         } else {          
27209           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
27210         }
27211       }else{
27212         rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
27213       }
27214       if( rc==SQLITE_OK ){
27215         char writeBuffer[PROXY_MAXCONCHLEN];
27216         int writeSize = 0;
27217         
27218         writeBuffer[0] = (char)PROXY_CONCHVERSION;
27219         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
27220         if( pCtx->lockProxyPath!=NULL ){
27221           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
27222         }else{
27223           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
27224         }
27225         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
27226         ftruncate(conchFile->h, writeSize);
27227         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
27228         fsync(conchFile->h);
27229         /* If we created a new conch file (not just updated the contents of a 
27230          ** valid conch file), try to match the permissions of the database 
27231          */
27232         if( rc==SQLITE_OK && createConch ){
27233           struct stat buf;
27234           int err = fstat(pFile->h, &buf);
27235           if( err==0 ){
27236             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
27237                                         S_IROTH|S_IWOTH);
27238             /* try to match the database file R/W permissions, ignore failure */
27239 #ifndef SQLITE_PROXY_DEBUG
27240             fchmod(conchFile->h, cmode);
27241 #else
27242             if( fchmod(conchFile->h, cmode)!=0 ){
27243               int code = errno;
27244               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
27245                       cmode, code, strerror(code));
27246             } else {
27247               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
27248             }
27249           }else{
27250             int code = errno;
27251             fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
27252                     err, code, strerror(code));
27253 #endif
27254           }
27255         }
27256       }
27257       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
27258       
27259     end_takeconch:
27260       OSTRACE2("TRANSPROXY: CLOSE  %d\n", pFile->h);
27261       if( rc==SQLITE_OK && pFile->openFlags ){
27262         if( pFile->h>=0 ){
27263 #ifdef STRICT_CLOSE_ERROR
27264           if( close(pFile->h) ){
27265             pFile->lastErrno = errno;
27266             return SQLITE_IOERR_CLOSE;
27267           }
27268 #else
27269           close(pFile->h); /* silently leak fd if fail */
27270 #endif
27271         }
27272         pFile->h = -1;
27273         int fd = open(pCtx->dbPath, pFile->openFlags,
27274                       SQLITE_DEFAULT_FILE_PERMISSIONS);
27275         OSTRACE2("TRANSPROXY: OPEN  %d\n", fd);
27276         if( fd>=0 ){
27277           pFile->h = fd;
27278         }else{
27279           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
27280            during locking */
27281         }
27282       }
27283       if( rc==SQLITE_OK && !pCtx->lockProxy ){
27284         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
27285         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
27286         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
27287           /* we couldn't create the proxy lock file with the old lock file path
27288            ** so try again via auto-naming 
27289            */
27290           forceNewLockPath = 1;
27291           tryOldLockPath = 0;
27292           continue; /* go back to the do {} while start point, try again */
27293         }
27294       }
27295       if( rc==SQLITE_OK ){
27296         /* Need to make a copy of path if we extracted the value
27297          ** from the conch file or the path was allocated on the stack
27298          */
27299         if( tempLockPath ){
27300           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
27301           if( !pCtx->lockProxyPath ){
27302             rc = SQLITE_NOMEM;
27303           }
27304         }
27305       }
27306       if( rc==SQLITE_OK ){
27307         pCtx->conchHeld = 1;
27308         
27309         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
27310           afpLockingContext *afpCtx;
27311           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
27312           afpCtx->dbPath = pCtx->lockProxyPath;
27313         }
27314       } else {
27315         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
27316       }
27317       OSTRACE3("TAKECONCH  %d %s\n", conchFile->h, rc==SQLITE_OK?"ok":"failed");
27318       return rc;
27319     } while (1); /* in case we need to retry the :auto: lock file - we should never get here except via the 'continue' call. */
27320   }
27321 }
27322
27323 /*
27324 ** If pFile holds a lock on a conch file, then release that lock.
27325 */
27326 static int proxyReleaseConch(unixFile *pFile){
27327   int rc;                     /* Subroutine return code */
27328   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
27329   unixFile *conchFile;        /* Name of the conch file */
27330
27331   pCtx = (proxyLockingContext *)pFile->lockingContext;
27332   conchFile = pCtx->conchFile;
27333   OSTRACE4("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
27334            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
27335            getpid());
27336   if( pCtx->conchHeld>0 ){
27337     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
27338   }
27339   pCtx->conchHeld = 0;
27340   OSTRACE3("RELEASECONCH  %d %s\n", conchFile->h,
27341            (rc==SQLITE_OK ? "ok" : "failed"));
27342   return rc;
27343 }
27344
27345 /*
27346 ** Given the name of a database file, compute the name of its conch file.
27347 ** Store the conch filename in memory obtained from sqlite3_malloc().
27348 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
27349 ** or SQLITE_NOMEM if unable to obtain memory.
27350 **
27351 ** The caller is responsible for ensuring that the allocated memory
27352 ** space is eventually freed.
27353 **
27354 ** *pConchPath is set to NULL if a memory allocation error occurs.
27355 */
27356 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
27357   int i;                        /* Loop counter */
27358   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
27359   char *conchPath;              /* buffer in which to construct conch name */
27360
27361   /* Allocate space for the conch filename and initialize the name to
27362   ** the name of the original database file. */  
27363   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
27364   if( conchPath==0 ){
27365     return SQLITE_NOMEM;
27366   }
27367   memcpy(conchPath, dbPath, len+1);
27368   
27369   /* now insert a "." before the last / character */
27370   for( i=(len-1); i>=0; i-- ){
27371     if( conchPath[i]=='/' ){
27372       i++;
27373       break;
27374     }
27375   }
27376   conchPath[i]='.';
27377   while ( i<len ){
27378     conchPath[i+1]=dbPath[i];
27379     i++;
27380   }
27381
27382   /* append the "-conch" suffix to the file */
27383   memcpy(&conchPath[i+1], "-conch", 7);
27384   assert( (int)strlen(conchPath) == len+7 );
27385
27386   return SQLITE_OK;
27387 }
27388
27389
27390 /* Takes a fully configured proxy locking-style unix file and switches
27391 ** the local lock file path 
27392 */
27393 static int switchLockProxyPath(unixFile *pFile, const char *path) {
27394   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
27395   char *oldPath = pCtx->lockProxyPath;
27396   int rc = SQLITE_OK;
27397
27398   if( pFile->locktype!=NO_LOCK ){
27399     return SQLITE_BUSY;
27400   }  
27401
27402   /* nothing to do if the path is NULL, :auto: or matches the existing path */
27403   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
27404     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
27405     return SQLITE_OK;
27406   }else{
27407     unixFile *lockProxy = pCtx->lockProxy;
27408     pCtx->lockProxy=NULL;
27409     pCtx->conchHeld = 0;
27410     if( lockProxy!=NULL ){
27411       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
27412       if( rc ) return rc;
27413       sqlite3_free(lockProxy);
27414     }
27415     sqlite3_free(oldPath);
27416     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
27417   }
27418   
27419   return rc;
27420 }
27421
27422 /*
27423 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
27424 ** is a string buffer at least MAXPATHLEN+1 characters in size.
27425 **
27426 ** This routine find the filename associated with pFile and writes it
27427 ** int dbPath.
27428 */
27429 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
27430 #if defined(__APPLE__)
27431   if( pFile->pMethod == &afpIoMethods ){
27432     /* afp style keeps a reference to the db path in the filePath field 
27433     ** of the struct */
27434     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
27435     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
27436   } else
27437 #endif
27438   if( pFile->pMethod == &dotlockIoMethods ){
27439     /* dot lock style uses the locking context to store the dot lock
27440     ** file path */
27441     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
27442     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
27443   }else{
27444     /* all other styles use the locking context to store the db file path */
27445     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
27446     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
27447   }
27448   return SQLITE_OK;
27449 }
27450
27451 /*
27452 ** Takes an already filled in unix file and alters it so all file locking 
27453 ** will be performed on the local proxy lock file.  The following fields
27454 ** are preserved in the locking context so that they can be restored and 
27455 ** the unix structure properly cleaned up at close time:
27456 **  ->lockingContext
27457 **  ->pMethod
27458 */
27459 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
27460   proxyLockingContext *pCtx;
27461   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
27462   char *lockPath=NULL;
27463   int rc = SQLITE_OK;
27464   
27465   if( pFile->locktype!=NO_LOCK ){
27466     return SQLITE_BUSY;
27467   }
27468   proxyGetDbPathForUnixFile(pFile, dbPath);
27469   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
27470     lockPath=NULL;
27471   }else{
27472     lockPath=(char *)path;
27473   }
27474   
27475   OSTRACE4("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
27476            (lockPath ? lockPath : ":auto:"), getpid());
27477
27478   pCtx = sqlite3_malloc( sizeof(*pCtx) );
27479   if( pCtx==0 ){
27480     return SQLITE_NOMEM;
27481   }
27482   memset(pCtx, 0, sizeof(*pCtx));
27483
27484   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
27485   if( rc==SQLITE_OK ){
27486     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
27487     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
27488       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
27489       ** (c) the file system is read-only, then enable no-locking access.
27490       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
27491       ** that openFlags will have only one of O_RDONLY or O_RDWR.
27492       */
27493       struct statfs fsInfo;
27494       struct stat conchInfo;
27495       int goLockless = 0;
27496
27497       if( stat(pCtx->conchFilePath, &conchInfo) == -1 ) {
27498         int err = errno;
27499         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
27500           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
27501         }
27502       }
27503       if( goLockless ){
27504         pCtx->conchHeld = -1; /* read only FS/ lockless */
27505         rc = SQLITE_OK;
27506       }
27507     }
27508   }  
27509   if( rc==SQLITE_OK && lockPath ){
27510     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
27511   }
27512
27513   if( rc==SQLITE_OK ){
27514     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
27515     if( pCtx->dbPath==NULL ){
27516       rc = SQLITE_NOMEM;
27517     }
27518   }
27519   if( rc==SQLITE_OK ){
27520     /* all memory is allocated, proxys are created and assigned, 
27521     ** switch the locking context and pMethod then return.
27522     */
27523     pCtx->oldLockingContext = pFile->lockingContext;
27524     pFile->lockingContext = pCtx;
27525     pCtx->pOldMethod = pFile->pMethod;
27526     pFile->pMethod = &proxyIoMethods;
27527   }else{
27528     if( pCtx->conchFile ){ 
27529       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
27530       sqlite3_free(pCtx->conchFile);
27531     }
27532     sqlite3_free(pCtx->lockProxyPath);
27533     sqlite3_free(pCtx->conchFilePath); 
27534     sqlite3_free(pCtx);
27535   }
27536   OSTRACE3("TRANSPROXY  %d %s\n", pFile->h,
27537            (rc==SQLITE_OK ? "ok" : "failed"));
27538   return rc;
27539 }
27540
27541
27542 /*
27543 ** This routine handles sqlite3_file_control() calls that are specific
27544 ** to proxy locking.
27545 */
27546 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
27547   switch( op ){
27548     case SQLITE_GET_LOCKPROXYFILE: {
27549       unixFile *pFile = (unixFile*)id;
27550       if( pFile->pMethod == &proxyIoMethods ){
27551         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
27552         proxyTakeConch(pFile);
27553         if( pCtx->lockProxyPath ){
27554           *(const char **)pArg = pCtx->lockProxyPath;
27555         }else{
27556           *(const char **)pArg = ":auto: (not held)";
27557         }
27558       } else {
27559         *(const char **)pArg = NULL;
27560       }
27561       return SQLITE_OK;
27562     }
27563     case SQLITE_SET_LOCKPROXYFILE: {
27564       unixFile *pFile = (unixFile*)id;
27565       int rc = SQLITE_OK;
27566       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
27567       if( pArg==NULL || (const char *)pArg==0 ){
27568         if( isProxyStyle ){
27569           /* turn off proxy locking - not supported */
27570           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
27571         }else{
27572           /* turn off proxy locking - already off - NOOP */
27573           rc = SQLITE_OK;
27574         }
27575       }else{
27576         const char *proxyPath = (const char *)pArg;
27577         if( isProxyStyle ){
27578           proxyLockingContext *pCtx = 
27579             (proxyLockingContext*)pFile->lockingContext;
27580           if( !strcmp(pArg, ":auto:") 
27581            || (pCtx->lockProxyPath &&
27582                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
27583           ){
27584             rc = SQLITE_OK;
27585           }else{
27586             rc = switchLockProxyPath(pFile, proxyPath);
27587           }
27588         }else{
27589           /* turn on proxy file locking */
27590           rc = proxyTransformUnixFile(pFile, proxyPath);
27591         }
27592       }
27593       return rc;
27594     }
27595     default: {
27596       assert( 0 );  /* The call assures that only valid opcodes are sent */
27597     }
27598   }
27599   /*NOTREACHED*/
27600   return SQLITE_ERROR;
27601 }
27602
27603 /*
27604 ** Within this division (the proxying locking implementation) the procedures
27605 ** above this point are all utilities.  The lock-related methods of the
27606 ** proxy-locking sqlite3_io_method object follow.
27607 */
27608
27609
27610 /*
27611 ** This routine checks if there is a RESERVED lock held on the specified
27612 ** file by this or any other process. If such a lock is held, set *pResOut
27613 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
27614 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27615 */
27616 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
27617   unixFile *pFile = (unixFile*)id;
27618   int rc = proxyTakeConch(pFile);
27619   if( rc==SQLITE_OK ){
27620     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
27621     if( pCtx->conchHeld>0 ){
27622       unixFile *proxy = pCtx->lockProxy;
27623       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
27624     }else{ /* conchHeld < 0 is lockless */
27625       pResOut=0;
27626     }
27627   }
27628   return rc;
27629 }
27630
27631 /*
27632 ** Lock the file with the lock specified by parameter locktype - one
27633 ** of the following:
27634 **
27635 **     (1) SHARED_LOCK
27636 **     (2) RESERVED_LOCK
27637 **     (3) PENDING_LOCK
27638 **     (4) EXCLUSIVE_LOCK
27639 **
27640 ** Sometimes when requesting one lock state, additional lock states
27641 ** are inserted in between.  The locking might fail on one of the later
27642 ** transitions leaving the lock state different from what it started but
27643 ** still short of its goal.  The following chart shows the allowed
27644 ** transitions and the inserted intermediate states:
27645 **
27646 **    UNLOCKED -> SHARED
27647 **    SHARED -> RESERVED
27648 **    SHARED -> (PENDING) -> EXCLUSIVE
27649 **    RESERVED -> (PENDING) -> EXCLUSIVE
27650 **    PENDING -> EXCLUSIVE
27651 **
27652 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27653 ** routine to lower a locking level.
27654 */
27655 static int proxyLock(sqlite3_file *id, int locktype) {
27656   unixFile *pFile = (unixFile*)id;
27657   int rc = proxyTakeConch(pFile);
27658   if( rc==SQLITE_OK ){
27659     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
27660     if( pCtx->conchHeld>0 ){
27661       unixFile *proxy = pCtx->lockProxy;
27662       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, locktype);
27663       pFile->locktype = proxy->locktype;
27664     }else{
27665       /* conchHeld < 0 is lockless */
27666     }
27667   }
27668   return rc;
27669 }
27670
27671
27672 /*
27673 ** Lower the locking level on file descriptor pFile to locktype.  locktype
27674 ** must be either NO_LOCK or SHARED_LOCK.
27675 **
27676 ** If the locking level of the file descriptor is already at or below
27677 ** the requested locking level, this routine is a no-op.
27678 */
27679 static int proxyUnlock(sqlite3_file *id, int locktype) {
27680   unixFile *pFile = (unixFile*)id;
27681   int rc = proxyTakeConch(pFile);
27682   if( rc==SQLITE_OK ){
27683     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
27684     if( pCtx->conchHeld>0 ){
27685       unixFile *proxy = pCtx->lockProxy;
27686       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, locktype);
27687       pFile->locktype = proxy->locktype;
27688     }else{
27689       /* conchHeld < 0 is lockless */
27690     }
27691   }
27692   return rc;
27693 }
27694
27695 /*
27696 ** Close a file that uses proxy locks.
27697 */
27698 static int proxyClose(sqlite3_file *id) {
27699   if( id ){
27700     unixFile *pFile = (unixFile*)id;
27701     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
27702     unixFile *lockProxy = pCtx->lockProxy;
27703     unixFile *conchFile = pCtx->conchFile;
27704     int rc = SQLITE_OK;
27705     
27706     if( lockProxy ){
27707       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
27708       if( rc ) return rc;
27709       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
27710       if( rc ) return rc;
27711       sqlite3_free(lockProxy);
27712       pCtx->lockProxy = 0;
27713     }
27714     if( conchFile ){
27715       if( pCtx->conchHeld ){
27716         rc = proxyReleaseConch(pFile);
27717         if( rc ) return rc;
27718       }
27719       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
27720       if( rc ) return rc;
27721       sqlite3_free(conchFile);
27722     }
27723     sqlite3_free(pCtx->lockProxyPath);
27724     sqlite3_free(pCtx->conchFilePath);
27725     sqlite3_free(pCtx->dbPath);
27726     /* restore the original locking context and pMethod then close it */
27727     pFile->lockingContext = pCtx->oldLockingContext;
27728     pFile->pMethod = pCtx->pOldMethod;
27729     sqlite3_free(pCtx);
27730     return pFile->pMethod->xClose(id);
27731   }
27732   return SQLITE_OK;
27733 }
27734
27735
27736
27737 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27738 /*
27739 ** The proxy locking style is intended for use with AFP filesystems.
27740 ** And since AFP is only supported on MacOSX, the proxy locking is also
27741 ** restricted to MacOSX.
27742 ** 
27743 **
27744 ******************* End of the proxy lock implementation **********************
27745 ******************************************************************************/
27746
27747 /*
27748 ** Initialize the operating system interface.
27749 **
27750 ** This routine registers all VFS implementations for unix-like operating
27751 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
27752 ** should be the only routines in this file that are visible from other
27753 ** files.
27754 **
27755 ** This routine is called once during SQLite initialization and by a
27756 ** single thread.  The memory allocation and mutex subsystems have not
27757 ** necessarily been initialized when this routine is called, and so they
27758 ** should not be used.
27759 */
27760 SQLITE_API int sqlite3_os_init(void){ 
27761   /* 
27762   ** The following macro defines an initializer for an sqlite3_vfs object.
27763   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
27764   ** to the "finder" function.  (pAppData is a pointer to a pointer because
27765   ** silly C90 rules prohibit a void* from being cast to a function pointer
27766   ** and so we have to go through the intermediate pointer to avoid problems
27767   ** when compiling with -pedantic-errors on GCC.)
27768   **
27769   ** The FINDER parameter to this macro is the name of the pointer to the
27770   ** finder-function.  The finder-function returns a pointer to the
27771   ** sqlite_io_methods object that implements the desired locking
27772   ** behaviors.  See the division above that contains the IOMETHODS
27773   ** macro for addition information on finder-functions.
27774   **
27775   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
27776   ** object.  But the "autolockIoFinder" available on MacOSX does a little
27777   ** more than that; it looks at the filesystem type that hosts the 
27778   ** database file and tries to choose an locking method appropriate for
27779   ** that filesystem time.
27780   */
27781   #define UNIXVFS(VFSNAME, FINDER) {                        \
27782     1,                    /* iVersion */                    \
27783     sizeof(unixFile),     /* szOsFile */                    \
27784     MAX_PATHNAME,         /* mxPathname */                  \
27785     0,                    /* pNext */                       \
27786     VFSNAME,              /* zName */                       \
27787     (void*)&FINDER,       /* pAppData */                    \
27788     unixOpen,             /* xOpen */                       \
27789     unixDelete,           /* xDelete */                     \
27790     unixAccess,           /* xAccess */                     \
27791     unixFullPathname,     /* xFullPathname */               \
27792     unixDlOpen,           /* xDlOpen */                     \
27793     unixDlError,          /* xDlError */                    \
27794     unixDlSym,            /* xDlSym */                      \
27795     unixDlClose,          /* xDlClose */                    \
27796     unixRandomness,       /* xRandomness */                 \
27797     unixSleep,            /* xSleep */                      \
27798     unixCurrentTime,      /* xCurrentTime */                \
27799     unixGetLastError      /* xGetLastError */               \
27800   }
27801
27802   /*
27803   ** All default VFSes for unix are contained in the following array.
27804   **
27805   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
27806   ** by the SQLite core when the VFS is registered.  So the following
27807   ** array cannot be const.
27808   */
27809   static sqlite3_vfs aVfs[] = {
27810 #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
27811     UNIXVFS("unix",          autolockIoFinder ),
27812 #else
27813     UNIXVFS("unix",          posixIoFinder ),
27814 #endif
27815     UNIXVFS("unix-none",     nolockIoFinder ),
27816     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
27817 #if OS_VXWORKS
27818     UNIXVFS("unix-namedsem", semIoFinder ),
27819 #endif
27820 #if SQLITE_ENABLE_LOCKING_STYLE
27821     UNIXVFS("unix-posix",    posixIoFinder ),
27822 #if !OS_VXWORKS
27823     UNIXVFS("unix-flock",    flockIoFinder ),
27824 #endif
27825 #endif
27826 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
27827     UNIXVFS("unix-afp",      afpIoFinder ),
27828     UNIXVFS("unix-nfs",      nfsIoFinder ),
27829     UNIXVFS("unix-proxy",    proxyIoFinder ),
27830 #endif
27831   };
27832   unsigned int i;          /* Loop counter */
27833
27834   /* Register all VFSes defined in the aVfs[] array */
27835   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
27836     sqlite3_vfs_register(&aVfs[i], i==0);
27837   }
27838   return SQLITE_OK; 
27839 }
27840
27841 /*
27842 ** Shutdown the operating system interface.
27843 **
27844 ** Some operating systems might need to do some cleanup in this routine,
27845 ** to release dynamically allocated objects.  But not on unix.
27846 ** This routine is a no-op for unix.
27847 */
27848 SQLITE_API int sqlite3_os_end(void){ 
27849   return SQLITE_OK; 
27850 }
27851  
27852 #endif /* SQLITE_OS_UNIX */
27853
27854 /************** End of os_unix.c *********************************************/
27855 /************** Begin file os_win.c ******************************************/
27856 /*
27857 ** 2004 May 22
27858 **
27859 ** The author disclaims copyright to this source code.  In place of
27860 ** a legal notice, here is a blessing:
27861 **
27862 **    May you do good and not evil.
27863 **    May you find forgiveness for yourself and forgive others.
27864 **    May you share freely, never taking more than you give.
27865 **
27866 ******************************************************************************
27867 **
27868 ** This file contains code that is specific to windows.
27869 */
27870 #if SQLITE_OS_WIN               /* This file is used for windows only */
27871
27872
27873 /*
27874 ** A Note About Memory Allocation:
27875 **
27876 ** This driver uses malloc()/free() directly rather than going through
27877 ** the SQLite-wrappers sqlite3_malloc()/sqlite3_free().  Those wrappers
27878 ** are designed for use on embedded systems where memory is scarce and
27879 ** malloc failures happen frequently.  Win32 does not typically run on
27880 ** embedded systems, and when it does the developers normally have bigger
27881 ** problems to worry about than running out of memory.  So there is not
27882 ** a compelling need to use the wrappers.
27883 **
27884 ** But there is a good reason to not use the wrappers.  If we use the
27885 ** wrappers then we will get simulated malloc() failures within this
27886 ** driver.  And that causes all kinds of problems for our tests.  We
27887 ** could enhance SQLite to deal with simulated malloc failures within
27888 ** the OS driver, but the code to deal with those failure would not
27889 ** be exercised on Linux (which does not need to malloc() in the driver)
27890 ** and so we would have difficulty writing coverage tests for that
27891 ** code.  Better to leave the code out, we think.
27892 **
27893 ** The point of this discussion is as follows:  When creating a new
27894 ** OS layer for an embedded system, if you use this file as an example,
27895 ** avoid the use of malloc()/free().  Those routines work ok on windows
27896 ** desktops but not so well in embedded systems.
27897 */
27898
27899 #include <winbase.h>
27900
27901 #ifdef __CYGWIN__
27902 # include <sys/cygwin.h>
27903 #endif
27904
27905 /*
27906 ** Macros used to determine whether or not to use threads.
27907 */
27908 #if defined(THREADSAFE) && THREADSAFE
27909 # define SQLITE_W32_THREADS 1
27910 #endif
27911
27912 /*
27913 ** Include code that is common to all os_*.c files
27914 */
27915 /************** Include os_common.h in the middle of os_win.c ****************/
27916 /************** Begin file os_common.h ***************************************/
27917 /*
27918 ** 2004 May 22
27919 **
27920 ** The author disclaims copyright to this source code.  In place of
27921 ** a legal notice, here is a blessing:
27922 **
27923 **    May you do good and not evil.
27924 **    May you find forgiveness for yourself and forgive others.
27925 **    May you share freely, never taking more than you give.
27926 **
27927 ******************************************************************************
27928 **
27929 ** This file contains macros and a little bit of code that is common to
27930 ** all of the platform-specific files (os_*.c) and is #included into those
27931 ** files.
27932 **
27933 ** This file should be #included by the os_*.c files only.  It is not a
27934 ** general purpose header file.
27935 */
27936 #ifndef _OS_COMMON_H_
27937 #define _OS_COMMON_H_
27938
27939 /*
27940 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
27941 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
27942 ** switch.  The following code should catch this problem at compile-time.
27943 */
27944 #ifdef MEMORY_DEBUG
27945 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
27946 #endif
27947
27948 #ifdef SQLITE_DEBUG
27949 SQLITE_PRIVATE int sqlite3OSTrace = 0;
27950 #define OSTRACE1(X)         if( sqlite3OSTrace ) sqlite3DebugPrintf(X)
27951 #define OSTRACE2(X,Y)       if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y)
27952 #define OSTRACE3(X,Y,Z)     if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z)
27953 #define OSTRACE4(X,Y,Z,A)   if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A)
27954 #define OSTRACE5(X,Y,Z,A,B) if( sqlite3OSTrace ) sqlite3DebugPrintf(X,Y,Z,A,B)
27955 #define OSTRACE6(X,Y,Z,A,B,C) \
27956     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C)
27957 #define OSTRACE7(X,Y,Z,A,B,C,D) \
27958     if(sqlite3OSTrace) sqlite3DebugPrintf(X,Y,Z,A,B,C,D)
27959 #else
27960 #define OSTRACE1(X)
27961 #define OSTRACE2(X,Y)
27962 #define OSTRACE3(X,Y,Z)
27963 #define OSTRACE4(X,Y,Z,A)
27964 #define OSTRACE5(X,Y,Z,A,B)
27965 #define OSTRACE6(X,Y,Z,A,B,C)
27966 #define OSTRACE7(X,Y,Z,A,B,C,D)
27967 #endif
27968
27969 /*
27970 ** Macros for performance tracing.  Normally turned off.  Only works
27971 ** on i486 hardware.
27972 */
27973 #ifdef SQLITE_PERFORMANCE_TRACE
27974
27975 /* 
27976 ** hwtime.h contains inline assembler code for implementing 
27977 ** high-performance timing routines.
27978 */
27979 /************** Include hwtime.h in the middle of os_common.h ****************/
27980 /************** Begin file hwtime.h ******************************************/
27981 /*
27982 ** 2008 May 27
27983 **
27984 ** The author disclaims copyright to this source code.  In place of
27985 ** a legal notice, here is a blessing:
27986 **
27987 **    May you do good and not evil.
27988 **    May you find forgiveness for yourself and forgive others.
27989 **    May you share freely, never taking more than you give.
27990 **
27991 ******************************************************************************
27992 **
27993 ** This file contains inline asm code for retrieving "high-performance"
27994 ** counters for x86 class CPUs.
27995 */
27996 #ifndef _HWTIME_H_
27997 #define _HWTIME_H_
27998
27999 /*
28000 ** The following routine only works on pentium-class (or newer) processors.
28001 ** It uses the RDTSC opcode to read the cycle count value out of the
28002 ** processor and returns that value.  This can be used for high-res
28003 ** profiling.
28004 */
28005 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
28006       (defined(i386) || defined(__i386__) || defined(_M_IX86))
28007
28008   #if defined(__GNUC__)
28009
28010   __inline__ sqlite_uint64 sqlite3Hwtime(void){
28011      unsigned int lo, hi;
28012      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
28013      return (sqlite_uint64)hi << 32 | lo;
28014   }
28015
28016   #elif defined(_MSC_VER)
28017
28018   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
28019      __asm {
28020         rdtsc
28021         ret       ; return value at EDX:EAX
28022      }
28023   }
28024
28025   #endif
28026
28027 #elif (defined(__GNUC__) && defined(__x86_64__))
28028
28029   __inline__ sqlite_uint64 sqlite3Hwtime(void){
28030       unsigned long val;
28031       __asm__ __volatile__ ("rdtsc" : "=A" (val));
28032       return val;
28033   }
28034  
28035 #elif (defined(__GNUC__) && defined(__ppc__))
28036
28037   __inline__ sqlite_uint64 sqlite3Hwtime(void){
28038       unsigned long long retval;
28039       unsigned long junk;
28040       __asm__ __volatile__ ("\n\
28041           1:      mftbu   %1\n\
28042                   mftb    %L0\n\
28043                   mftbu   %0\n\
28044                   cmpw    %0,%1\n\
28045                   bne     1b"
28046                   : "=r" (retval), "=r" (junk));
28047       return retval;
28048   }
28049
28050 #else
28051
28052   #error Need implementation of sqlite3Hwtime() for your platform.
28053
28054   /*
28055   ** To compile without implementing sqlite3Hwtime() for your platform,
28056   ** you can remove the above #error and use the following
28057   ** stub function.  You will lose timing support for many
28058   ** of the debugging and testing utilities, but it should at
28059   ** least compile and run.
28060   */
28061 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
28062
28063 #endif
28064
28065 #endif /* !defined(_HWTIME_H_) */
28066
28067 /************** End of hwtime.h **********************************************/
28068 /************** Continuing where we left off in os_common.h ******************/
28069
28070 static sqlite_uint64 g_start;
28071 static sqlite_uint64 g_elapsed;
28072 #define TIMER_START       g_start=sqlite3Hwtime()
28073 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
28074 #define TIMER_ELAPSED     g_elapsed
28075 #else
28076 #define TIMER_START
28077 #define TIMER_END
28078 #define TIMER_ELAPSED     ((sqlite_uint64)0)
28079 #endif
28080
28081 /*
28082 ** If we compile with the SQLITE_TEST macro set, then the following block
28083 ** of code will give us the ability to simulate a disk I/O error.  This
28084 ** is used for testing the I/O recovery logic.
28085 */
28086 #ifdef SQLITE_TEST
28087 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
28088 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
28089 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
28090 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
28091 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
28092 SQLITE_API int sqlite3_diskfull_pending = 0;
28093 SQLITE_API int sqlite3_diskfull = 0;
28094 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
28095 #define SimulateIOError(CODE)  \
28096   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
28097        || sqlite3_io_error_pending-- == 1 )  \
28098               { local_ioerr(); CODE; }
28099 static void local_ioerr(){
28100   IOTRACE(("IOERR\n"));
28101   sqlite3_io_error_hit++;
28102   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
28103 }
28104 #define SimulateDiskfullError(CODE) \
28105    if( sqlite3_diskfull_pending ){ \
28106      if( sqlite3_diskfull_pending == 1 ){ \
28107        local_ioerr(); \
28108        sqlite3_diskfull = 1; \
28109        sqlite3_io_error_hit = 1; \
28110        CODE; \
28111      }else{ \
28112        sqlite3_diskfull_pending--; \
28113      } \
28114    }
28115 #else
28116 #define SimulateIOErrorBenign(X)
28117 #define SimulateIOError(A)
28118 #define SimulateDiskfullError(A)
28119 #endif
28120
28121 /*
28122 ** When testing, keep a count of the number of open files.
28123 */
28124 #ifdef SQLITE_TEST
28125 SQLITE_API int sqlite3_open_file_count = 0;
28126 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
28127 #else
28128 #define OpenCounter(X)
28129 #endif
28130
28131 #endif /* !defined(_OS_COMMON_H_) */
28132
28133 /************** End of os_common.h *******************************************/
28134 /************** Continuing where we left off in os_win.c *********************/
28135
28136 /*
28137 ** Some microsoft compilers lack this definition.
28138 */
28139 #ifndef INVALID_FILE_ATTRIBUTES
28140 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1) 
28141 #endif
28142
28143 /*
28144 ** Determine if we are dealing with WindowsCE - which has a much
28145 ** reduced API.
28146 */
28147 #if SQLITE_OS_WINCE
28148 # define AreFileApisANSI() 1
28149 # define FormatMessageW(a,b,c,d,e,f,g) 0
28150 #endif
28151
28152 /*
28153 ** WinCE lacks native support for file locking so we have to fake it
28154 ** with some code of our own.
28155 */
28156 #if SQLITE_OS_WINCE
28157 typedef struct winceLock {
28158   int nReaders;       /* Number of reader locks obtained */
28159   BOOL bPending;      /* Indicates a pending lock has been obtained */
28160   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
28161   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
28162 } winceLock;
28163 #endif
28164
28165 /*
28166 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
28167 ** portability layer.
28168 */
28169 typedef struct winFile winFile;
28170 struct winFile {
28171   const sqlite3_io_methods *pMethod;/* Must be first */
28172   HANDLE h;               /* Handle for accessing the file */
28173   unsigned char locktype; /* Type of lock currently held on this file */
28174   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
28175   DWORD lastErrno;        /* The Windows errno from the last I/O error */
28176   DWORD sectorSize;       /* Sector size of the device file is on */
28177 #if SQLITE_OS_WINCE
28178   WCHAR *zDeleteOnClose;  /* Name of file to delete when closing */
28179   HANDLE hMutex;          /* Mutex used to control access to shared lock */  
28180   HANDLE hShared;         /* Shared memory segment used for locking */
28181   winceLock local;        /* Locks obtained by this instance of winFile */
28182   winceLock *shared;      /* Global shared lock memory for the file  */
28183 #endif
28184 };
28185
28186 /*
28187 ** Forward prototypes.
28188 */
28189 static int getSectorSize(
28190     sqlite3_vfs *pVfs,
28191     const char *zRelative     /* UTF-8 file name */
28192 );
28193
28194 /*
28195 ** The following variable is (normally) set once and never changes
28196 ** thereafter.  It records whether the operating system is Win95
28197 ** or WinNT.
28198 **
28199 ** 0:   Operating system unknown.
28200 ** 1:   Operating system is Win95.
28201 ** 2:   Operating system is WinNT.
28202 **
28203 ** In order to facilitate testing on a WinNT system, the test fixture
28204 ** can manually set this value to 1 to emulate Win98 behavior.
28205 */
28206 #ifdef SQLITE_TEST
28207 SQLITE_API int sqlite3_os_type = 0;
28208 #else
28209 static int sqlite3_os_type = 0;
28210 #endif
28211
28212 /*
28213 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
28214 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
28215 **
28216 ** Here is an interesting observation:  Win95, Win98, and WinME lack
28217 ** the LockFileEx() API.  But we can still statically link against that
28218 ** API as long as we don't call it when running Win95/98/ME.  A call to
28219 ** this routine is used to determine if the host is Win95/98/ME or
28220 ** WinNT/2K/XP so that we will know whether or not we can safely call
28221 ** the LockFileEx() API.
28222 */
28223 #if SQLITE_OS_WINCE
28224 # define isNT()  (1)
28225 #else
28226   static int isNT(void){
28227     if( sqlite3_os_type==0 ){
28228       OSVERSIONINFO sInfo;
28229       sInfo.dwOSVersionInfoSize = sizeof(sInfo);
28230       GetVersionEx(&sInfo);
28231       sqlite3_os_type = sInfo.dwPlatformId==VER_PLATFORM_WIN32_NT ? 2 : 1;
28232     }
28233     return sqlite3_os_type==2;
28234   }
28235 #endif /* SQLITE_OS_WINCE */
28236
28237 /*
28238 ** Convert a UTF-8 string to microsoft unicode (UTF-16?). 
28239 **
28240 ** Space to hold the returned string is obtained from malloc.
28241 */
28242 static WCHAR *utf8ToUnicode(const char *zFilename){
28243   int nChar;
28244   WCHAR *zWideFilename;
28245
28246   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
28247   zWideFilename = malloc( nChar*sizeof(zWideFilename[0]) );
28248   if( zWideFilename==0 ){
28249     return 0;
28250   }
28251   nChar = MultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename, nChar);
28252   if( nChar==0 ){
28253     free(zWideFilename);
28254     zWideFilename = 0;
28255   }
28256   return zWideFilename;
28257 }
28258
28259 /*
28260 ** Convert microsoft unicode to UTF-8.  Space to hold the returned string is
28261 ** obtained from malloc().
28262 */
28263 static char *unicodeToUtf8(const WCHAR *zWideFilename){
28264   int nByte;
28265   char *zFilename;
28266
28267   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
28268   zFilename = malloc( nByte );
28269   if( zFilename==0 ){
28270     return 0;
28271   }
28272   nByte = WideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
28273                               0, 0);
28274   if( nByte == 0 ){
28275     free(zFilename);
28276     zFilename = 0;
28277   }
28278   return zFilename;
28279 }
28280
28281 /*
28282 ** Convert an ansi string to microsoft unicode, based on the
28283 ** current codepage settings for file apis.
28284 ** 
28285 ** Space to hold the returned string is obtained
28286 ** from malloc.
28287 */
28288 static WCHAR *mbcsToUnicode(const char *zFilename){
28289   int nByte;
28290   WCHAR *zMbcsFilename;
28291   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
28292
28293   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, NULL,0)*sizeof(WCHAR);
28294   zMbcsFilename = malloc( nByte*sizeof(zMbcsFilename[0]) );
28295   if( zMbcsFilename==0 ){
28296     return 0;
28297   }
28298   nByte = MultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename, nByte);
28299   if( nByte==0 ){
28300     free(zMbcsFilename);
28301     zMbcsFilename = 0;
28302   }
28303   return zMbcsFilename;
28304 }
28305
28306 /*
28307 ** Convert microsoft unicode to multibyte character string, based on the
28308 ** user's Ansi codepage.
28309 **
28310 ** Space to hold the returned string is obtained from
28311 ** malloc().
28312 */
28313 static char *unicodeToMbcs(const WCHAR *zWideFilename){
28314   int nByte;
28315   char *zFilename;
28316   int codepage = AreFileApisANSI() ? CP_ACP : CP_OEMCP;
28317
28318   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
28319   zFilename = malloc( nByte );
28320   if( zFilename==0 ){
28321     return 0;
28322   }
28323   nByte = WideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename, nByte,
28324                               0, 0);
28325   if( nByte == 0 ){
28326     free(zFilename);
28327     zFilename = 0;
28328   }
28329   return zFilename;
28330 }
28331
28332 /*
28333 ** Convert multibyte character string to UTF-8.  Space to hold the
28334 ** returned string is obtained from malloc().
28335 */
28336 SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
28337   char *zFilenameUtf8;
28338   WCHAR *zTmpWide;
28339
28340   zTmpWide = mbcsToUnicode(zFilename);
28341   if( zTmpWide==0 ){
28342     return 0;
28343   }
28344   zFilenameUtf8 = unicodeToUtf8(zTmpWide);
28345   free(zTmpWide);
28346   return zFilenameUtf8;
28347 }
28348
28349 /*
28350 ** Convert UTF-8 to multibyte character string.  Space to hold the 
28351 ** returned string is obtained from malloc().
28352 */
28353 static char *utf8ToMbcs(const char *zFilename){
28354   char *zFilenameMbcs;
28355   WCHAR *zTmpWide;
28356
28357   zTmpWide = utf8ToUnicode(zFilename);
28358   if( zTmpWide==0 ){
28359     return 0;
28360   }
28361   zFilenameMbcs = unicodeToMbcs(zTmpWide);
28362   free(zTmpWide);
28363   return zFilenameMbcs;
28364 }
28365
28366 #if SQLITE_OS_WINCE
28367 /*************************************************************************
28368 ** This section contains code for WinCE only.
28369 */
28370 /*
28371 ** WindowsCE does not have a localtime() function.  So create a
28372 ** substitute.
28373 */
28374 struct tm *__cdecl localtime(const time_t *t)
28375 {
28376   static struct tm y;
28377   FILETIME uTm, lTm;
28378   SYSTEMTIME pTm;
28379   sqlite3_int64 t64;
28380   t64 = *t;
28381   t64 = (t64 + 11644473600)*10000000;
28382   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
28383   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
28384   FileTimeToLocalFileTime(&uTm,&lTm);
28385   FileTimeToSystemTime(&lTm,&pTm);
28386   y.tm_year = pTm.wYear - 1900;
28387   y.tm_mon = pTm.wMonth - 1;
28388   y.tm_wday = pTm.wDayOfWeek;
28389   y.tm_mday = pTm.wDay;
28390   y.tm_hour = pTm.wHour;
28391   y.tm_min = pTm.wMinute;
28392   y.tm_sec = pTm.wSecond;
28393   return &y;
28394 }
28395
28396 /* This will never be called, but defined to make the code compile */
28397 #define GetTempPathA(a,b)
28398
28399 #define LockFile(a,b,c,d,e)       winceLockFile(&a, b, c, d, e)
28400 #define UnlockFile(a,b,c,d,e)     winceUnlockFile(&a, b, c, d, e)
28401 #define LockFileEx(a,b,c,d,e,f)   winceLockFileEx(&a, b, c, d, e, f)
28402
28403 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
28404
28405 /*
28406 ** Acquire a lock on the handle h
28407 */
28408 static void winceMutexAcquire(HANDLE h){
28409    DWORD dwErr;
28410    do {
28411      dwErr = WaitForSingleObject(h, INFINITE);
28412    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
28413 }
28414 /*
28415 ** Release a lock acquired by winceMutexAcquire()
28416 */
28417 #define winceMutexRelease(h) ReleaseMutex(h)
28418
28419 /*
28420 ** Create the mutex and shared memory used for locking in the file
28421 ** descriptor pFile
28422 */
28423 static BOOL winceCreateLock(const char *zFilename, winFile *pFile){
28424   WCHAR *zTok;
28425   WCHAR *zName = utf8ToUnicode(zFilename);
28426   BOOL bInit = TRUE;
28427
28428   /* Initialize the local lockdata */
28429   ZeroMemory(&pFile->local, sizeof(pFile->local));
28430
28431   /* Replace the backslashes from the filename and lowercase it
28432   ** to derive a mutex name. */
28433   zTok = CharLowerW(zName);
28434   for (;*zTok;zTok++){
28435     if (*zTok == '\\') *zTok = '_';
28436   }
28437
28438   /* Create/open the named mutex */
28439   pFile->hMutex = CreateMutexW(NULL, FALSE, zName);
28440   if (!pFile->hMutex){
28441     pFile->lastErrno = GetLastError();
28442     free(zName);
28443     return FALSE;
28444   }
28445
28446   /* Acquire the mutex before continuing */
28447   winceMutexAcquire(pFile->hMutex);
28448   
28449   /* Since the names of named mutexes, semaphores, file mappings etc are 
28450   ** case-sensitive, take advantage of that by uppercasing the mutex name
28451   ** and using that as the shared filemapping name.
28452   */
28453   CharUpperW(zName);
28454   pFile->hShared = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
28455                                        PAGE_READWRITE, 0, sizeof(winceLock),
28456                                        zName);  
28457
28458   /* Set a flag that indicates we're the first to create the memory so it 
28459   ** must be zero-initialized */
28460   if (GetLastError() == ERROR_ALREADY_EXISTS){
28461     bInit = FALSE;
28462   }
28463
28464   free(zName);
28465
28466   /* If we succeeded in making the shared memory handle, map it. */
28467   if (pFile->hShared){
28468     pFile->shared = (winceLock*)MapViewOfFile(pFile->hShared, 
28469              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
28470     /* If mapping failed, close the shared memory handle and erase it */
28471     if (!pFile->shared){
28472       pFile->lastErrno = GetLastError();
28473       CloseHandle(pFile->hShared);
28474       pFile->hShared = NULL;
28475     }
28476   }
28477
28478   /* If shared memory could not be created, then close the mutex and fail */
28479   if (pFile->hShared == NULL){
28480     winceMutexRelease(pFile->hMutex);
28481     CloseHandle(pFile->hMutex);
28482     pFile->hMutex = NULL;
28483     return FALSE;
28484   }
28485   
28486   /* Initialize the shared memory if we're supposed to */
28487   if (bInit) {
28488     ZeroMemory(pFile->shared, sizeof(winceLock));
28489   }
28490
28491   winceMutexRelease(pFile->hMutex);
28492   return TRUE;
28493 }
28494
28495 /*
28496 ** Destroy the part of winFile that deals with wince locks
28497 */
28498 static void winceDestroyLock(winFile *pFile){
28499   if (pFile->hMutex){
28500     /* Acquire the mutex */
28501     winceMutexAcquire(pFile->hMutex);
28502
28503     /* The following blocks should probably assert in debug mode, but they
28504        are to cleanup in case any locks remained open */
28505     if (pFile->local.nReaders){
28506       pFile->shared->nReaders --;
28507     }
28508     if (pFile->local.bReserved){
28509       pFile->shared->bReserved = FALSE;
28510     }
28511     if (pFile->local.bPending){
28512       pFile->shared->bPending = FALSE;
28513     }
28514     if (pFile->local.bExclusive){
28515       pFile->shared->bExclusive = FALSE;
28516     }
28517
28518     /* De-reference and close our copy of the shared memory handle */
28519     UnmapViewOfFile(pFile->shared);
28520     CloseHandle(pFile->hShared);
28521
28522     /* Done with the mutex */
28523     winceMutexRelease(pFile->hMutex);    
28524     CloseHandle(pFile->hMutex);
28525     pFile->hMutex = NULL;
28526   }
28527 }
28528
28529 /* 
28530 ** An implementation of the LockFile() API of windows for wince
28531 */
28532 static BOOL winceLockFile(
28533   HANDLE *phFile,
28534   DWORD dwFileOffsetLow,
28535   DWORD dwFileOffsetHigh,
28536   DWORD nNumberOfBytesToLockLow,
28537   DWORD nNumberOfBytesToLockHigh
28538 ){
28539   winFile *pFile = HANDLE_TO_WINFILE(phFile);
28540   BOOL bReturn = FALSE;
28541
28542   UNUSED_PARAMETER(dwFileOffsetHigh);
28543   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
28544
28545   if (!pFile->hMutex) return TRUE;
28546   winceMutexAcquire(pFile->hMutex);
28547
28548   /* Wanting an exclusive lock? */
28549   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
28550        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
28551     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
28552        pFile->shared->bExclusive = TRUE;
28553        pFile->local.bExclusive = TRUE;
28554        bReturn = TRUE;
28555     }
28556   }
28557
28558   /* Want a read-only lock? */
28559   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
28560            nNumberOfBytesToLockLow == 1){
28561     if (pFile->shared->bExclusive == 0){
28562       pFile->local.nReaders ++;
28563       if (pFile->local.nReaders == 1){
28564         pFile->shared->nReaders ++;
28565       }
28566       bReturn = TRUE;
28567     }
28568   }
28569
28570   /* Want a pending lock? */
28571   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToLockLow == 1){
28572     /* If no pending lock has been acquired, then acquire it */
28573     if (pFile->shared->bPending == 0) {
28574       pFile->shared->bPending = TRUE;
28575       pFile->local.bPending = TRUE;
28576       bReturn = TRUE;
28577     }
28578   }
28579
28580   /* Want a reserved lock? */
28581   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToLockLow == 1){
28582     if (pFile->shared->bReserved == 0) {
28583       pFile->shared->bReserved = TRUE;
28584       pFile->local.bReserved = TRUE;
28585       bReturn = TRUE;
28586     }
28587   }
28588
28589   winceMutexRelease(pFile->hMutex);
28590   return bReturn;
28591 }
28592
28593 /*
28594 ** An implementation of the UnlockFile API of windows for wince
28595 */
28596 static BOOL winceUnlockFile(
28597   HANDLE *phFile,
28598   DWORD dwFileOffsetLow,
28599   DWORD dwFileOffsetHigh,
28600   DWORD nNumberOfBytesToUnlockLow,
28601   DWORD nNumberOfBytesToUnlockHigh
28602 ){
28603   winFile *pFile = HANDLE_TO_WINFILE(phFile);
28604   BOOL bReturn = FALSE;
28605
28606   UNUSED_PARAMETER(dwFileOffsetHigh);
28607   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
28608
28609   if (!pFile->hMutex) return TRUE;
28610   winceMutexAcquire(pFile->hMutex);
28611
28612   /* Releasing a reader lock or an exclusive lock */
28613   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
28614     /* Did we have an exclusive lock? */
28615     if (pFile->local.bExclusive){
28616       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
28617       pFile->local.bExclusive = FALSE;
28618       pFile->shared->bExclusive = FALSE;
28619       bReturn = TRUE;
28620     }
28621
28622     /* Did we just have a reader lock? */
28623     else if (pFile->local.nReaders){
28624       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE || nNumberOfBytesToUnlockLow == 1);
28625       pFile->local.nReaders --;
28626       if (pFile->local.nReaders == 0)
28627       {
28628         pFile->shared->nReaders --;
28629       }
28630       bReturn = TRUE;
28631     }
28632   }
28633
28634   /* Releasing a pending lock */
28635   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE && nNumberOfBytesToUnlockLow == 1){
28636     if (pFile->local.bPending){
28637       pFile->local.bPending = FALSE;
28638       pFile->shared->bPending = FALSE;
28639       bReturn = TRUE;
28640     }
28641   }
28642   /* Releasing a reserved lock */
28643   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE && nNumberOfBytesToUnlockLow == 1){
28644     if (pFile->local.bReserved) {
28645       pFile->local.bReserved = FALSE;
28646       pFile->shared->bReserved = FALSE;
28647       bReturn = TRUE;
28648     }
28649   }
28650
28651   winceMutexRelease(pFile->hMutex);
28652   return bReturn;
28653 }
28654
28655 /*
28656 ** An implementation of the LockFileEx() API of windows for wince
28657 */
28658 static BOOL winceLockFileEx(
28659   HANDLE *phFile,
28660   DWORD dwFlags,
28661   DWORD dwReserved,
28662   DWORD nNumberOfBytesToLockLow,
28663   DWORD nNumberOfBytesToLockHigh,
28664   LPOVERLAPPED lpOverlapped
28665 ){
28666   UNUSED_PARAMETER(dwReserved);
28667   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
28668
28669   /* If the caller wants a shared read lock, forward this call
28670   ** to winceLockFile */
28671   if (lpOverlapped->Offset == (DWORD)SHARED_FIRST &&
28672       dwFlags == 1 &&
28673       nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
28674     return winceLockFile(phFile, SHARED_FIRST, 0, 1, 0);
28675   }
28676   return FALSE;
28677 }
28678 /*
28679 ** End of the special code for wince
28680 *****************************************************************************/
28681 #endif /* SQLITE_OS_WINCE */
28682
28683 /*****************************************************************************
28684 ** The next group of routines implement the I/O methods specified
28685 ** by the sqlite3_io_methods object.
28686 ******************************************************************************/
28687
28688 /*
28689 ** Close a file.
28690 **
28691 ** It is reported that an attempt to close a handle might sometimes
28692 ** fail.  This is a very unreasonable result, but windows is notorious
28693 ** for being unreasonable so I do not doubt that it might happen.  If
28694 ** the close fails, we pause for 100 milliseconds and try again.  As
28695 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
28696 ** giving up and returning an error.
28697 */
28698 #define MX_CLOSE_ATTEMPT 3
28699 static int winClose(sqlite3_file *id){
28700   int rc, cnt = 0;
28701   winFile *pFile = (winFile*)id;
28702
28703   assert( id!=0 );
28704   OSTRACE2("CLOSE %d\n", pFile->h);
28705   do{
28706     rc = CloseHandle(pFile->h);
28707   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (Sleep(100), 1) );
28708 #if SQLITE_OS_WINCE
28709 #define WINCE_DELETION_ATTEMPTS 3
28710   winceDestroyLock(pFile);
28711   if( pFile->zDeleteOnClose ){
28712     int cnt = 0;
28713     while(
28714            DeleteFileW(pFile->zDeleteOnClose)==0
28715         && GetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff 
28716         && cnt++ < WINCE_DELETION_ATTEMPTS
28717     ){
28718        Sleep(100);  /* Wait a little before trying again */
28719     }
28720     free(pFile->zDeleteOnClose);
28721   }
28722 #endif
28723   OpenCounter(-1);
28724   return rc ? SQLITE_OK : SQLITE_IOERR;
28725 }
28726
28727 /*
28728 ** Some microsoft compilers lack this definition.
28729 */
28730 #ifndef INVALID_SET_FILE_POINTER
28731 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
28732 #endif
28733
28734 /*
28735 ** Read data from a file into a buffer.  Return SQLITE_OK if all
28736 ** bytes were read successfully and SQLITE_IOERR if anything goes
28737 ** wrong.
28738 */
28739 static int winRead(
28740   sqlite3_file *id,          /* File to read from */
28741   void *pBuf,                /* Write content into this buffer */
28742   int amt,                   /* Number of bytes to read */
28743   sqlite3_int64 offset       /* Begin reading at this offset */
28744 ){
28745   LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
28746   LONG lowerBits = (LONG)(offset & 0xffffffff);
28747   DWORD rc;
28748   winFile *pFile = (winFile*)id;
28749   DWORD error;
28750   DWORD got;
28751
28752   assert( id!=0 );
28753   SimulateIOError(return SQLITE_IOERR_READ);
28754   OSTRACE3("READ %d lock=%d\n", pFile->h, pFile->locktype);
28755   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
28756   if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
28757     pFile->lastErrno = error;
28758     return SQLITE_FULL;
28759   }
28760   if( !ReadFile(pFile->h, pBuf, amt, &got, 0) ){
28761     pFile->lastErrno = GetLastError();
28762     return SQLITE_IOERR_READ;
28763   }
28764   if( got==(DWORD)amt ){
28765     return SQLITE_OK;
28766   }else{
28767     /* Unread parts of the buffer must be zero-filled */
28768     memset(&((char*)pBuf)[got], 0, amt-got);
28769     return SQLITE_IOERR_SHORT_READ;
28770   }
28771 }
28772
28773 /*
28774 ** Write data from a buffer into a file.  Return SQLITE_OK on success
28775 ** or some other error code on failure.
28776 */
28777 static int winWrite(
28778   sqlite3_file *id,         /* File to write into */
28779   const void *pBuf,         /* The bytes to be written */
28780   int amt,                  /* Number of bytes to write */
28781   sqlite3_int64 offset      /* Offset into the file to begin writing at */
28782 ){
28783   LONG upperBits = (LONG)((offset>>32) & 0x7fffffff);
28784   LONG lowerBits = (LONG)(offset & 0xffffffff);
28785   DWORD rc;
28786   winFile *pFile = (winFile*)id;
28787   DWORD error;
28788   DWORD wrote = 0;
28789
28790   assert( id!=0 );
28791   SimulateIOError(return SQLITE_IOERR_WRITE);
28792   SimulateDiskfullError(return SQLITE_FULL);
28793   OSTRACE3("WRITE %d lock=%d\n", pFile->h, pFile->locktype);
28794   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
28795   if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
28796     pFile->lastErrno = error;
28797     return SQLITE_FULL;
28798   }
28799   assert( amt>0 );
28800   while(
28801      amt>0
28802      && (rc = WriteFile(pFile->h, pBuf, amt, &wrote, 0))!=0
28803      && wrote>0
28804   ){
28805     amt -= wrote;
28806     pBuf = &((char*)pBuf)[wrote];
28807   }
28808   if( !rc || amt>(int)wrote ){
28809     pFile->lastErrno = GetLastError();
28810     return SQLITE_FULL;
28811   }
28812   return SQLITE_OK;
28813 }
28814
28815 /*
28816 ** Truncate an open file to a specified size
28817 */
28818 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
28819   LONG upperBits = (LONG)((nByte>>32) & 0x7fffffff);
28820   LONG lowerBits = (LONG)(nByte & 0xffffffff);
28821   DWORD rc;
28822   winFile *pFile = (winFile*)id;
28823   DWORD error;
28824
28825   assert( id!=0 );
28826   OSTRACE3("TRUNCATE %d %lld\n", pFile->h, nByte);
28827   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
28828   rc = SetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
28829   if( rc==INVALID_SET_FILE_POINTER && (error=GetLastError())!=NO_ERROR ){
28830     pFile->lastErrno = error;
28831     return SQLITE_IOERR_TRUNCATE;
28832   }
28833   /* SetEndOfFile will fail if nByte is negative */
28834   if( !SetEndOfFile(pFile->h) ){
28835     pFile->lastErrno = GetLastError();
28836     return SQLITE_IOERR_TRUNCATE;
28837   }
28838   return SQLITE_OK;
28839 }
28840
28841 #ifdef SQLITE_TEST
28842 /*
28843 ** Count the number of fullsyncs and normal syncs.  This is used to test
28844 ** that syncs and fullsyncs are occuring at the right times.
28845 */
28846 SQLITE_API int sqlite3_sync_count = 0;
28847 SQLITE_API int sqlite3_fullsync_count = 0;
28848 #endif
28849
28850 /*
28851 ** Make sure all writes to a particular file are committed to disk.
28852 */
28853 static int winSync(sqlite3_file *id, int flags){
28854 #ifndef SQLITE_NO_SYNC
28855   winFile *pFile = (winFile*)id;
28856
28857   assert( id!=0 );
28858   OSTRACE3("SYNC %d lock=%d\n", pFile->h, pFile->locktype);
28859 #else
28860   UNUSED_PARAMETER(id);
28861 #endif
28862 #ifndef SQLITE_TEST
28863   UNUSED_PARAMETER(flags);
28864 #else
28865   if( flags & SQLITE_SYNC_FULL ){
28866     sqlite3_fullsync_count++;
28867   }
28868   sqlite3_sync_count++;
28869 #endif
28870   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
28871   ** no-op
28872   */
28873 #ifdef SQLITE_NO_SYNC
28874     return SQLITE_OK;
28875 #else
28876   if( FlushFileBuffers(pFile->h) ){
28877     return SQLITE_OK;
28878   }else{
28879     pFile->lastErrno = GetLastError();
28880     return SQLITE_IOERR;
28881   }
28882 #endif
28883 }
28884
28885 /*
28886 ** Determine the current size of a file in bytes
28887 */
28888 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
28889   DWORD upperBits;
28890   DWORD lowerBits;
28891   winFile *pFile = (winFile*)id;
28892   DWORD error;
28893
28894   assert( id!=0 );
28895   SimulateIOError(return SQLITE_IOERR_FSTAT);
28896   lowerBits = GetFileSize(pFile->h, &upperBits);
28897   if(   (lowerBits == INVALID_FILE_SIZE)
28898      && ((error = GetLastError()) != NO_ERROR) )
28899   {
28900     pFile->lastErrno = error;
28901     return SQLITE_IOERR_FSTAT;
28902   }
28903   *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
28904   return SQLITE_OK;
28905 }
28906
28907 /*
28908 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
28909 */
28910 #ifndef LOCKFILE_FAIL_IMMEDIATELY
28911 # define LOCKFILE_FAIL_IMMEDIATELY 1
28912 #endif
28913
28914 /*
28915 ** Acquire a reader lock.
28916 ** Different API routines are called depending on whether or not this
28917 ** is Win95 or WinNT.
28918 */
28919 static int getReadLock(winFile *pFile){
28920   int res;
28921   if( isNT() ){
28922     OVERLAPPED ovlp;
28923     ovlp.Offset = SHARED_FIRST;
28924     ovlp.OffsetHigh = 0;
28925     ovlp.hEvent = 0;
28926     res = LockFileEx(pFile->h, LOCKFILE_FAIL_IMMEDIATELY,
28927                      0, SHARED_SIZE, 0, &ovlp);
28928 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
28929 */
28930 #if SQLITE_OS_WINCE==0
28931   }else{
28932     int lk;
28933     sqlite3_randomness(sizeof(lk), &lk);
28934     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
28935     res = LockFile(pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
28936 #endif
28937   }
28938   if( res == 0 ){
28939     pFile->lastErrno = GetLastError();
28940   }
28941   return res;
28942 }
28943
28944 /*
28945 ** Undo a readlock
28946 */
28947 static int unlockReadLock(winFile *pFile){
28948   int res;
28949   if( isNT() ){
28950     res = UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
28951 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
28952 */
28953 #if SQLITE_OS_WINCE==0
28954   }else{
28955     res = UnlockFile(pFile->h, SHARED_FIRST + pFile->sharedLockByte, 0, 1, 0);
28956 #endif
28957   }
28958   if( res == 0 ){
28959     pFile->lastErrno = GetLastError();
28960   }
28961   return res;
28962 }
28963
28964 /*
28965 ** Lock the file with the lock specified by parameter locktype - one
28966 ** of the following:
28967 **
28968 **     (1) SHARED_LOCK
28969 **     (2) RESERVED_LOCK
28970 **     (3) PENDING_LOCK
28971 **     (4) EXCLUSIVE_LOCK
28972 **
28973 ** Sometimes when requesting one lock state, additional lock states
28974 ** are inserted in between.  The locking might fail on one of the later
28975 ** transitions leaving the lock state different from what it started but
28976 ** still short of its goal.  The following chart shows the allowed
28977 ** transitions and the inserted intermediate states:
28978 **
28979 **    UNLOCKED -> SHARED
28980 **    SHARED -> RESERVED
28981 **    SHARED -> (PENDING) -> EXCLUSIVE
28982 **    RESERVED -> (PENDING) -> EXCLUSIVE
28983 **    PENDING -> EXCLUSIVE
28984 **
28985 ** This routine will only increase a lock.  The winUnlock() routine
28986 ** erases all locks at once and returns us immediately to locking level 0.
28987 ** It is not possible to lower the locking level one step at a time.  You
28988 ** must go straight to locking level 0.
28989 */
28990 static int winLock(sqlite3_file *id, int locktype){
28991   int rc = SQLITE_OK;    /* Return code from subroutines */
28992   int res = 1;           /* Result of a windows lock call */
28993   int newLocktype;       /* Set pFile->locktype to this value before exiting */
28994   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
28995   winFile *pFile = (winFile*)id;
28996   DWORD error = NO_ERROR;
28997
28998   assert( id!=0 );
28999   OSTRACE5("LOCK %d %d was %d(%d)\n",
29000           pFile->h, locktype, pFile->locktype, pFile->sharedLockByte);
29001
29002   /* If there is already a lock of this type or more restrictive on the
29003   ** OsFile, do nothing. Don't use the end_lock: exit path, as
29004   ** sqlite3OsEnterMutex() hasn't been called yet.
29005   */
29006   if( pFile->locktype>=locktype ){
29007     return SQLITE_OK;
29008   }
29009
29010   /* Make sure the locking sequence is correct
29011   */
29012   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
29013   assert( locktype!=PENDING_LOCK );
29014   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
29015
29016   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
29017   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
29018   ** the PENDING_LOCK byte is temporary.
29019   */
29020   newLocktype = pFile->locktype;
29021   if(   (pFile->locktype==NO_LOCK)
29022      || (   (locktype==EXCLUSIVE_LOCK)
29023          && (pFile->locktype==RESERVED_LOCK))
29024   ){
29025     int cnt = 3;
29026     while( cnt-->0 && (res = LockFile(pFile->h, PENDING_BYTE, 0, 1, 0))==0 ){
29027       /* Try 3 times to get the pending lock.  The pending lock might be
29028       ** held by another reader process who will release it momentarily.
29029       */
29030       OSTRACE2("could not get a PENDING lock. cnt=%d\n", cnt);
29031       Sleep(1);
29032     }
29033     gotPendingLock = res;
29034     if( !res ){
29035       error = GetLastError();
29036     }
29037   }
29038
29039   /* Acquire a shared lock
29040   */
29041   if( locktype==SHARED_LOCK && res ){
29042     assert( pFile->locktype==NO_LOCK );
29043     res = getReadLock(pFile);
29044     if( res ){
29045       newLocktype = SHARED_LOCK;
29046     }else{
29047       error = GetLastError();
29048     }
29049   }
29050
29051   /* Acquire a RESERVED lock
29052   */
29053   if( locktype==RESERVED_LOCK && res ){
29054     assert( pFile->locktype==SHARED_LOCK );
29055     res = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
29056     if( res ){
29057       newLocktype = RESERVED_LOCK;
29058     }else{
29059       error = GetLastError();
29060     }
29061   }
29062
29063   /* Acquire a PENDING lock
29064   */
29065   if( locktype==EXCLUSIVE_LOCK && res ){
29066     newLocktype = PENDING_LOCK;
29067     gotPendingLock = 0;
29068   }
29069
29070   /* Acquire an EXCLUSIVE lock
29071   */
29072   if( locktype==EXCLUSIVE_LOCK && res ){
29073     assert( pFile->locktype>=SHARED_LOCK );
29074     res = unlockReadLock(pFile);
29075     OSTRACE2("unreadlock = %d\n", res);
29076     res = LockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
29077     if( res ){
29078       newLocktype = EXCLUSIVE_LOCK;
29079     }else{
29080       error = GetLastError();
29081       OSTRACE2("error-code = %d\n", error);
29082       getReadLock(pFile);
29083     }
29084   }
29085
29086   /* If we are holding a PENDING lock that ought to be released, then
29087   ** release it now.
29088   */
29089   if( gotPendingLock && locktype==SHARED_LOCK ){
29090     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
29091   }
29092
29093   /* Update the state of the lock has held in the file descriptor then
29094   ** return the appropriate result code.
29095   */
29096   if( res ){
29097     rc = SQLITE_OK;
29098   }else{
29099     OSTRACE4("LOCK FAILED %d trying for %d but got %d\n", pFile->h,
29100            locktype, newLocktype);
29101     pFile->lastErrno = error;
29102     rc = SQLITE_BUSY;
29103   }
29104   pFile->locktype = (u8)newLocktype;
29105   return rc;
29106 }
29107
29108 /*
29109 ** This routine checks if there is a RESERVED lock held on the specified
29110 ** file by this or any other process. If such a lock is held, return
29111 ** non-zero, otherwise zero.
29112 */
29113 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
29114   int rc;
29115   winFile *pFile = (winFile*)id;
29116
29117   assert( id!=0 );
29118   if( pFile->locktype>=RESERVED_LOCK ){
29119     rc = 1;
29120     OSTRACE3("TEST WR-LOCK %d %d (local)\n", pFile->h, rc);
29121   }else{
29122     rc = LockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
29123     if( rc ){
29124       UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
29125     }
29126     rc = !rc;
29127     OSTRACE3("TEST WR-LOCK %d %d (remote)\n", pFile->h, rc);
29128   }
29129   *pResOut = rc;
29130   return SQLITE_OK;
29131 }
29132
29133 /*
29134 ** Lower the locking level on file descriptor id to locktype.  locktype
29135 ** must be either NO_LOCK or SHARED_LOCK.
29136 **
29137 ** If the locking level of the file descriptor is already at or below
29138 ** the requested locking level, this routine is a no-op.
29139 **
29140 ** It is not possible for this routine to fail if the second argument
29141 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
29142 ** might return SQLITE_IOERR;
29143 */
29144 static int winUnlock(sqlite3_file *id, int locktype){
29145   int type;
29146   winFile *pFile = (winFile*)id;
29147   int rc = SQLITE_OK;
29148   assert( pFile!=0 );
29149   assert( locktype<=SHARED_LOCK );
29150   OSTRACE5("UNLOCK %d to %d was %d(%d)\n", pFile->h, locktype,
29151           pFile->locktype, pFile->sharedLockByte);
29152   type = pFile->locktype;
29153   if( type>=EXCLUSIVE_LOCK ){
29154     UnlockFile(pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
29155     if( locktype==SHARED_LOCK && !getReadLock(pFile) ){
29156       /* This should never happen.  We should always be able to
29157       ** reacquire the read lock */
29158       rc = SQLITE_IOERR_UNLOCK;
29159     }
29160   }
29161   if( type>=RESERVED_LOCK ){
29162     UnlockFile(pFile->h, RESERVED_BYTE, 0, 1, 0);
29163   }
29164   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
29165     unlockReadLock(pFile);
29166   }
29167   if( type>=PENDING_LOCK ){
29168     UnlockFile(pFile->h, PENDING_BYTE, 0, 1, 0);
29169   }
29170   pFile->locktype = (u8)locktype;
29171   return rc;
29172 }
29173
29174 /*
29175 ** Control and query of the open file handle.
29176 */
29177 static int winFileControl(sqlite3_file *id, int op, void *pArg){
29178   switch( op ){
29179     case SQLITE_FCNTL_LOCKSTATE: {
29180       *(int*)pArg = ((winFile*)id)->locktype;
29181       return SQLITE_OK;
29182     }
29183     case SQLITE_LAST_ERRNO: {
29184       *(int*)pArg = (int)((winFile*)id)->lastErrno;
29185       return SQLITE_OK;
29186     }
29187   }
29188   return SQLITE_ERROR;
29189 }
29190
29191 /*
29192 ** Return the sector size in bytes of the underlying block device for
29193 ** the specified file. This is almost always 512 bytes, but may be
29194 ** larger for some devices.
29195 **
29196 ** SQLite code assumes this function cannot fail. It also assumes that
29197 ** if two files are created in the same file-system directory (i.e.
29198 ** a database and its journal file) that the sector size will be the
29199 ** same for both.
29200 */
29201 static int winSectorSize(sqlite3_file *id){
29202   assert( id!=0 );
29203   return (int)(((winFile*)id)->sectorSize);
29204 }
29205
29206 /*
29207 ** Return a vector of device characteristics.
29208 */
29209 static int winDeviceCharacteristics(sqlite3_file *id){
29210   UNUSED_PARAMETER(id);
29211   return 0;
29212 }
29213
29214 /*
29215 ** This vector defines all the methods that can operate on an
29216 ** sqlite3_file for win32.
29217 */
29218 static const sqlite3_io_methods winIoMethod = {
29219   1,                        /* iVersion */
29220   winClose,
29221   winRead,
29222   winWrite,
29223   winTruncate,
29224   winSync,
29225   winFileSize,
29226   winLock,
29227   winUnlock,
29228   winCheckReservedLock,
29229   winFileControl,
29230   winSectorSize,
29231   winDeviceCharacteristics
29232 };
29233
29234 /***************************************************************************
29235 ** Here ends the I/O methods that form the sqlite3_io_methods object.
29236 **
29237 ** The next block of code implements the VFS methods.
29238 ****************************************************************************/
29239
29240 /*
29241 ** Convert a UTF-8 filename into whatever form the underlying
29242 ** operating system wants filenames in.  Space to hold the result
29243 ** is obtained from malloc and must be freed by the calling
29244 ** function.
29245 */
29246 static void *convertUtf8Filename(const char *zFilename){
29247   void *zConverted = 0;
29248   if( isNT() ){
29249     zConverted = utf8ToUnicode(zFilename);
29250 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
29251 */
29252 #if SQLITE_OS_WINCE==0
29253   }else{
29254     zConverted = utf8ToMbcs(zFilename);
29255 #endif
29256   }
29257   /* caller will handle out of memory */
29258   return zConverted;
29259 }
29260
29261 /*
29262 ** Create a temporary file name in zBuf.  zBuf must be big enough to
29263 ** hold at pVfs->mxPathname characters.
29264 */
29265 static int getTempname(int nBuf, char *zBuf){
29266   static char zChars[] =
29267     "abcdefghijklmnopqrstuvwxyz"
29268     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
29269     "0123456789";
29270   size_t i, j;
29271   char zTempPath[MAX_PATH+1];
29272   if( sqlite3_temp_directory ){
29273     sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", sqlite3_temp_directory);
29274   }else if( isNT() ){
29275     char *zMulti;
29276     WCHAR zWidePath[MAX_PATH];
29277     GetTempPathW(MAX_PATH-30, zWidePath);
29278     zMulti = unicodeToUtf8(zWidePath);
29279     if( zMulti ){
29280       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zMulti);
29281       free(zMulti);
29282     }else{
29283       return SQLITE_NOMEM;
29284     }
29285 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
29286 ** Since the ASCII version of these Windows API do not exist for WINCE,
29287 ** it's important to not reference them for WINCE builds.
29288 */
29289 #if SQLITE_OS_WINCE==0
29290   }else{
29291     char *zUtf8;
29292     char zMbcsPath[MAX_PATH];
29293     GetTempPathA(MAX_PATH-30, zMbcsPath);
29294     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
29295     if( zUtf8 ){
29296       sqlite3_snprintf(MAX_PATH-30, zTempPath, "%s", zUtf8);
29297       free(zUtf8);
29298     }else{
29299       return SQLITE_NOMEM;
29300     }
29301 #endif
29302   }
29303   for(i=sqlite3Strlen30(zTempPath); i>0 && zTempPath[i-1]=='\\'; i--){}
29304   zTempPath[i] = 0;
29305   sqlite3_snprintf(nBuf-30, zBuf,
29306                    "%s\\"SQLITE_TEMP_FILE_PREFIX, zTempPath);
29307   j = sqlite3Strlen30(zBuf);
29308   sqlite3_randomness(20, &zBuf[j]);
29309   for(i=0; i<20; i++, j++){
29310     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
29311   }
29312   zBuf[j] = 0;
29313   OSTRACE2("TEMP FILENAME: %s\n", zBuf);
29314   return SQLITE_OK; 
29315 }
29316
29317 /*
29318 ** The return value of getLastErrorMsg
29319 ** is zero if the error message fits in the buffer, or non-zero
29320 ** otherwise (if the message was truncated).
29321 */
29322 static int getLastErrorMsg(int nBuf, char *zBuf){
29323   /* FormatMessage returns 0 on failure.  Otherwise it
29324   ** returns the number of TCHARs written to the output
29325   ** buffer, excluding the terminating null char.
29326   */
29327   DWORD error = GetLastError();
29328   DWORD dwLen = 0;
29329   char *zOut = 0;
29330
29331   if( isNT() ){
29332     WCHAR *zTempWide = NULL;
29333     dwLen = FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
29334                            NULL,
29335                            error,
29336                            0,
29337                            (LPWSTR) &zTempWide,
29338                            0,
29339                            0);
29340     if( dwLen > 0 ){
29341       /* allocate a buffer and convert to UTF8 */
29342       zOut = unicodeToUtf8(zTempWide);
29343       /* free the system buffer allocated by FormatMessage */
29344       LocalFree(zTempWide);
29345     }
29346 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
29347 ** Since the ASCII version of these Windows API do not exist for WINCE,
29348 ** it's important to not reference them for WINCE builds.
29349 */
29350 #if SQLITE_OS_WINCE==0
29351   }else{
29352     char *zTemp = NULL;
29353     dwLen = FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
29354                            NULL,
29355                            error,
29356                            0,
29357                            (LPSTR) &zTemp,
29358                            0,
29359                            0);
29360     if( dwLen > 0 ){
29361       /* allocate a buffer and convert to UTF8 */
29362       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
29363       /* free the system buffer allocated by FormatMessage */
29364       LocalFree(zTemp);
29365     }
29366 #endif
29367   }
29368   if( 0 == dwLen ){
29369     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%x (%u)", error, error);
29370   }else{
29371     /* copy a maximum of nBuf chars to output buffer */
29372     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
29373     /* free the UTF8 buffer */
29374     free(zOut);
29375   }
29376   return 0;
29377 }
29378
29379 /*
29380 ** Open a file.
29381 */
29382 static int winOpen(
29383   sqlite3_vfs *pVfs,        /* Not used */
29384   const char *zName,        /* Name of the file (UTF-8) */
29385   sqlite3_file *id,         /* Write the SQLite file handle here */
29386   int flags,                /* Open mode flags */
29387   int *pOutFlags            /* Status return flags */
29388 ){
29389   HANDLE h;
29390   DWORD dwDesiredAccess;
29391   DWORD dwShareMode;
29392   DWORD dwCreationDisposition;
29393   DWORD dwFlagsAndAttributes = 0;
29394 #if SQLITE_OS_WINCE
29395   int isTemp = 0;
29396 #endif
29397   winFile *pFile = (winFile*)id;
29398   void *zConverted;                 /* Filename in OS encoding */
29399   const char *zUtf8Name = zName;    /* Filename in UTF-8 encoding */
29400   char zTmpname[MAX_PATH+1];        /* Buffer used to create temp filename */
29401
29402   assert( id!=0 );
29403   UNUSED_PARAMETER(pVfs);
29404
29405   /* If the second argument to this function is NULL, generate a 
29406   ** temporary file name to use 
29407   */
29408   if( !zUtf8Name ){
29409     int rc = getTempname(MAX_PATH+1, zTmpname);
29410     if( rc!=SQLITE_OK ){
29411       return rc;
29412     }
29413     zUtf8Name = zTmpname;
29414   }
29415
29416   /* Convert the filename to the system encoding. */
29417   zConverted = convertUtf8Filename(zUtf8Name);
29418   if( zConverted==0 ){
29419     return SQLITE_NOMEM;
29420   }
29421
29422   if( flags & SQLITE_OPEN_READWRITE ){
29423     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
29424   }else{
29425     dwDesiredAccess = GENERIC_READ;
29426   }
29427   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is 
29428   ** created. SQLite doesn't use it to indicate "exclusive access" 
29429   ** as it is usually understood.
29430   */
29431   assert(!(flags & SQLITE_OPEN_EXCLUSIVE) || (flags & SQLITE_OPEN_CREATE));
29432   if( flags & SQLITE_OPEN_EXCLUSIVE ){
29433     /* Creates a new file, only if it does not already exist. */
29434     /* If the file exists, it fails. */
29435     dwCreationDisposition = CREATE_NEW;
29436   }else if( flags & SQLITE_OPEN_CREATE ){
29437     /* Open existing file, or create if it doesn't exist */
29438     dwCreationDisposition = OPEN_ALWAYS;
29439   }else{
29440     /* Opens a file, only if it exists. */
29441     dwCreationDisposition = OPEN_EXISTING;
29442   }
29443   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
29444   if( flags & SQLITE_OPEN_DELETEONCLOSE ){
29445 #if SQLITE_OS_WINCE
29446     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
29447     isTemp = 1;
29448 #else
29449     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
29450                                | FILE_ATTRIBUTE_HIDDEN
29451                                | FILE_FLAG_DELETE_ON_CLOSE;
29452 #endif
29453   }else{
29454     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
29455   }
29456   /* Reports from the internet are that performance is always
29457   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
29458 #if SQLITE_OS_WINCE
29459   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
29460 #endif
29461   if( isNT() ){
29462     h = CreateFileW((WCHAR*)zConverted,
29463        dwDesiredAccess,
29464        dwShareMode,
29465        NULL,
29466        dwCreationDisposition,
29467        dwFlagsAndAttributes,
29468        NULL
29469     );
29470 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
29471 ** Since the ASCII version of these Windows API do not exist for WINCE,
29472 ** it's important to not reference them for WINCE builds.
29473 */
29474 #if SQLITE_OS_WINCE==0
29475   }else{
29476     h = CreateFileA((char*)zConverted,
29477        dwDesiredAccess,
29478        dwShareMode,
29479        NULL,
29480        dwCreationDisposition,
29481        dwFlagsAndAttributes,
29482        NULL
29483     );
29484 #endif
29485   }
29486   if( h==INVALID_HANDLE_VALUE ){
29487     free(zConverted);
29488     if( flags & SQLITE_OPEN_READWRITE ){
29489       return winOpen(pVfs, zName, id, 
29490              ((flags|SQLITE_OPEN_READONLY)&~SQLITE_OPEN_READWRITE), pOutFlags);
29491     }else{
29492       return SQLITE_CANTOPEN_BKPT;
29493     }
29494   }
29495   if( pOutFlags ){
29496     if( flags & SQLITE_OPEN_READWRITE ){
29497       *pOutFlags = SQLITE_OPEN_READWRITE;
29498     }else{
29499       *pOutFlags = SQLITE_OPEN_READONLY;
29500     }
29501   }
29502   memset(pFile, 0, sizeof(*pFile));
29503   pFile->pMethod = &winIoMethod;
29504   pFile->h = h;
29505   pFile->lastErrno = NO_ERROR;
29506   pFile->sectorSize = getSectorSize(pVfs, zUtf8Name);
29507 #if SQLITE_OS_WINCE
29508   if( (flags & (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)) ==
29509                (SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_DB)
29510        && !winceCreateLock(zName, pFile)
29511   ){
29512     CloseHandle(h);
29513     free(zConverted);
29514     return SQLITE_CANTOPEN_BKPT;
29515   }
29516   if( isTemp ){
29517     pFile->zDeleteOnClose = zConverted;
29518   }else
29519 #endif
29520   {
29521     free(zConverted);
29522   }
29523   OpenCounter(+1);
29524   return SQLITE_OK;
29525 }
29526
29527 /*
29528 ** Delete the named file.
29529 **
29530 ** Note that windows does not allow a file to be deleted if some other
29531 ** process has it open.  Sometimes a virus scanner or indexing program
29532 ** will open a journal file shortly after it is created in order to do
29533 ** whatever it does.  While this other process is holding the
29534 ** file open, we will be unable to delete it.  To work around this
29535 ** problem, we delay 100 milliseconds and try to delete again.  Up
29536 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
29537 ** up and returning an error.
29538 */
29539 #define MX_DELETION_ATTEMPTS 5
29540 static int winDelete(
29541   sqlite3_vfs *pVfs,          /* Not used on win32 */
29542   const char *zFilename,      /* Name of file to delete */
29543   int syncDir                 /* Not used on win32 */
29544 ){
29545   int cnt = 0;
29546   DWORD rc;
29547   DWORD error = 0;
29548   void *zConverted = convertUtf8Filename(zFilename);
29549   UNUSED_PARAMETER(pVfs);
29550   UNUSED_PARAMETER(syncDir);
29551   if( zConverted==0 ){
29552     return SQLITE_NOMEM;
29553   }
29554   SimulateIOError(return SQLITE_IOERR_DELETE);
29555   if( isNT() ){
29556     do{
29557       DeleteFileW(zConverted);
29558     }while(   (   ((rc = GetFileAttributesW(zConverted)) != INVALID_FILE_ATTRIBUTES)
29559                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
29560            && (++cnt < MX_DELETION_ATTEMPTS)
29561            && (Sleep(100), 1) );
29562 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
29563 ** Since the ASCII version of these Windows API do not exist for WINCE,
29564 ** it's important to not reference them for WINCE builds.
29565 */
29566 #if SQLITE_OS_WINCE==0
29567   }else{
29568     do{
29569       DeleteFileA(zConverted);
29570     }while(   (   ((rc = GetFileAttributesA(zConverted)) != INVALID_FILE_ATTRIBUTES)
29571                || ((error = GetLastError()) == ERROR_ACCESS_DENIED))
29572            && (++cnt < MX_DELETION_ATTEMPTS)
29573            && (Sleep(100), 1) );
29574 #endif
29575   }
29576   free(zConverted);
29577   OSTRACE2("DELETE \"%s\"\n", zFilename);
29578   return (   (rc == INVALID_FILE_ATTRIBUTES) 
29579           && (error == ERROR_FILE_NOT_FOUND)) ? SQLITE_OK : SQLITE_IOERR_DELETE;
29580 }
29581
29582 /*
29583 ** Check the existance and status of a file.
29584 */
29585 static int winAccess(
29586   sqlite3_vfs *pVfs,         /* Not used on win32 */
29587   const char *zFilename,     /* Name of file to check */
29588   int flags,                 /* Type of test to make on this file */
29589   int *pResOut               /* OUT: Result */
29590 ){
29591   DWORD attr;
29592   int rc = 0;
29593   void *zConverted = convertUtf8Filename(zFilename);
29594   UNUSED_PARAMETER(pVfs);
29595   if( zConverted==0 ){
29596     return SQLITE_NOMEM;
29597   }
29598   if( isNT() ){
29599     attr = GetFileAttributesW((WCHAR*)zConverted);
29600 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
29601 ** Since the ASCII version of these Windows API do not exist for WINCE,
29602 ** it's important to not reference them for WINCE builds.
29603 */
29604 #if SQLITE_OS_WINCE==0
29605   }else{
29606     attr = GetFileAttributesA((char*)zConverted);
29607 #endif
29608   }
29609   free(zConverted);
29610   switch( flags ){
29611     case SQLITE_ACCESS_READ:
29612     case SQLITE_ACCESS_EXISTS:
29613       rc = attr!=INVALID_FILE_ATTRIBUTES;
29614       break;
29615     case SQLITE_ACCESS_READWRITE:
29616       rc = (attr & FILE_ATTRIBUTE_READONLY)==0;
29617       break;
29618     default:
29619       assert(!"Invalid flags argument");
29620   }
29621   *pResOut = rc;
29622   return SQLITE_OK;
29623 }
29624
29625
29626 /*
29627 ** Turn a relative pathname into a full pathname.  Write the full
29628 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
29629 ** bytes in size.
29630 */
29631 static int winFullPathname(
29632   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
29633   const char *zRelative,        /* Possibly relative input path */
29634   int nFull,                    /* Size of output buffer in bytes */
29635   char *zFull                   /* Output buffer */
29636 ){
29637   
29638 #if defined(__CYGWIN__)
29639   UNUSED_PARAMETER(nFull);
29640   cygwin_conv_to_full_win32_path(zRelative, zFull);
29641   return SQLITE_OK;
29642 #endif
29643
29644 #if SQLITE_OS_WINCE
29645   UNUSED_PARAMETER(nFull);
29646   /* WinCE has no concept of a relative pathname, or so I am told. */
29647   sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zRelative);
29648   return SQLITE_OK;
29649 #endif
29650
29651 #if !SQLITE_OS_WINCE && !defined(__CYGWIN__)
29652   int nByte;
29653   void *zConverted;
29654   char *zOut;
29655   UNUSED_PARAMETER(nFull);
29656   zConverted = convertUtf8Filename(zRelative);
29657   if( isNT() ){
29658     WCHAR *zTemp;
29659     nByte = GetFullPathNameW((WCHAR*)zConverted, 0, 0, 0) + 3;
29660     zTemp = malloc( nByte*sizeof(zTemp[0]) );
29661     if( zTemp==0 ){
29662       free(zConverted);
29663       return SQLITE_NOMEM;
29664     }
29665     GetFullPathNameW((WCHAR*)zConverted, nByte, zTemp, 0);
29666     free(zConverted);
29667     zOut = unicodeToUtf8(zTemp);
29668     free(zTemp);
29669 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
29670 ** Since the ASCII version of these Windows API do not exist for WINCE,
29671 ** it's important to not reference them for WINCE builds.
29672 */
29673 #if SQLITE_OS_WINCE==0
29674   }else{
29675     char *zTemp;
29676     nByte = GetFullPathNameA((char*)zConverted, 0, 0, 0) + 3;
29677     zTemp = malloc( nByte*sizeof(zTemp[0]) );
29678     if( zTemp==0 ){
29679       free(zConverted);
29680       return SQLITE_NOMEM;
29681     }
29682     GetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
29683     free(zConverted);
29684     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
29685     free(zTemp);
29686 #endif
29687   }
29688   if( zOut ){
29689     sqlite3_snprintf(pVfs->mxPathname, zFull, "%s", zOut);
29690     free(zOut);
29691     return SQLITE_OK;
29692   }else{
29693     return SQLITE_NOMEM;
29694   }
29695 #endif
29696 }
29697
29698 /*
29699 ** Get the sector size of the device used to store
29700 ** file.
29701 */
29702 static int getSectorSize(
29703     sqlite3_vfs *pVfs,
29704     const char *zRelative     /* UTF-8 file name */
29705 ){
29706   DWORD bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
29707   /* GetDiskFreeSpace is not supported under WINCE */
29708 #if SQLITE_OS_WINCE
29709   UNUSED_PARAMETER(pVfs);
29710   UNUSED_PARAMETER(zRelative);
29711 #else
29712   char zFullpath[MAX_PATH+1];
29713   int rc;
29714   DWORD dwRet = 0;
29715   DWORD dwDummy;
29716
29717   /*
29718   ** We need to get the full path name of the file
29719   ** to get the drive letter to look up the sector
29720   ** size.
29721   */
29722   rc = winFullPathname(pVfs, zRelative, MAX_PATH, zFullpath);
29723   if( rc == SQLITE_OK )
29724   {
29725     void *zConverted = convertUtf8Filename(zFullpath);
29726     if( zConverted ){
29727       if( isNT() ){
29728         /* trim path to just drive reference */
29729         WCHAR *p = zConverted;
29730         for(;*p;p++){
29731           if( *p == '\\' ){
29732             *p = '\0';
29733             break;
29734           }
29735         }
29736         dwRet = GetDiskFreeSpaceW((WCHAR*)zConverted,
29737                                   &dwDummy,
29738                                   &bytesPerSector,
29739                                   &dwDummy,
29740                                   &dwDummy);
29741       }else{
29742         /* trim path to just drive reference */
29743         char *p = (char *)zConverted;
29744         for(;*p;p++){
29745           if( *p == '\\' ){
29746             *p = '\0';
29747             break;
29748           }
29749         }
29750         dwRet = GetDiskFreeSpaceA((char*)zConverted,
29751                                   &dwDummy,
29752                                   &bytesPerSector,
29753                                   &dwDummy,
29754                                   &dwDummy);
29755       }
29756       free(zConverted);
29757     }
29758     if( !dwRet ){
29759       bytesPerSector = SQLITE_DEFAULT_SECTOR_SIZE;
29760     }
29761   }
29762 #endif
29763   return (int) bytesPerSector; 
29764 }
29765
29766 #ifndef SQLITE_OMIT_LOAD_EXTENSION
29767 /*
29768 ** Interfaces for opening a shared library, finding entry points
29769 ** within the shared library, and closing the shared library.
29770 */
29771 /*
29772 ** Interfaces for opening a shared library, finding entry points
29773 ** within the shared library, and closing the shared library.
29774 */
29775 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
29776   HANDLE h;
29777   void *zConverted = convertUtf8Filename(zFilename);
29778   UNUSED_PARAMETER(pVfs);
29779   if( zConverted==0 ){
29780     return 0;
29781   }
29782   if( isNT() ){
29783     h = LoadLibraryW((WCHAR*)zConverted);
29784 /* isNT() is 1 if SQLITE_OS_WINCE==1, so this else is never executed. 
29785 ** Since the ASCII version of these Windows API do not exist for WINCE,
29786 ** it's important to not reference them for WINCE builds.
29787 */
29788 #if SQLITE_OS_WINCE==0
29789   }else{
29790     h = LoadLibraryA((char*)zConverted);
29791 #endif
29792   }
29793   free(zConverted);
29794   return (void*)h;
29795 }
29796 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
29797   UNUSED_PARAMETER(pVfs);
29798   getLastErrorMsg(nBuf, zBufOut);
29799 }
29800 void (*winDlSym(sqlite3_vfs *pVfs, void *pHandle, const char *zSymbol))(void){
29801   UNUSED_PARAMETER(pVfs);
29802 #if SQLITE_OS_WINCE
29803   /* The GetProcAddressA() routine is only available on wince. */
29804   return (void(*)(void))GetProcAddressA((HANDLE)pHandle, zSymbol);
29805 #else
29806   /* All other windows platforms expect GetProcAddress() to take
29807   ** an Ansi string regardless of the _UNICODE setting */
29808   return (void(*)(void))GetProcAddress((HANDLE)pHandle, zSymbol);
29809 #endif
29810 }
29811 void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
29812   UNUSED_PARAMETER(pVfs);
29813   FreeLibrary((HANDLE)pHandle);
29814 }
29815 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
29816   #define winDlOpen  0
29817   #define winDlError 0
29818   #define winDlSym   0
29819   #define winDlClose 0
29820 #endif
29821
29822
29823 /*
29824 ** Write up to nBuf bytes of randomness into zBuf.
29825 */
29826 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
29827   int n = 0;
29828   UNUSED_PARAMETER(pVfs);
29829 #if defined(SQLITE_TEST)
29830   n = nBuf;
29831   memset(zBuf, 0, nBuf);
29832 #else
29833   if( sizeof(SYSTEMTIME)<=nBuf-n ){
29834     SYSTEMTIME x;
29835     GetSystemTime(&x);
29836     memcpy(&zBuf[n], &x, sizeof(x));
29837     n += sizeof(x);
29838   }
29839   if( sizeof(DWORD)<=nBuf-n ){
29840     DWORD pid = GetCurrentProcessId();
29841     memcpy(&zBuf[n], &pid, sizeof(pid));
29842     n += sizeof(pid);
29843   }
29844   if( sizeof(DWORD)<=nBuf-n ){
29845     DWORD cnt = GetTickCount();
29846     memcpy(&zBuf[n], &cnt, sizeof(cnt));
29847     n += sizeof(cnt);
29848   }
29849   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
29850     LARGE_INTEGER i;
29851     QueryPerformanceCounter(&i);
29852     memcpy(&zBuf[n], &i, sizeof(i));
29853     n += sizeof(i);
29854   }
29855 #endif
29856   return n;
29857 }
29858
29859
29860 /*
29861 ** Sleep for a little while.  Return the amount of time slept.
29862 */
29863 static int winSleep(sqlite3_vfs *pVfs, int microsec){
29864   Sleep((microsec+999)/1000);
29865   UNUSED_PARAMETER(pVfs);
29866   return ((microsec+999)/1000)*1000;
29867 }
29868
29869 /*
29870 ** The following variable, if set to a non-zero value, becomes the result
29871 ** returned from sqlite3OsCurrentTime().  This is used for testing.
29872 */
29873 #ifdef SQLITE_TEST
29874 SQLITE_API int sqlite3_current_time = 0;
29875 #endif
29876
29877 /*
29878 ** Find the current time (in Universal Coordinated Time).  Write the
29879 ** current time and date as a Julian Day number into *prNow and
29880 ** return 0.  Return 1 if the time and date cannot be found.
29881 */
29882 int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
29883   FILETIME ft;
29884   /* FILETIME structure is a 64-bit value representing the number of 
29885      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5). 
29886   */
29887   sqlite3_int64 timeW;   /* Whole days */
29888   sqlite3_int64 timeF;   /* Fractional Days */
29889
29890   /* Number of 100-nanosecond intervals in a single day */
29891   static const sqlite3_int64 ntuPerDay = 
29892       10000000*(sqlite3_int64)86400;
29893
29894   /* Number of 100-nanosecond intervals in half of a day */
29895   static const sqlite3_int64 ntuPerHalfDay = 
29896       10000000*(sqlite3_int64)43200;
29897
29898   /* 2^32 - to avoid use of LL and warnings in gcc */
29899   static const sqlite3_int64 max32BitValue = 
29900       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 + (sqlite3_int64)294967296;
29901
29902 #if SQLITE_OS_WINCE
29903   SYSTEMTIME time;
29904   GetSystemTime(&time);
29905   /* if SystemTimeToFileTime() fails, it returns zero. */
29906   if (!SystemTimeToFileTime(&time,&ft)){
29907     return 1;
29908   }
29909 #else
29910   GetSystemTimeAsFileTime( &ft );
29911 #endif
29912   UNUSED_PARAMETER(pVfs);
29913   timeW = (((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) + (sqlite3_int64)ft.dwLowDateTime;
29914   timeF = timeW % ntuPerDay;          /* fractional days (100-nanoseconds) */
29915   timeW = timeW / ntuPerDay;          /* whole days */
29916   timeW = timeW + 2305813;            /* add whole days (from 2305813.5) */
29917   timeF = timeF + ntuPerHalfDay;      /* add half a day (from 2305813.5) */
29918   timeW = timeW + (timeF/ntuPerDay);  /* add whole day if half day made one */
29919   timeF = timeF % ntuPerDay;          /* compute new fractional days */
29920   *prNow = (double)timeW + ((double)timeF / (double)ntuPerDay);
29921 #ifdef SQLITE_TEST
29922   if( sqlite3_current_time ){
29923     *prNow = ((double)sqlite3_current_time + (double)43200) / (double)86400 + (double)2440587;
29924   }
29925 #endif
29926   return 0;
29927 }
29928
29929 /*
29930 ** The idea is that this function works like a combination of
29931 ** GetLastError() and FormatMessage() on windows (or errno and
29932 ** strerror_r() on unix). After an error is returned by an OS
29933 ** function, SQLite calls this function with zBuf pointing to
29934 ** a buffer of nBuf bytes. The OS layer should populate the
29935 ** buffer with a nul-terminated UTF-8 encoded error message
29936 ** describing the last IO error to have occurred within the calling
29937 ** thread.
29938 **
29939 ** If the error message is too large for the supplied buffer,
29940 ** it should be truncated. The return value of xGetLastError
29941 ** is zero if the error message fits in the buffer, or non-zero
29942 ** otherwise (if the message was truncated). If non-zero is returned,
29943 ** then it is not necessary to include the nul-terminator character
29944 ** in the output buffer.
29945 **
29946 ** Not supplying an error message will have no adverse effect
29947 ** on SQLite. It is fine to have an implementation that never
29948 ** returns an error message:
29949 **
29950 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
29951 **     assert(zBuf[0]=='\0');
29952 **     return 0;
29953 **   }
29954 **
29955 ** However if an error message is supplied, it will be incorporated
29956 ** by sqlite into the error message available to the user using
29957 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
29958 */
29959 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
29960   UNUSED_PARAMETER(pVfs);
29961   return getLastErrorMsg(nBuf, zBuf);
29962 }
29963
29964 /*
29965 ** Initialize and deinitialize the operating system interface.
29966 */
29967 SQLITE_API int sqlite3_os_init(void){
29968   static sqlite3_vfs winVfs = {
29969     1,                 /* iVersion */
29970     sizeof(winFile),   /* szOsFile */
29971     MAX_PATH,          /* mxPathname */
29972     0,                 /* pNext */
29973     "win32",           /* zName */
29974     0,                 /* pAppData */
29975  
29976     winOpen,           /* xOpen */
29977     winDelete,         /* xDelete */
29978     winAccess,         /* xAccess */
29979     winFullPathname,   /* xFullPathname */
29980     winDlOpen,         /* xDlOpen */
29981     winDlError,        /* xDlError */
29982     winDlSym,          /* xDlSym */
29983     winDlClose,        /* xDlClose */
29984     winRandomness,     /* xRandomness */
29985     winSleep,          /* xSleep */
29986     winCurrentTime,    /* xCurrentTime */
29987     winGetLastError    /* xGetLastError */
29988   };
29989
29990   sqlite3_vfs_register(&winVfs, 1);
29991   return SQLITE_OK; 
29992 }
29993 SQLITE_API int sqlite3_os_end(void){ 
29994   return SQLITE_OK;
29995 }
29996
29997 #endif /* SQLITE_OS_WIN */
29998
29999 /************** End of os_win.c **********************************************/
30000 /************** Begin file bitvec.c ******************************************/
30001 /*
30002 ** 2008 February 16
30003 **
30004 ** The author disclaims copyright to this source code.  In place of
30005 ** a legal notice, here is a blessing:
30006 **
30007 **    May you do good and not evil.
30008 **    May you find forgiveness for yourself and forgive others.
30009 **    May you share freely, never taking more than you give.
30010 **
30011 *************************************************************************
30012 ** This file implements an object that represents a fixed-length
30013 ** bitmap.  Bits are numbered starting with 1.
30014 **
30015 ** A bitmap is used to record which pages of a database file have been
30016 ** journalled during a transaction, or which pages have the "dont-write"
30017 ** property.  Usually only a few pages are meet either condition.
30018 ** So the bitmap is usually sparse and has low cardinality.
30019 ** But sometimes (for example when during a DROP of a large table) most
30020 ** or all of the pages in a database can get journalled.  In those cases, 
30021 ** the bitmap becomes dense with high cardinality.  The algorithm needs 
30022 ** to handle both cases well.
30023 **
30024 ** The size of the bitmap is fixed when the object is created.
30025 **
30026 ** All bits are clear when the bitmap is created.  Individual bits
30027 ** may be set or cleared one at a time.
30028 **
30029 ** Test operations are about 100 times more common that set operations.
30030 ** Clear operations are exceedingly rare.  There are usually between
30031 ** 5 and 500 set operations per Bitvec object, though the number of sets can
30032 ** sometimes grow into tens of thousands or larger.  The size of the
30033 ** Bitvec object is the number of pages in the database file at the
30034 ** start of a transaction, and is thus usually less than a few thousand,
30035 ** but can be as large as 2 billion for a really big database.
30036 */
30037
30038 /* Size of the Bitvec structure in bytes. */
30039 #define BITVEC_SZ        (sizeof(void*)*128)  /* 512 on 32bit.  1024 on 64bit */
30040
30041 /* Round the union size down to the nearest pointer boundary, since that's how 
30042 ** it will be aligned within the Bitvec struct. */
30043 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
30044
30045 /* Type of the array "element" for the bitmap representation. 
30046 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
30047 ** Setting this to the "natural word" size of your CPU may improve
30048 ** performance. */
30049 #define BITVEC_TELEM     u8
30050 /* Size, in bits, of the bitmap element. */
30051 #define BITVEC_SZELEM    8
30052 /* Number of elements in a bitmap array. */
30053 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
30054 /* Number of bits in the bitmap array. */
30055 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
30056
30057 /* Number of u32 values in hash table. */
30058 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
30059 /* Maximum number of entries in hash table before 
30060 ** sub-dividing and re-hashing. */
30061 #define BITVEC_MXHASH    (BITVEC_NINT/2)
30062 /* Hashing function for the aHash representation.
30063 ** Empirical testing showed that the *37 multiplier 
30064 ** (an arbitrary prime)in the hash function provided 
30065 ** no fewer collisions than the no-op *1. */
30066 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
30067
30068 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
30069
30070
30071 /*
30072 ** A bitmap is an instance of the following structure.
30073 **
30074 ** This bitmap records the existance of zero or more bits
30075 ** with values between 1 and iSize, inclusive.
30076 **
30077 ** There are three possible representations of the bitmap.
30078 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
30079 ** bitmap.  The least significant bit is bit 1.
30080 **
30081 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
30082 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
30083 **
30084 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
30085 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
30086 ** handles up to iDivisor separate values of i.  apSub[0] holds
30087 ** values between 1 and iDivisor.  apSub[1] holds values between
30088 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
30089 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
30090 ** to hold deal with values between 1 and iDivisor.
30091 */
30092 struct Bitvec {
30093   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
30094   u32 nSet;       /* Number of bits that are set - only valid for aHash
30095                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
30096                   ** this would be 125. */
30097   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
30098                   /* Should >=0 for apSub element. */
30099                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
30100                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
30101   union {
30102     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
30103     u32 aHash[BITVEC_NINT];      /* Hash table representation */
30104     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
30105   } u;
30106 };
30107
30108 /*
30109 ** Create a new bitmap object able to handle bits between 0 and iSize,
30110 ** inclusive.  Return a pointer to the new object.  Return NULL if 
30111 ** malloc fails.
30112 */
30113 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
30114   Bitvec *p;
30115   assert( sizeof(*p)==BITVEC_SZ );
30116   p = sqlite3MallocZero( sizeof(*p) );
30117   if( p ){
30118     p->iSize = iSize;
30119   }
30120   return p;
30121 }
30122
30123 /*
30124 ** Check to see if the i-th bit is set.  Return true or false.
30125 ** If p is NULL (if the bitmap has not been created) or if
30126 ** i is out of range, then return false.
30127 */
30128 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
30129   if( p==0 ) return 0;
30130   if( i>p->iSize || i==0 ) return 0;
30131   i--;
30132   while( p->iDivisor ){
30133     u32 bin = i/p->iDivisor;
30134     i = i%p->iDivisor;
30135     p = p->u.apSub[bin];
30136     if (!p) {
30137       return 0;
30138     }
30139   }
30140   if( p->iSize<=BITVEC_NBIT ){
30141     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
30142   } else{
30143     u32 h = BITVEC_HASH(i++);
30144     while( p->u.aHash[h] ){
30145       if( p->u.aHash[h]==i ) return 1;
30146       h = (h+1) % BITVEC_NINT;
30147     }
30148     return 0;
30149   }
30150 }
30151
30152 /*
30153 ** Set the i-th bit.  Return 0 on success and an error code if
30154 ** anything goes wrong.
30155 **
30156 ** This routine might cause sub-bitmaps to be allocated.  Failing
30157 ** to get the memory needed to hold the sub-bitmap is the only
30158 ** that can go wrong with an insert, assuming p and i are valid.
30159 **
30160 ** The calling function must ensure that p is a valid Bitvec object
30161 ** and that the value for "i" is within range of the Bitvec object.
30162 ** Otherwise the behavior is undefined.
30163 */
30164 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
30165   u32 h;
30166   if( p==0 ) return SQLITE_OK;
30167   assert( i>0 );
30168   assert( i<=p->iSize );
30169   i--;
30170   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
30171     u32 bin = i/p->iDivisor;
30172     i = i%p->iDivisor;
30173     if( p->u.apSub[bin]==0 ){
30174       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
30175       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
30176     }
30177     p = p->u.apSub[bin];
30178   }
30179   if( p->iSize<=BITVEC_NBIT ){
30180     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
30181     return SQLITE_OK;
30182   }
30183   h = BITVEC_HASH(i++);
30184   /* if there wasn't a hash collision, and this doesn't */
30185   /* completely fill the hash, then just add it without */
30186   /* worring about sub-dividing and re-hashing. */
30187   if( !p->u.aHash[h] ){
30188     if (p->nSet<(BITVEC_NINT-1)) {
30189       goto bitvec_set_end;
30190     } else {
30191       goto bitvec_set_rehash;
30192     }
30193   }
30194   /* there was a collision, check to see if it's already */
30195   /* in hash, if not, try to find a spot for it */
30196   do {
30197     if( p->u.aHash[h]==i ) return SQLITE_OK;
30198     h++;
30199     if( h>=BITVEC_NINT ) h = 0;
30200   } while( p->u.aHash[h] );
30201   /* we didn't find it in the hash.  h points to the first */
30202   /* available free spot. check to see if this is going to */
30203   /* make our hash too "full".  */
30204 bitvec_set_rehash:
30205   if( p->nSet>=BITVEC_MXHASH ){
30206     unsigned int j;
30207     int rc;
30208     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
30209     if( aiValues==0 ){
30210       return SQLITE_NOMEM;
30211     }else{
30212       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
30213       memset(p->u.apSub, 0, sizeof(p->u.apSub));
30214       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
30215       rc = sqlite3BitvecSet(p, i);
30216       for(j=0; j<BITVEC_NINT; j++){
30217         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
30218       }
30219       sqlite3StackFree(0, aiValues);
30220       return rc;
30221     }
30222   }
30223 bitvec_set_end:
30224   p->nSet++;
30225   p->u.aHash[h] = i;
30226   return SQLITE_OK;
30227 }
30228
30229 /*
30230 ** Clear the i-th bit.
30231 **
30232 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
30233 ** that BitvecClear can use to rebuilt its hash table.
30234 */
30235 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
30236   if( p==0 ) return;
30237   assert( i>0 );
30238   i--;
30239   while( p->iDivisor ){
30240     u32 bin = i/p->iDivisor;
30241     i = i%p->iDivisor;
30242     p = p->u.apSub[bin];
30243     if (!p) {
30244       return;
30245     }
30246   }
30247   if( p->iSize<=BITVEC_NBIT ){
30248     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
30249   }else{
30250     unsigned int j;
30251     u32 *aiValues = pBuf;
30252     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
30253     memset(p->u.aHash, 0, sizeof(p->u.aHash));
30254     p->nSet = 0;
30255     for(j=0; j<BITVEC_NINT; j++){
30256       if( aiValues[j] && aiValues[j]!=(i+1) ){
30257         u32 h = BITVEC_HASH(aiValues[j]-1);
30258         p->nSet++;
30259         while( p->u.aHash[h] ){
30260           h++;
30261           if( h>=BITVEC_NINT ) h = 0;
30262         }
30263         p->u.aHash[h] = aiValues[j];
30264       }
30265     }
30266   }
30267 }
30268
30269 /*
30270 ** Destroy a bitmap object.  Reclaim all memory used.
30271 */
30272 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
30273   if( p==0 ) return;
30274   if( p->iDivisor ){
30275     unsigned int i;
30276     for(i=0; i<BITVEC_NPTR; i++){
30277       sqlite3BitvecDestroy(p->u.apSub[i]);
30278     }
30279   }
30280   sqlite3_free(p);
30281 }
30282
30283 /*
30284 ** Return the value of the iSize parameter specified when Bitvec *p
30285 ** was created.
30286 */
30287 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
30288   return p->iSize;
30289 }
30290
30291 #ifndef SQLITE_OMIT_BUILTIN_TEST
30292 /*
30293 ** Let V[] be an array of unsigned characters sufficient to hold
30294 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
30295 ** Then the following macros can be used to set, clear, or test
30296 ** individual bits within V.
30297 */
30298 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
30299 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
30300 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
30301
30302 /*
30303 ** This routine runs an extensive test of the Bitvec code.
30304 **
30305 ** The input is an array of integers that acts as a program
30306 ** to test the Bitvec.  The integers are opcodes followed
30307 ** by 0, 1, or 3 operands, depending on the opcode.  Another
30308 ** opcode follows immediately after the last operand.
30309 **
30310 ** There are 6 opcodes numbered from 0 through 5.  0 is the
30311 ** "halt" opcode and causes the test to end.
30312 **
30313 **    0          Halt and return the number of errors
30314 **    1 N S X    Set N bits beginning with S and incrementing by X
30315 **    2 N S X    Clear N bits beginning with S and incrementing by X
30316 **    3 N        Set N randomly chosen bits
30317 **    4 N        Clear N randomly chosen bits
30318 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
30319 **
30320 ** The opcodes 1 through 4 perform set and clear operations are performed
30321 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
30322 ** Opcode 5 works on the linear array only, not on the Bitvec.
30323 ** Opcode 5 is used to deliberately induce a fault in order to
30324 ** confirm that error detection works.
30325 **
30326 ** At the conclusion of the test the linear array is compared
30327 ** against the Bitvec object.  If there are any differences,
30328 ** an error is returned.  If they are the same, zero is returned.
30329 **
30330 ** If a memory allocation error occurs, return -1.
30331 */
30332 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
30333   Bitvec *pBitvec = 0;
30334   unsigned char *pV = 0;
30335   int rc = -1;
30336   int i, nx, pc, op;
30337   void *pTmpSpace;
30338
30339   /* Allocate the Bitvec to be tested and a linear array of
30340   ** bits to act as the reference */
30341   pBitvec = sqlite3BitvecCreate( sz );
30342   pV = sqlite3_malloc( (sz+7)/8 + 1 );
30343   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
30344   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
30345   memset(pV, 0, (sz+7)/8 + 1);
30346
30347   /* NULL pBitvec tests */
30348   sqlite3BitvecSet(0, 1);
30349   sqlite3BitvecClear(0, 1, pTmpSpace);
30350
30351   /* Run the program */
30352   pc = 0;
30353   while( (op = aOp[pc])!=0 ){
30354     switch( op ){
30355       case 1:
30356       case 2:
30357       case 5: {
30358         nx = 4;
30359         i = aOp[pc+2] - 1;
30360         aOp[pc+2] += aOp[pc+3];
30361         break;
30362       }
30363       case 3:
30364       case 4: 
30365       default: {
30366         nx = 2;
30367         sqlite3_randomness(sizeof(i), &i);
30368         break;
30369       }
30370     }
30371     if( (--aOp[pc+1]) > 0 ) nx = 0;
30372     pc += nx;
30373     i = (i & 0x7fffffff)%sz;
30374     if( (op & 1)!=0 ){
30375       SETBIT(pV, (i+1));
30376       if( op!=5 ){
30377         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
30378       }
30379     }else{
30380       CLEARBIT(pV, (i+1));
30381       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
30382     }
30383   }
30384
30385   /* Test to make sure the linear array exactly matches the
30386   ** Bitvec object.  Start with the assumption that they do
30387   ** match (rc==0).  Change rc to non-zero if a discrepancy
30388   ** is found.
30389   */
30390   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
30391           + sqlite3BitvecTest(pBitvec, 0)
30392           + (sqlite3BitvecSize(pBitvec) - sz);
30393   for(i=1; i<=sz; i++){
30394     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
30395       rc = i;
30396       break;
30397     }
30398   }
30399
30400   /* Free allocated structure */
30401 bitvec_end:
30402   sqlite3_free(pTmpSpace);
30403   sqlite3_free(pV);
30404   sqlite3BitvecDestroy(pBitvec);
30405   return rc;
30406 }
30407 #endif /* SQLITE_OMIT_BUILTIN_TEST */
30408
30409 /************** End of bitvec.c **********************************************/
30410 /************** Begin file pcache.c ******************************************/
30411 /*
30412 ** 2008 August 05
30413 **
30414 ** The author disclaims copyright to this source code.  In place of
30415 ** a legal notice, here is a blessing:
30416 **
30417 **    May you do good and not evil.
30418 **    May you find forgiveness for yourself and forgive others.
30419 **    May you share freely, never taking more than you give.
30420 **
30421 *************************************************************************
30422 ** This file implements that page cache.
30423 */
30424
30425 /*
30426 ** A complete page cache is an instance of this structure.
30427 */
30428 struct PCache {
30429   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
30430   PgHdr *pSynced;                     /* Last synced page in dirty page list */
30431   int nRef;                           /* Number of referenced pages */
30432   int nMax;                           /* Configured cache size */
30433   int szPage;                         /* Size of every page in this cache */
30434   int szExtra;                        /* Size of extra space for each page */
30435   int bPurgeable;                     /* True if pages are on backing store */
30436   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
30437   void *pStress;                      /* Argument to xStress */
30438   sqlite3_pcache *pCache;             /* Pluggable cache module */
30439   PgHdr *pPage1;                      /* Reference to page 1 */
30440 };
30441
30442 /*
30443 ** Some of the assert() macros in this code are too expensive to run
30444 ** even during normal debugging.  Use them only rarely on long-running
30445 ** tests.  Enable the expensive asserts using the
30446 ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
30447 */
30448 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
30449 # define expensive_assert(X)  assert(X)
30450 #else
30451 # define expensive_assert(X)
30452 #endif
30453
30454 /********************************** Linked List Management ********************/
30455
30456 #if !defined(NDEBUG) && defined(SQLITE_ENABLE_EXPENSIVE_ASSERT)
30457 /*
30458 ** Check that the pCache->pSynced variable is set correctly. If it
30459 ** is not, either fail an assert or return zero. Otherwise, return
30460 ** non-zero. This is only used in debugging builds, as follows:
30461 **
30462 **   expensive_assert( pcacheCheckSynced(pCache) );
30463 */
30464 static int pcacheCheckSynced(PCache *pCache){
30465   PgHdr *p;
30466   for(p=pCache->pDirtyTail; p!=pCache->pSynced; p=p->pDirtyPrev){
30467     assert( p->nRef || (p->flags&PGHDR_NEED_SYNC) );
30468   }
30469   return (p==0 || p->nRef || (p->flags&PGHDR_NEED_SYNC)==0);
30470 }
30471 #endif /* !NDEBUG && SQLITE_ENABLE_EXPENSIVE_ASSERT */
30472
30473 /*
30474 ** Remove page pPage from the list of dirty pages.
30475 */
30476 static void pcacheRemoveFromDirtyList(PgHdr *pPage){
30477   PCache *p = pPage->pCache;
30478
30479   assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
30480   assert( pPage->pDirtyPrev || pPage==p->pDirty );
30481
30482   /* Update the PCache1.pSynced variable if necessary. */
30483   if( p->pSynced==pPage ){
30484     PgHdr *pSynced = pPage->pDirtyPrev;
30485     while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
30486       pSynced = pSynced->pDirtyPrev;
30487     }
30488     p->pSynced = pSynced;
30489   }
30490
30491   if( pPage->pDirtyNext ){
30492     pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
30493   }else{
30494     assert( pPage==p->pDirtyTail );
30495     p->pDirtyTail = pPage->pDirtyPrev;
30496   }
30497   if( pPage->pDirtyPrev ){
30498     pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
30499   }else{
30500     assert( pPage==p->pDirty );
30501     p->pDirty = pPage->pDirtyNext;
30502   }
30503   pPage->pDirtyNext = 0;
30504   pPage->pDirtyPrev = 0;
30505
30506   expensive_assert( pcacheCheckSynced(p) );
30507 }
30508
30509 /*
30510 ** Add page pPage to the head of the dirty list (PCache1.pDirty is set to
30511 ** pPage).
30512 */
30513 static void pcacheAddToDirtyList(PgHdr *pPage){
30514   PCache *p = pPage->pCache;
30515
30516   assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
30517
30518   pPage->pDirtyNext = p->pDirty;
30519   if( pPage->pDirtyNext ){
30520     assert( pPage->pDirtyNext->pDirtyPrev==0 );
30521     pPage->pDirtyNext->pDirtyPrev = pPage;
30522   }
30523   p->pDirty = pPage;
30524   if( !p->pDirtyTail ){
30525     p->pDirtyTail = pPage;
30526   }
30527   if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
30528     p->pSynced = pPage;
30529   }
30530   expensive_assert( pcacheCheckSynced(p) );
30531 }
30532
30533 /*
30534 ** Wrapper around the pluggable caches xUnpin method. If the cache is
30535 ** being used for an in-memory database, this function is a no-op.
30536 */
30537 static void pcacheUnpin(PgHdr *p){
30538   PCache *pCache = p->pCache;
30539   if( pCache->bPurgeable ){
30540     if( p->pgno==1 ){
30541       pCache->pPage1 = 0;
30542     }
30543     sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 0);
30544   }
30545 }
30546
30547 /*************************************************** General Interfaces ******
30548 **
30549 ** Initialize and shutdown the page cache subsystem. Neither of these 
30550 ** functions are threadsafe.
30551 */
30552 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
30553   if( sqlite3GlobalConfig.pcache.xInit==0 ){
30554     sqlite3PCacheSetDefault();
30555   }
30556   return sqlite3GlobalConfig.pcache.xInit(sqlite3GlobalConfig.pcache.pArg);
30557 }
30558 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
30559   if( sqlite3GlobalConfig.pcache.xShutdown ){
30560     sqlite3GlobalConfig.pcache.xShutdown(sqlite3GlobalConfig.pcache.pArg);
30561   }
30562 }
30563
30564 /*
30565 ** Return the size in bytes of a PCache object.
30566 */
30567 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
30568
30569 /*
30570 ** Create a new PCache object. Storage space to hold the object
30571 ** has already been allocated and is passed in as the p pointer. 
30572 ** The caller discovers how much space needs to be allocated by 
30573 ** calling sqlite3PcacheSize().
30574 */
30575 SQLITE_PRIVATE void sqlite3PcacheOpen(
30576   int szPage,                  /* Size of every page */
30577   int szExtra,                 /* Extra space associated with each page */
30578   int bPurgeable,              /* True if pages are on backing store */
30579   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
30580   void *pStress,               /* Argument to xStress */
30581   PCache *p                    /* Preallocated space for the PCache */
30582 ){
30583   memset(p, 0, sizeof(PCache));
30584   p->szPage = szPage;
30585   p->szExtra = szExtra;
30586   p->bPurgeable = bPurgeable;
30587   p->xStress = xStress;
30588   p->pStress = pStress;
30589   p->nMax = 100;
30590 }
30591
30592 /*
30593 ** Change the page size for PCache object. The caller must ensure that there
30594 ** are no outstanding page references when this function is called.
30595 */
30596 SQLITE_PRIVATE void sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
30597   assert( pCache->nRef==0 && pCache->pDirty==0 );
30598   if( pCache->pCache ){
30599     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
30600     pCache->pCache = 0;
30601     pCache->pPage1 = 0;
30602   }
30603   pCache->szPage = szPage;
30604 }
30605
30606 /*
30607 ** Try to obtain a page from the cache.
30608 */
30609 SQLITE_PRIVATE int sqlite3PcacheFetch(
30610   PCache *pCache,       /* Obtain the page from this cache */
30611   Pgno pgno,            /* Page number to obtain */
30612   int createFlag,       /* If true, create page if it does not exist already */
30613   PgHdr **ppPage        /* Write the page here */
30614 ){
30615   PgHdr *pPage = 0;
30616   int eCreate;
30617
30618   assert( pCache!=0 );
30619   assert( createFlag==1 || createFlag==0 );
30620   assert( pgno>0 );
30621
30622   /* If the pluggable cache (sqlite3_pcache*) has not been allocated,
30623   ** allocate it now.
30624   */
30625   if( !pCache->pCache && createFlag ){
30626     sqlite3_pcache *p;
30627     int nByte;
30628     nByte = pCache->szPage + pCache->szExtra + sizeof(PgHdr);
30629     p = sqlite3GlobalConfig.pcache.xCreate(nByte, pCache->bPurgeable);
30630     if( !p ){
30631       return SQLITE_NOMEM;
30632     }
30633     sqlite3GlobalConfig.pcache.xCachesize(p, pCache->nMax);
30634     pCache->pCache = p;
30635   }
30636
30637   eCreate = createFlag * (1 + (!pCache->bPurgeable || !pCache->pDirty));
30638   if( pCache->pCache ){
30639     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, eCreate);
30640   }
30641
30642   if( !pPage && eCreate==1 ){
30643     PgHdr *pPg;
30644
30645     /* Find a dirty page to write-out and recycle. First try to find a 
30646     ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
30647     ** cleared), but if that is not possible settle for any other 
30648     ** unreferenced dirty page.
30649     */
30650     expensive_assert( pcacheCheckSynced(pCache) );
30651     for(pPg=pCache->pSynced; 
30652         pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
30653         pPg=pPg->pDirtyPrev
30654     );
30655     pCache->pSynced = pPg;
30656     if( !pPg ){
30657       for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
30658     }
30659     if( pPg ){
30660       int rc;
30661       rc = pCache->xStress(pCache->pStress, pPg);
30662       if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
30663         return rc;
30664       }
30665     }
30666
30667     pPage = sqlite3GlobalConfig.pcache.xFetch(pCache->pCache, pgno, 2);
30668   }
30669
30670   if( pPage ){
30671     if( !pPage->pData ){
30672       memset(pPage, 0, sizeof(PgHdr) + pCache->szExtra);
30673       pPage->pExtra = (void*)&pPage[1];
30674       pPage->pData = (void *)&((char *)pPage)[sizeof(PgHdr) + pCache->szExtra];
30675       pPage->pCache = pCache;
30676       pPage->pgno = pgno;
30677     }
30678     assert( pPage->pCache==pCache );
30679     assert( pPage->pgno==pgno );
30680     assert( pPage->pExtra==(void *)&pPage[1] );
30681
30682     if( 0==pPage->nRef ){
30683       pCache->nRef++;
30684     }
30685     pPage->nRef++;
30686     if( pgno==1 ){
30687       pCache->pPage1 = pPage;
30688     }
30689   }
30690   *ppPage = pPage;
30691   return (pPage==0 && eCreate) ? SQLITE_NOMEM : SQLITE_OK;
30692 }
30693
30694 /*
30695 ** Decrement the reference count on a page. If the page is clean and the
30696 ** reference count drops to 0, then it is made elible for recycling.
30697 */
30698 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr *p){
30699   assert( p->nRef>0 );
30700   p->nRef--;
30701   if( p->nRef==0 ){
30702     PCache *pCache = p->pCache;
30703     pCache->nRef--;
30704     if( (p->flags&PGHDR_DIRTY)==0 ){
30705       pcacheUnpin(p);
30706     }else{
30707       /* Move the page to the head of the dirty list. */
30708       pcacheRemoveFromDirtyList(p);
30709       pcacheAddToDirtyList(p);
30710     }
30711   }
30712 }
30713
30714 /*
30715 ** Increase the reference count of a supplied page by 1.
30716 */
30717 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
30718   assert(p->nRef>0);
30719   p->nRef++;
30720 }
30721
30722 /*
30723 ** Drop a page from the cache. There must be exactly one reference to the
30724 ** page. This function deletes that reference, so after it returns the
30725 ** page pointed to by p is invalid.
30726 */
30727 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
30728   PCache *pCache;
30729   assert( p->nRef==1 );
30730   if( p->flags&PGHDR_DIRTY ){
30731     pcacheRemoveFromDirtyList(p);
30732   }
30733   pCache = p->pCache;
30734   pCache->nRef--;
30735   if( p->pgno==1 ){
30736     pCache->pPage1 = 0;
30737   }
30738   sqlite3GlobalConfig.pcache.xUnpin(pCache->pCache, p, 1);
30739 }
30740
30741 /*
30742 ** Make sure the page is marked as dirty. If it isn't dirty already,
30743 ** make it so.
30744 */
30745 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
30746   p->flags &= ~PGHDR_DONT_WRITE;
30747   assert( p->nRef>0 );
30748   if( 0==(p->flags & PGHDR_DIRTY) ){
30749     p->flags |= PGHDR_DIRTY;
30750     pcacheAddToDirtyList( p);
30751   }
30752 }
30753
30754 /*
30755 ** Make sure the page is marked as clean. If it isn't clean already,
30756 ** make it so.
30757 */
30758 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
30759   if( (p->flags & PGHDR_DIRTY) ){
30760     pcacheRemoveFromDirtyList(p);
30761     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
30762     if( p->nRef==0 ){
30763       pcacheUnpin(p);
30764     }
30765   }
30766 }
30767
30768 /*
30769 ** Make every page in the cache clean.
30770 */
30771 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
30772   PgHdr *p;
30773   while( (p = pCache->pDirty)!=0 ){
30774     sqlite3PcacheMakeClean(p);
30775   }
30776 }
30777
30778 /*
30779 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
30780 */
30781 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
30782   PgHdr *p;
30783   for(p=pCache->pDirty; p; p=p->pDirtyNext){
30784     p->flags &= ~PGHDR_NEED_SYNC;
30785   }
30786   pCache->pSynced = pCache->pDirtyTail;
30787 }
30788
30789 /*
30790 ** Change the page number of page p to newPgno. 
30791 */
30792 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
30793   PCache *pCache = p->pCache;
30794   assert( p->nRef>0 );
30795   assert( newPgno>0 );
30796   sqlite3GlobalConfig.pcache.xRekey(pCache->pCache, p, p->pgno, newPgno);
30797   p->pgno = newPgno;
30798   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
30799     pcacheRemoveFromDirtyList(p);
30800     pcacheAddToDirtyList(p);
30801   }
30802 }
30803
30804 /*
30805 ** Drop every cache entry whose page number is greater than "pgno". The
30806 ** caller must ensure that there are no outstanding references to any pages
30807 ** other than page 1 with a page number greater than pgno.
30808 **
30809 ** If there is a reference to page 1 and the pgno parameter passed to this
30810 ** function is 0, then the data area associated with page 1 is zeroed, but
30811 ** the page object is not dropped.
30812 */
30813 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
30814   if( pCache->pCache ){
30815     PgHdr *p;
30816     PgHdr *pNext;
30817     for(p=pCache->pDirty; p; p=pNext){
30818       pNext = p->pDirtyNext;
30819       if( p->pgno>pgno ){
30820         assert( p->flags&PGHDR_DIRTY );
30821         sqlite3PcacheMakeClean(p);
30822       }
30823     }
30824     if( pgno==0 && pCache->pPage1 ){
30825       memset(pCache->pPage1->pData, 0, pCache->szPage);
30826       pgno = 1;
30827     }
30828     sqlite3GlobalConfig.pcache.xTruncate(pCache->pCache, pgno+1);
30829   }
30830 }
30831
30832 /*
30833 ** Close a cache.
30834 */
30835 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
30836   if( pCache->pCache ){
30837     sqlite3GlobalConfig.pcache.xDestroy(pCache->pCache);
30838   }
30839 }
30840
30841 /* 
30842 ** Discard the contents of the cache.
30843 */
30844 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
30845   sqlite3PcacheTruncate(pCache, 0);
30846 }
30847
30848 /*
30849 ** Merge two lists of pages connected by pDirty and in pgno order.
30850 ** Do not both fixing the pDirtyPrev pointers.
30851 */
30852 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
30853   PgHdr result, *pTail;
30854   pTail = &result;
30855   while( pA && pB ){
30856     if( pA->pgno<pB->pgno ){
30857       pTail->pDirty = pA;
30858       pTail = pA;
30859       pA = pA->pDirty;
30860     }else{
30861       pTail->pDirty = pB;
30862       pTail = pB;
30863       pB = pB->pDirty;
30864     }
30865   }
30866   if( pA ){
30867     pTail->pDirty = pA;
30868   }else if( pB ){
30869     pTail->pDirty = pB;
30870   }else{
30871     pTail->pDirty = 0;
30872   }
30873   return result.pDirty;
30874 }
30875
30876 /*
30877 ** Sort the list of pages in accending order by pgno.  Pages are
30878 ** connected by pDirty pointers.  The pDirtyPrev pointers are
30879 ** corrupted by this sort.
30880 **
30881 ** Since there cannot be more than 2^31 distinct pages in a database,
30882 ** there cannot be more than 31 buckets required by the merge sorter.
30883 ** One extra bucket is added to catch overflow in case something
30884 ** ever changes to make the previous sentence incorrect.
30885 */
30886 #define N_SORT_BUCKET  32
30887 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
30888   PgHdr *a[N_SORT_BUCKET], *p;
30889   int i;
30890   memset(a, 0, sizeof(a));
30891   while( pIn ){
30892     p = pIn;
30893     pIn = p->pDirty;
30894     p->pDirty = 0;
30895     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
30896       if( a[i]==0 ){
30897         a[i] = p;
30898         break;
30899       }else{
30900         p = pcacheMergeDirtyList(a[i], p);
30901         a[i] = 0;
30902       }
30903     }
30904     if( NEVER(i==N_SORT_BUCKET-1) ){
30905       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
30906       ** the input list.  But that is impossible.
30907       */
30908       a[i] = pcacheMergeDirtyList(a[i], p);
30909     }
30910   }
30911   p = a[0];
30912   for(i=1; i<N_SORT_BUCKET; i++){
30913     p = pcacheMergeDirtyList(p, a[i]);
30914   }
30915   return p;
30916 }
30917
30918 /*
30919 ** Return a list of all dirty pages in the cache, sorted by page number.
30920 */
30921 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
30922   PgHdr *p;
30923   for(p=pCache->pDirty; p; p=p->pDirtyNext){
30924     p->pDirty = p->pDirtyNext;
30925   }
30926   return pcacheSortDirtyList(pCache->pDirty);
30927 }
30928
30929 /* 
30930 ** Return the total number of referenced pages held by the cache.
30931 */
30932 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
30933   return pCache->nRef;
30934 }
30935
30936 /*
30937 ** Return the number of references to the page supplied as an argument.
30938 */
30939 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
30940   return p->nRef;
30941 }
30942
30943 /* 
30944 ** Return the total number of pages in the cache.
30945 */
30946 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
30947   int nPage = 0;
30948   if( pCache->pCache ){
30949     nPage = sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache);
30950   }
30951   return nPage;
30952 }
30953
30954 #ifdef SQLITE_TEST
30955 /*
30956 ** Get the suggested cache-size value.
30957 */
30958 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
30959   return pCache->nMax;
30960 }
30961 #endif
30962
30963 /*
30964 ** Set the suggested cache-size value.
30965 */
30966 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
30967   pCache->nMax = mxPage;
30968   if( pCache->pCache ){
30969     sqlite3GlobalConfig.pcache.xCachesize(pCache->pCache, mxPage);
30970   }
30971 }
30972
30973 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
30974 /*
30975 ** For all dirty pages currently in the cache, invoke the specified
30976 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
30977 ** defined.
30978 */
30979 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
30980   PgHdr *pDirty;
30981   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
30982     xIter(pDirty);
30983   }
30984 }
30985 #endif
30986
30987 /************** End of pcache.c **********************************************/
30988 /************** Begin file pcache1.c *****************************************/
30989 /*
30990 ** 2008 November 05
30991 **
30992 ** The author disclaims copyright to this source code.  In place of
30993 ** a legal notice, here is a blessing:
30994 **
30995 **    May you do good and not evil.
30996 **    May you find forgiveness for yourself and forgive others.
30997 **    May you share freely, never taking more than you give.
30998 **
30999 *************************************************************************
31000 **
31001 ** This file implements the default page cache implementation (the
31002 ** sqlite3_pcache interface). It also contains part of the implementation
31003 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
31004 ** If the default page cache implementation is overriden, then neither of
31005 ** these two features are available.
31006 */
31007
31008
31009 typedef struct PCache1 PCache1;
31010 typedef struct PgHdr1 PgHdr1;
31011 typedef struct PgFreeslot PgFreeslot;
31012
31013 /* Pointers to structures of this type are cast and returned as 
31014 ** opaque sqlite3_pcache* handles
31015 */
31016 struct PCache1 {
31017   /* Cache configuration parameters. Page size (szPage) and the purgeable
31018   ** flag (bPurgeable) are set when the cache is created. nMax may be 
31019   ** modified at any time by a call to the pcache1CacheSize() method.
31020   ** The global mutex must be held when accessing nMax.
31021   */
31022   int szPage;                         /* Size of allocated pages in bytes */
31023   int bPurgeable;                     /* True if cache is purgeable */
31024   unsigned int nMin;                  /* Minimum number of pages reserved */
31025   unsigned int nMax;                  /* Configured "cache_size" value */
31026
31027   /* Hash table of all pages. The following variables may only be accessed
31028   ** when the accessor is holding the global mutex (see pcache1EnterMutex() 
31029   ** and pcache1LeaveMutex()).
31030   */
31031   unsigned int nRecyclable;           /* Number of pages in the LRU list */
31032   unsigned int nPage;                 /* Total number of pages in apHash */
31033   unsigned int nHash;                 /* Number of slots in apHash[] */
31034   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
31035
31036   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
31037 };
31038
31039 /*
31040 ** Each cache entry is represented by an instance of the following 
31041 ** structure. A buffer of PgHdr1.pCache->szPage bytes is allocated 
31042 ** directly before this structure in memory (see the PGHDR1_TO_PAGE() 
31043 ** macro below).
31044 */
31045 struct PgHdr1 {
31046   unsigned int iKey;             /* Key value (page number) */
31047   PgHdr1 *pNext;                 /* Next in hash table chain */
31048   PCache1 *pCache;               /* Cache that currently owns this page */
31049   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
31050   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
31051 };
31052
31053 /*
31054 ** Free slots in the allocator used to divide up the buffer provided using
31055 ** the SQLITE_CONFIG_PAGECACHE mechanism.
31056 */
31057 struct PgFreeslot {
31058   PgFreeslot *pNext;  /* Next free slot */
31059 };
31060
31061 /*
31062 ** Global data used by this cache.
31063 */
31064 static SQLITE_WSD struct PCacheGlobal {
31065   sqlite3_mutex *mutex;               /* static mutex MUTEX_STATIC_LRU */
31066
31067   int nMaxPage;                       /* Sum of nMaxPage for purgeable caches */
31068   int nMinPage;                       /* Sum of nMinPage for purgeable caches */
31069   int nCurrentPage;                   /* Number of purgeable pages allocated */
31070   PgHdr1 *pLruHead, *pLruTail;        /* LRU list of unpinned pages */
31071
31072   /* Variables related to SQLITE_CONFIG_PAGECACHE settings. */
31073   int szSlot;                         /* Size of each free slot */
31074   void *pStart, *pEnd;                /* Bounds of pagecache malloc range */
31075   PgFreeslot *pFree;                  /* Free page blocks */
31076   int isInit;                         /* True if initialized */
31077 } pcache1_g;
31078
31079 /*
31080 ** All code in this file should access the global structure above via the
31081 ** alias "pcache1". This ensures that the WSD emulation is used when
31082 ** compiling for systems that do not support real WSD.
31083 */
31084 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
31085
31086 /*
31087 ** When a PgHdr1 structure is allocated, the associated PCache1.szPage
31088 ** bytes of data are located directly before it in memory (i.e. the total
31089 ** size of the allocation is sizeof(PgHdr1)+PCache1.szPage byte). The
31090 ** PGHDR1_TO_PAGE() macro takes a pointer to a PgHdr1 structure as
31091 ** an argument and returns a pointer to the associated block of szPage
31092 ** bytes. The PAGE_TO_PGHDR1() macro does the opposite: its argument is
31093 ** a pointer to a block of szPage bytes of data and the return value is
31094 ** a pointer to the associated PgHdr1 structure.
31095 **
31096 **   assert( PGHDR1_TO_PAGE(PAGE_TO_PGHDR1(pCache, X))==X );
31097 */
31098 #define PGHDR1_TO_PAGE(p)    (void*)(((char*)p) - p->pCache->szPage)
31099 #define PAGE_TO_PGHDR1(c, p) (PgHdr1*)(((char*)p) + c->szPage)
31100
31101 /*
31102 ** Macros to enter and leave the global LRU mutex.
31103 */
31104 #define pcache1EnterMutex() sqlite3_mutex_enter(pcache1.mutex)
31105 #define pcache1LeaveMutex() sqlite3_mutex_leave(pcache1.mutex)
31106
31107 /******************************************************************************/
31108 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
31109
31110 /*
31111 ** This function is called during initialization if a static buffer is 
31112 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
31113 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
31114 ** enough to contain 'n' buffers of 'sz' bytes each.
31115 */
31116 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
31117   if( pcache1.isInit ){
31118     PgFreeslot *p;
31119     sz = ROUNDDOWN8(sz);
31120     pcache1.szSlot = sz;
31121     pcache1.pStart = pBuf;
31122     pcache1.pFree = 0;
31123     while( n-- ){
31124       p = (PgFreeslot*)pBuf;
31125       p->pNext = pcache1.pFree;
31126       pcache1.pFree = p;
31127       pBuf = (void*)&((char*)pBuf)[sz];
31128     }
31129     pcache1.pEnd = pBuf;
31130   }
31131 }
31132
31133 /*
31134 ** Malloc function used within this file to allocate space from the buffer
31135 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
31136 ** such buffer exists or there is no space left in it, this function falls 
31137 ** back to sqlite3Malloc().
31138 */
31139 static void *pcache1Alloc(int nByte){
31140   void *p;
31141   assert( sqlite3_mutex_held(pcache1.mutex) );
31142   if( nByte<=pcache1.szSlot && pcache1.pFree ){
31143     assert( pcache1.isInit );
31144     p = (PgHdr1 *)pcache1.pFree;
31145     pcache1.pFree = pcache1.pFree->pNext;
31146     sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
31147     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
31148   }else{
31149
31150     /* Allocate a new buffer using sqlite3Malloc. Before doing so, exit the
31151     ** global pcache mutex and unlock the pager-cache object pCache. This is 
31152     ** so that if the attempt to allocate a new buffer causes the the 
31153     ** configured soft-heap-limit to be breached, it will be possible to
31154     ** reclaim memory from this pager-cache.
31155     */
31156     pcache1LeaveMutex();
31157     p = sqlite3Malloc(nByte);
31158     pcache1EnterMutex();
31159     if( p ){
31160       int sz = sqlite3MallocSize(p);
31161       sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
31162     }
31163   }
31164   return p;
31165 }
31166
31167 /*
31168 ** Free an allocated buffer obtained from pcache1Alloc().
31169 */
31170 static void pcache1Free(void *p){
31171   assert( sqlite3_mutex_held(pcache1.mutex) );
31172   if( p==0 ) return;
31173   if( p>=pcache1.pStart && p<pcache1.pEnd ){
31174     PgFreeslot *pSlot;
31175     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
31176     pSlot = (PgFreeslot*)p;
31177     pSlot->pNext = pcache1.pFree;
31178     pcache1.pFree = pSlot;
31179   }else{
31180     int iSize = sqlite3MallocSize(p);
31181     sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -iSize);
31182     sqlite3_free(p);
31183   }
31184 }
31185
31186 /*
31187 ** Allocate a new page object initially associated with cache pCache.
31188 */
31189 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
31190   int nByte = sizeof(PgHdr1) + pCache->szPage;
31191   void *pPg = pcache1Alloc(nByte);
31192   PgHdr1 *p;
31193   if( pPg ){
31194     p = PAGE_TO_PGHDR1(pCache, pPg);
31195     if( pCache->bPurgeable ){
31196       pcache1.nCurrentPage++;
31197     }
31198   }else{
31199     p = 0;
31200   }
31201   return p;
31202 }
31203
31204 /*
31205 ** Free a page object allocated by pcache1AllocPage().
31206 **
31207 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
31208 ** that the current implementation happens to never call this routine
31209 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
31210 */
31211 static void pcache1FreePage(PgHdr1 *p){
31212   if( ALWAYS(p) ){
31213     if( p->pCache->bPurgeable ){
31214       pcache1.nCurrentPage--;
31215     }
31216     pcache1Free(PGHDR1_TO_PAGE(p));
31217   }
31218 }
31219
31220 /*
31221 ** Malloc function used by SQLite to obtain space from the buffer configured
31222 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
31223 ** exists, this function falls back to sqlite3Malloc().
31224 */
31225 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
31226   void *p;
31227   pcache1EnterMutex();
31228   p = pcache1Alloc(sz);
31229   pcache1LeaveMutex();
31230   return p;
31231 }
31232
31233 /*
31234 ** Free an allocated buffer obtained from sqlite3PageMalloc().
31235 */
31236 SQLITE_PRIVATE void sqlite3PageFree(void *p){
31237   pcache1EnterMutex();
31238   pcache1Free(p);
31239   pcache1LeaveMutex();
31240 }
31241
31242 /******************************************************************************/
31243 /******** General Implementation Functions ************************************/
31244
31245 /*
31246 ** This function is used to resize the hash table used by the cache passed
31247 ** as the first argument.
31248 **
31249 ** The global mutex must be held when this function is called.
31250 */
31251 static int pcache1ResizeHash(PCache1 *p){
31252   PgHdr1 **apNew;
31253   unsigned int nNew;
31254   unsigned int i;
31255
31256   assert( sqlite3_mutex_held(pcache1.mutex) );
31257
31258   nNew = p->nHash*2;
31259   if( nNew<256 ){
31260     nNew = 256;
31261   }
31262
31263   pcache1LeaveMutex();
31264   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
31265   apNew = (PgHdr1 **)sqlite3_malloc(sizeof(PgHdr1 *)*nNew);
31266   if( p->nHash ){ sqlite3EndBenignMalloc(); }
31267   pcache1EnterMutex();
31268   if( apNew ){
31269     memset(apNew, 0, sizeof(PgHdr1 *)*nNew);
31270     for(i=0; i<p->nHash; i++){
31271       PgHdr1 *pPage;
31272       PgHdr1 *pNext = p->apHash[i];
31273       while( (pPage = pNext)!=0 ){
31274         unsigned int h = pPage->iKey % nNew;
31275         pNext = pPage->pNext;
31276         pPage->pNext = apNew[h];
31277         apNew[h] = pPage;
31278       }
31279     }
31280     sqlite3_free(p->apHash);
31281     p->apHash = apNew;
31282     p->nHash = nNew;
31283   }
31284
31285   return (p->apHash ? SQLITE_OK : SQLITE_NOMEM);
31286 }
31287
31288 /*
31289 ** This function is used internally to remove the page pPage from the 
31290 ** global LRU list, if is part of it. If pPage is not part of the global
31291 ** LRU list, then this function is a no-op.
31292 **
31293 ** The global mutex must be held when this function is called.
31294 */
31295 static void pcache1PinPage(PgHdr1 *pPage){
31296   assert( sqlite3_mutex_held(pcache1.mutex) );
31297   if( pPage && (pPage->pLruNext || pPage==pcache1.pLruTail) ){
31298     if( pPage->pLruPrev ){
31299       pPage->pLruPrev->pLruNext = pPage->pLruNext;
31300     }
31301     if( pPage->pLruNext ){
31302       pPage->pLruNext->pLruPrev = pPage->pLruPrev;
31303     }
31304     if( pcache1.pLruHead==pPage ){
31305       pcache1.pLruHead = pPage->pLruNext;
31306     }
31307     if( pcache1.pLruTail==pPage ){
31308       pcache1.pLruTail = pPage->pLruPrev;
31309     }
31310     pPage->pLruNext = 0;
31311     pPage->pLruPrev = 0;
31312     pPage->pCache->nRecyclable--;
31313   }
31314 }
31315
31316
31317 /*
31318 ** Remove the page supplied as an argument from the hash table 
31319 ** (PCache1.apHash structure) that it is currently stored in.
31320 **
31321 ** The global mutex must be held when this function is called.
31322 */
31323 static void pcache1RemoveFromHash(PgHdr1 *pPage){
31324   unsigned int h;
31325   PCache1 *pCache = pPage->pCache;
31326   PgHdr1 **pp;
31327
31328   h = pPage->iKey % pCache->nHash;
31329   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
31330   *pp = (*pp)->pNext;
31331
31332   pCache->nPage--;
31333 }
31334
31335 /*
31336 ** If there are currently more than pcache.nMaxPage pages allocated, try
31337 ** to recycle pages to reduce the number allocated to pcache.nMaxPage.
31338 */
31339 static void pcache1EnforceMaxPage(void){
31340   assert( sqlite3_mutex_held(pcache1.mutex) );
31341   while( pcache1.nCurrentPage>pcache1.nMaxPage && pcache1.pLruTail ){
31342     PgHdr1 *p = pcache1.pLruTail;
31343     pcache1PinPage(p);
31344     pcache1RemoveFromHash(p);
31345     pcache1FreePage(p);
31346   }
31347 }
31348
31349 /*
31350 ** Discard all pages from cache pCache with a page number (key value) 
31351 ** greater than or equal to iLimit. Any pinned pages that meet this 
31352 ** criteria are unpinned before they are discarded.
31353 **
31354 ** The global mutex must be held when this function is called.
31355 */
31356 static void pcache1TruncateUnsafe(
31357   PCache1 *pCache, 
31358   unsigned int iLimit 
31359 ){
31360   TESTONLY( unsigned int nPage = 0; )      /* Used to assert pCache->nPage is correct */
31361   unsigned int h;
31362   assert( sqlite3_mutex_held(pcache1.mutex) );
31363   for(h=0; h<pCache->nHash; h++){
31364     PgHdr1 **pp = &pCache->apHash[h]; 
31365     PgHdr1 *pPage;
31366     while( (pPage = *pp)!=0 ){
31367       if( pPage->iKey>=iLimit ){
31368         pCache->nPage--;
31369         *pp = pPage->pNext;
31370         pcache1PinPage(pPage);
31371         pcache1FreePage(pPage);
31372       }else{
31373         pp = &pPage->pNext;
31374         TESTONLY( nPage++; )
31375       }
31376     }
31377   }
31378   assert( pCache->nPage==nPage );
31379 }
31380
31381 /******************************************************************************/
31382 /******** sqlite3_pcache Methods **********************************************/
31383
31384 /*
31385 ** Implementation of the sqlite3_pcache.xInit method.
31386 */
31387 static int pcache1Init(void *NotUsed){
31388   UNUSED_PARAMETER(NotUsed);
31389   assert( pcache1.isInit==0 );
31390   memset(&pcache1, 0, sizeof(pcache1));
31391   if( sqlite3GlobalConfig.bCoreMutex ){
31392     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
31393   }
31394   pcache1.isInit = 1;
31395   return SQLITE_OK;
31396 }
31397
31398 /*
31399 ** Implementation of the sqlite3_pcache.xShutdown method.
31400 ** Note that the static mutex allocated in xInit does 
31401 ** not need to be freed.
31402 */
31403 static void pcache1Shutdown(void *NotUsed){
31404   UNUSED_PARAMETER(NotUsed);
31405   assert( pcache1.isInit!=0 );
31406   memset(&pcache1, 0, sizeof(pcache1));
31407 }
31408
31409 /*
31410 ** Implementation of the sqlite3_pcache.xCreate method.
31411 **
31412 ** Allocate a new cache.
31413 */
31414 static sqlite3_pcache *pcache1Create(int szPage, int bPurgeable){
31415   PCache1 *pCache;
31416
31417   pCache = (PCache1 *)sqlite3_malloc(sizeof(PCache1));
31418   if( pCache ){
31419     memset(pCache, 0, sizeof(PCache1));
31420     pCache->szPage = szPage;
31421     pCache->bPurgeable = (bPurgeable ? 1 : 0);
31422     if( bPurgeable ){
31423       pCache->nMin = 10;
31424       pcache1EnterMutex();
31425       pcache1.nMinPage += pCache->nMin;
31426       pcache1LeaveMutex();
31427     }
31428   }
31429   return (sqlite3_pcache *)pCache;
31430 }
31431
31432 /*
31433 ** Implementation of the sqlite3_pcache.xCachesize method. 
31434 **
31435 ** Configure the cache_size limit for a cache.
31436 */
31437 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
31438   PCache1 *pCache = (PCache1 *)p;
31439   if( pCache->bPurgeable ){
31440     pcache1EnterMutex();
31441     pcache1.nMaxPage += (nMax - pCache->nMax);
31442     pCache->nMax = nMax;
31443     pcache1EnforceMaxPage();
31444     pcache1LeaveMutex();
31445   }
31446 }
31447
31448 /*
31449 ** Implementation of the sqlite3_pcache.xPagecount method. 
31450 */
31451 static int pcache1Pagecount(sqlite3_pcache *p){
31452   int n;
31453   pcache1EnterMutex();
31454   n = ((PCache1 *)p)->nPage;
31455   pcache1LeaveMutex();
31456   return n;
31457 }
31458
31459 /*
31460 ** Implementation of the sqlite3_pcache.xFetch method. 
31461 **
31462 ** Fetch a page by key value.
31463 **
31464 ** Whether or not a new page may be allocated by this function depends on
31465 ** the value of the createFlag argument.  0 means do not allocate a new
31466 ** page.  1 means allocate a new page if space is easily available.  2 
31467 ** means to try really hard to allocate a new page.
31468 **
31469 ** For a non-purgeable cache (a cache used as the storage for an in-memory
31470 ** database) there is really no difference between createFlag 1 and 2.  So
31471 ** the calling function (pcache.c) will never have a createFlag of 1 on
31472 ** a non-purgable cache.
31473 **
31474 ** There are three different approaches to obtaining space for a page,
31475 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
31476 **
31477 **   1. Regardless of the value of createFlag, the cache is searched for a 
31478 **      copy of the requested page. If one is found, it is returned.
31479 **
31480 **   2. If createFlag==0 and the page is not already in the cache, NULL is
31481 **      returned.
31482 **
31483 **   3. If createFlag is 1, and the page is not already in the cache,
31484 **      and if either of the following are true, return NULL:
31485 **
31486 **       (a) the number of pages pinned by the cache is greater than
31487 **           PCache1.nMax, or
31488 **       (b) the number of pages pinned by the cache is greater than
31489 **           the sum of nMax for all purgeable caches, less the sum of 
31490 **           nMin for all other purgeable caches. 
31491 **
31492 **   4. If none of the first three conditions apply and the cache is marked
31493 **      as purgeable, and if one of the following is true:
31494 **
31495 **       (a) The number of pages allocated for the cache is already 
31496 **           PCache1.nMax, or
31497 **
31498 **       (b) The number of pages allocated for all purgeable caches is
31499 **           already equal to or greater than the sum of nMax for all
31500 **           purgeable caches,
31501 **
31502 **      then attempt to recycle a page from the LRU list. If it is the right
31503 **      size, return the recycled buffer. Otherwise, free the buffer and
31504 **      proceed to step 5. 
31505 **
31506 **   5. Otherwise, allocate and return a new page buffer.
31507 */
31508 static void *pcache1Fetch(sqlite3_pcache *p, unsigned int iKey, int createFlag){
31509   unsigned int nPinned;
31510   PCache1 *pCache = (PCache1 *)p;
31511   PgHdr1 *pPage = 0;
31512
31513   assert( pCache->bPurgeable || createFlag!=1 );
31514   pcache1EnterMutex();
31515   if( createFlag==1 ) sqlite3BeginBenignMalloc();
31516
31517   /* Search the hash table for an existing entry. */
31518   if( pCache->nHash>0 ){
31519     unsigned int h = iKey % pCache->nHash;
31520     for(pPage=pCache->apHash[h]; pPage&&pPage->iKey!=iKey; pPage=pPage->pNext);
31521   }
31522
31523   if( pPage || createFlag==0 ){
31524     pcache1PinPage(pPage);
31525     goto fetch_out;
31526   }
31527
31528   /* Step 3 of header comment. */
31529   nPinned = pCache->nPage - pCache->nRecyclable;
31530   if( createFlag==1 && (
31531         nPinned>=(pcache1.nMaxPage+pCache->nMin-pcache1.nMinPage)
31532      || nPinned>=(pCache->nMax * 9 / 10)
31533   )){
31534     goto fetch_out;
31535   }
31536
31537   if( pCache->nPage>=pCache->nHash && pcache1ResizeHash(pCache) ){
31538     goto fetch_out;
31539   }
31540
31541   /* Step 4. Try to recycle a page buffer if appropriate. */
31542   if( pCache->bPurgeable && pcache1.pLruTail && (
31543      (pCache->nPage+1>=pCache->nMax) || pcache1.nCurrentPage>=pcache1.nMaxPage
31544   )){
31545     pPage = pcache1.pLruTail;
31546     pcache1RemoveFromHash(pPage);
31547     pcache1PinPage(pPage);
31548     if( pPage->pCache->szPage!=pCache->szPage ){
31549       pcache1FreePage(pPage);
31550       pPage = 0;
31551     }else{
31552       pcache1.nCurrentPage -= (pPage->pCache->bPurgeable - pCache->bPurgeable);
31553     }
31554   }
31555
31556   /* Step 5. If a usable page buffer has still not been found, 
31557   ** attempt to allocate a new one. 
31558   */
31559   if( !pPage ){
31560     pPage = pcache1AllocPage(pCache);
31561   }
31562
31563   if( pPage ){
31564     unsigned int h = iKey % pCache->nHash;
31565     pCache->nPage++;
31566     pPage->iKey = iKey;
31567     pPage->pNext = pCache->apHash[h];
31568     pPage->pCache = pCache;
31569     pPage->pLruPrev = 0;
31570     pPage->pLruNext = 0;
31571     *(void **)(PGHDR1_TO_PAGE(pPage)) = 0;
31572     pCache->apHash[h] = pPage;
31573   }
31574
31575 fetch_out:
31576   if( pPage && iKey>pCache->iMaxKey ){
31577     pCache->iMaxKey = iKey;
31578   }
31579   if( createFlag==1 ) sqlite3EndBenignMalloc();
31580   pcache1LeaveMutex();
31581   return (pPage ? PGHDR1_TO_PAGE(pPage) : 0);
31582 }
31583
31584
31585 /*
31586 ** Implementation of the sqlite3_pcache.xUnpin method.
31587 **
31588 ** Mark a page as unpinned (eligible for asynchronous recycling).
31589 */
31590 static void pcache1Unpin(sqlite3_pcache *p, void *pPg, int reuseUnlikely){
31591   PCache1 *pCache = (PCache1 *)p;
31592   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
31593  
31594   assert( pPage->pCache==pCache );
31595   pcache1EnterMutex();
31596
31597   /* It is an error to call this function if the page is already 
31598   ** part of the global LRU list.
31599   */
31600   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
31601   assert( pcache1.pLruHead!=pPage && pcache1.pLruTail!=pPage );
31602
31603   if( reuseUnlikely || pcache1.nCurrentPage>pcache1.nMaxPage ){
31604     pcache1RemoveFromHash(pPage);
31605     pcache1FreePage(pPage);
31606   }else{
31607     /* Add the page to the global LRU list. Normally, the page is added to
31608     ** the head of the list (last page to be recycled). However, if the 
31609     ** reuseUnlikely flag passed to this function is true, the page is added
31610     ** to the tail of the list (first page to be recycled).
31611     */
31612     if( pcache1.pLruHead ){
31613       pcache1.pLruHead->pLruPrev = pPage;
31614       pPage->pLruNext = pcache1.pLruHead;
31615       pcache1.pLruHead = pPage;
31616     }else{
31617       pcache1.pLruTail = pPage;
31618       pcache1.pLruHead = pPage;
31619     }
31620     pCache->nRecyclable++;
31621   }
31622
31623   pcache1LeaveMutex();
31624 }
31625
31626 /*
31627 ** Implementation of the sqlite3_pcache.xRekey method. 
31628 */
31629 static void pcache1Rekey(
31630   sqlite3_pcache *p,
31631   void *pPg,
31632   unsigned int iOld,
31633   unsigned int iNew
31634 ){
31635   PCache1 *pCache = (PCache1 *)p;
31636   PgHdr1 *pPage = PAGE_TO_PGHDR1(pCache, pPg);
31637   PgHdr1 **pp;
31638   unsigned int h; 
31639   assert( pPage->iKey==iOld );
31640   assert( pPage->pCache==pCache );
31641
31642   pcache1EnterMutex();
31643
31644   h = iOld%pCache->nHash;
31645   pp = &pCache->apHash[h];
31646   while( (*pp)!=pPage ){
31647     pp = &(*pp)->pNext;
31648   }
31649   *pp = pPage->pNext;
31650
31651   h = iNew%pCache->nHash;
31652   pPage->iKey = iNew;
31653   pPage->pNext = pCache->apHash[h];
31654   pCache->apHash[h] = pPage;
31655   if( iNew>pCache->iMaxKey ){
31656     pCache->iMaxKey = iNew;
31657   }
31658
31659   pcache1LeaveMutex();
31660 }
31661
31662 /*
31663 ** Implementation of the sqlite3_pcache.xTruncate method. 
31664 **
31665 ** Discard all unpinned pages in the cache with a page number equal to
31666 ** or greater than parameter iLimit. Any pinned pages with a page number
31667 ** equal to or greater than iLimit are implicitly unpinned.
31668 */
31669 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
31670   PCache1 *pCache = (PCache1 *)p;
31671   pcache1EnterMutex();
31672   if( iLimit<=pCache->iMaxKey ){
31673     pcache1TruncateUnsafe(pCache, iLimit);
31674     pCache->iMaxKey = iLimit-1;
31675   }
31676   pcache1LeaveMutex();
31677 }
31678
31679 /*
31680 ** Implementation of the sqlite3_pcache.xDestroy method. 
31681 **
31682 ** Destroy a cache allocated using pcache1Create().
31683 */
31684 static void pcache1Destroy(sqlite3_pcache *p){
31685   PCache1 *pCache = (PCache1 *)p;
31686   pcache1EnterMutex();
31687   pcache1TruncateUnsafe(pCache, 0);
31688   pcache1.nMaxPage -= pCache->nMax;
31689   pcache1.nMinPage -= pCache->nMin;
31690   pcache1EnforceMaxPage();
31691   pcache1LeaveMutex();
31692   sqlite3_free(pCache->apHash);
31693   sqlite3_free(pCache);
31694 }
31695
31696 /*
31697 ** This function is called during initialization (sqlite3_initialize()) to
31698 ** install the default pluggable cache module, assuming the user has not
31699 ** already provided an alternative.
31700 */
31701 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
31702   static sqlite3_pcache_methods defaultMethods = {
31703     0,                       /* pArg */
31704     pcache1Init,             /* xInit */
31705     pcache1Shutdown,         /* xShutdown */
31706     pcache1Create,           /* xCreate */
31707     pcache1Cachesize,        /* xCachesize */
31708     pcache1Pagecount,        /* xPagecount */
31709     pcache1Fetch,            /* xFetch */
31710     pcache1Unpin,            /* xUnpin */
31711     pcache1Rekey,            /* xRekey */
31712     pcache1Truncate,         /* xTruncate */
31713     pcache1Destroy           /* xDestroy */
31714   };
31715   sqlite3_config(SQLITE_CONFIG_PCACHE, &defaultMethods);
31716 }
31717
31718 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
31719 /*
31720 ** This function is called to free superfluous dynamically allocated memory
31721 ** held by the pager system. Memory in use by any SQLite pager allocated
31722 ** by the current thread may be sqlite3_free()ed.
31723 **
31724 ** nReq is the number of bytes of memory required. Once this much has
31725 ** been released, the function returns. The return value is the total number 
31726 ** of bytes of memory released.
31727 */
31728 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
31729   int nFree = 0;
31730   if( pcache1.pStart==0 ){
31731     PgHdr1 *p;
31732     pcache1EnterMutex();
31733     while( (nReq<0 || nFree<nReq) && (p=pcache1.pLruTail) ){
31734       nFree += sqlite3MallocSize(PGHDR1_TO_PAGE(p));
31735       pcache1PinPage(p);
31736       pcache1RemoveFromHash(p);
31737       pcache1FreePage(p);
31738     }
31739     pcache1LeaveMutex();
31740   }
31741   return nFree;
31742 }
31743 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
31744
31745 #ifdef SQLITE_TEST
31746 /*
31747 ** This function is used by test procedures to inspect the internal state
31748 ** of the global cache.
31749 */
31750 SQLITE_PRIVATE void sqlite3PcacheStats(
31751   int *pnCurrent,      /* OUT: Total number of pages cached */
31752   int *pnMax,          /* OUT: Global maximum cache size */
31753   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
31754   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
31755 ){
31756   PgHdr1 *p;
31757   int nRecyclable = 0;
31758   for(p=pcache1.pLruHead; p; p=p->pLruNext){
31759     nRecyclable++;
31760   }
31761   *pnCurrent = pcache1.nCurrentPage;
31762   *pnMax = pcache1.nMaxPage;
31763   *pnMin = pcache1.nMinPage;
31764   *pnRecyclable = nRecyclable;
31765 }
31766 #endif
31767
31768 /************** End of pcache1.c *********************************************/
31769 /************** Begin file rowset.c ******************************************/
31770 /*
31771 ** 2008 December 3
31772 **
31773 ** The author disclaims copyright to this source code.  In place of
31774 ** a legal notice, here is a blessing:
31775 **
31776 **    May you do good and not evil.
31777 **    May you find forgiveness for yourself and forgive others.
31778 **    May you share freely, never taking more than you give.
31779 **
31780 *************************************************************************
31781 **
31782 ** This module implements an object we call a "RowSet".
31783 **
31784 ** The RowSet object is a collection of rowids.  Rowids
31785 ** are inserted into the RowSet in an arbitrary order.  Inserts
31786 ** can be intermixed with tests to see if a given rowid has been
31787 ** previously inserted into the RowSet.
31788 **
31789 ** After all inserts are finished, it is possible to extract the
31790 ** elements of the RowSet in sorted order.  Once this extraction
31791 ** process has started, no new elements may be inserted.
31792 **
31793 ** Hence, the primitive operations for a RowSet are:
31794 **
31795 **    CREATE
31796 **    INSERT
31797 **    TEST
31798 **    SMALLEST
31799 **    DESTROY
31800 **
31801 ** The CREATE and DESTROY primitives are the constructor and destructor,
31802 ** obviously.  The INSERT primitive adds a new element to the RowSet.
31803 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
31804 ** extracts the least value from the RowSet.
31805 **
31806 ** The INSERT primitive might allocate additional memory.  Memory is
31807 ** allocated in chunks so most INSERTs do no allocation.  There is an 
31808 ** upper bound on the size of allocated memory.  No memory is freed
31809 ** until DESTROY.
31810 **
31811 ** The TEST primitive includes a "batch" number.  The TEST primitive
31812 ** will only see elements that were inserted before the last change
31813 ** in the batch number.  In other words, if an INSERT occurs between
31814 ** two TESTs where the TESTs have the same batch nubmer, then the
31815 ** value added by the INSERT will not be visible to the second TEST.
31816 ** The initial batch number is zero, so if the very first TEST contains
31817 ** a non-zero batch number, it will see all prior INSERTs.
31818 **
31819 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
31820 ** that is attempted.
31821 **
31822 ** The cost of an INSERT is roughly constant.  (Sometime new memory
31823 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
31824 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
31825 ** The cost of a TEST using the same batch number is O(logN).  The cost
31826 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
31827 ** primitives are constant time.  The cost of DESTROY is O(N).
31828 **
31829 ** There is an added cost of O(N) when switching between TEST and
31830 ** SMALLEST primitives.
31831 */
31832
31833
31834 /*
31835 ** Target size for allocation chunks.
31836 */
31837 #define ROWSET_ALLOCATION_SIZE 1024
31838
31839 /*
31840 ** The number of rowset entries per allocation chunk.
31841 */
31842 #define ROWSET_ENTRY_PER_CHUNK  \
31843                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
31844
31845 /*
31846 ** Each entry in a RowSet is an instance of the following object.
31847 */
31848 struct RowSetEntry {            
31849   i64 v;                        /* ROWID value for this entry */
31850   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
31851   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
31852 };
31853
31854 /*
31855 ** RowSetEntry objects are allocated in large chunks (instances of the
31856 ** following structure) to reduce memory allocation overhead.  The
31857 ** chunks are kept on a linked list so that they can be deallocated
31858 ** when the RowSet is destroyed.
31859 */
31860 struct RowSetChunk {
31861   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
31862   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
31863 };
31864
31865 /*
31866 ** A RowSet in an instance of the following structure.
31867 **
31868 ** A typedef of this structure if found in sqliteInt.h.
31869 */
31870 struct RowSet {
31871   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
31872   sqlite3 *db;                   /* The database connection */
31873   struct RowSetEntry *pEntry;    /* List of entries using pRight */
31874   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
31875   struct RowSetEntry *pFresh;    /* Source of new entry objects */
31876   struct RowSetEntry *pTree;     /* Binary tree of entries */
31877   u16 nFresh;                    /* Number of objects on pFresh */
31878   u8 isSorted;                   /* True if pEntry is sorted */
31879   u8 iBatch;                     /* Current insert batch */
31880 };
31881
31882 /*
31883 ** Turn bulk memory into a RowSet object.  N bytes of memory
31884 ** are available at pSpace.  The db pointer is used as a memory context
31885 ** for any subsequent allocations that need to occur.
31886 ** Return a pointer to the new RowSet object.
31887 **
31888 ** It must be the case that N is sufficient to make a Rowset.  If not
31889 ** an assertion fault occurs.
31890 ** 
31891 ** If N is larger than the minimum, use the surplus as an initial
31892 ** allocation of entries available to be filled.
31893 */
31894 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
31895   RowSet *p;
31896   assert( N >= ROUND8(sizeof(*p)) );
31897   p = pSpace;
31898   p->pChunk = 0;
31899   p->db = db;
31900   p->pEntry = 0;
31901   p->pLast = 0;
31902   p->pTree = 0;
31903   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
31904   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
31905   p->isSorted = 1;
31906   p->iBatch = 0;
31907   return p;
31908 }
31909
31910 /*
31911 ** Deallocate all chunks from a RowSet.  This frees all memory that
31912 ** the RowSet has allocated over its lifetime.  This routine is
31913 ** the destructor for the RowSet.
31914 */
31915 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
31916   struct RowSetChunk *pChunk, *pNextChunk;
31917   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
31918     pNextChunk = pChunk->pNextChunk;
31919     sqlite3DbFree(p->db, pChunk);
31920   }
31921   p->pChunk = 0;
31922   p->nFresh = 0;
31923   p->pEntry = 0;
31924   p->pLast = 0;
31925   p->pTree = 0;
31926   p->isSorted = 1;
31927 }
31928
31929 /*
31930 ** Insert a new value into a RowSet.
31931 **
31932 ** The mallocFailed flag of the database connection is set if a
31933 ** memory allocation fails.
31934 */
31935 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
31936   struct RowSetEntry *pEntry;  /* The new entry */
31937   struct RowSetEntry *pLast;   /* The last prior entry */
31938   assert( p!=0 );
31939   if( p->nFresh==0 ){
31940     struct RowSetChunk *pNew;
31941     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
31942     if( pNew==0 ){
31943       return;
31944     }
31945     pNew->pNextChunk = p->pChunk;
31946     p->pChunk = pNew;
31947     p->pFresh = pNew->aEntry;
31948     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
31949   }
31950   pEntry = p->pFresh++;
31951   p->nFresh--;
31952   pEntry->v = rowid;
31953   pEntry->pRight = 0;
31954   pLast = p->pLast;
31955   if( pLast ){
31956     if( p->isSorted && rowid<=pLast->v ){
31957       p->isSorted = 0;
31958     }
31959     pLast->pRight = pEntry;
31960   }else{
31961     assert( p->pEntry==0 ); /* Fires if INSERT after SMALLEST */
31962     p->pEntry = pEntry;
31963   }
31964   p->pLast = pEntry;
31965 }
31966
31967 /*
31968 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
31969 **
31970 ** The input lists are connected via pRight pointers and are 
31971 ** assumed to each already be in sorted order.
31972 */
31973 static struct RowSetEntry *rowSetMerge(
31974   struct RowSetEntry *pA,    /* First sorted list to be merged */
31975   struct RowSetEntry *pB     /* Second sorted list to be merged */
31976 ){
31977   struct RowSetEntry head;
31978   struct RowSetEntry *pTail;
31979
31980   pTail = &head;
31981   while( pA && pB ){
31982     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
31983     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
31984     if( pA->v<pB->v ){
31985       pTail->pRight = pA;
31986       pA = pA->pRight;
31987       pTail = pTail->pRight;
31988     }else if( pB->v<pA->v ){
31989       pTail->pRight = pB;
31990       pB = pB->pRight;
31991       pTail = pTail->pRight;
31992     }else{
31993       pA = pA->pRight;
31994     }
31995   }
31996   if( pA ){
31997     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
31998     pTail->pRight = pA;
31999   }else{
32000     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
32001     pTail->pRight = pB;
32002   }
32003   return head.pRight;
32004 }
32005
32006 /*
32007 ** Sort all elements on the pEntry list of the RowSet into ascending order.
32008 */ 
32009 static void rowSetSort(RowSet *p){
32010   unsigned int i;
32011   struct RowSetEntry *pEntry;
32012   struct RowSetEntry *aBucket[40];
32013
32014   assert( p->isSorted==0 );
32015   memset(aBucket, 0, sizeof(aBucket));
32016   while( p->pEntry ){
32017     pEntry = p->pEntry;
32018     p->pEntry = pEntry->pRight;
32019     pEntry->pRight = 0;
32020     for(i=0; aBucket[i]; i++){
32021       pEntry = rowSetMerge(aBucket[i], pEntry);
32022       aBucket[i] = 0;
32023     }
32024     aBucket[i] = pEntry;
32025   }
32026   pEntry = 0;
32027   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
32028     pEntry = rowSetMerge(pEntry, aBucket[i]);
32029   }
32030   p->pEntry = pEntry;
32031   p->pLast = 0;
32032   p->isSorted = 1;
32033 }
32034
32035
32036 /*
32037 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
32038 ** Convert this tree into a linked list connected by the pRight pointers
32039 ** and return pointers to the first and last elements of the new list.
32040 */
32041 static void rowSetTreeToList(
32042   struct RowSetEntry *pIn,         /* Root of the input tree */
32043   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
32044   struct RowSetEntry **ppLast      /* Write tail of the output list here */
32045 ){
32046   assert( pIn!=0 );
32047   if( pIn->pLeft ){
32048     struct RowSetEntry *p;
32049     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
32050     p->pRight = pIn;
32051   }else{
32052     *ppFirst = pIn;
32053   }
32054   if( pIn->pRight ){
32055     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
32056   }else{
32057     *ppLast = pIn;
32058   }
32059   assert( (*ppLast)->pRight==0 );
32060 }
32061
32062
32063 /*
32064 ** Convert a sorted list of elements (connected by pRight) into a binary
32065 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
32066 ** node taken from the head of *ppList.  A depth of 2 means a tree with
32067 ** three nodes.  And so forth.
32068 **
32069 ** Use as many entries from the input list as required and update the
32070 ** *ppList to point to the unused elements of the list.  If the input
32071 ** list contains too few elements, then construct an incomplete tree
32072 ** and leave *ppList set to NULL.
32073 **
32074 ** Return a pointer to the root of the constructed binary tree.
32075 */
32076 static struct RowSetEntry *rowSetNDeepTree(
32077   struct RowSetEntry **ppList,
32078   int iDepth
32079 ){
32080   struct RowSetEntry *p;         /* Root of the new tree */
32081   struct RowSetEntry *pLeft;     /* Left subtree */
32082   if( *ppList==0 ){
32083     return 0;
32084   }
32085   if( iDepth==1 ){
32086     p = *ppList;
32087     *ppList = p->pRight;
32088     p->pLeft = p->pRight = 0;
32089     return p;
32090   }
32091   pLeft = rowSetNDeepTree(ppList, iDepth-1);
32092   p = *ppList;
32093   if( p==0 ){
32094     return pLeft;
32095   }
32096   p->pLeft = pLeft;
32097   *ppList = p->pRight;
32098   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
32099   return p;
32100 }
32101
32102 /*
32103 ** Convert a sorted list of elements into a binary tree. Make the tree
32104 ** as deep as it needs to be in order to contain the entire list.
32105 */
32106 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
32107   int iDepth;           /* Depth of the tree so far */
32108   struct RowSetEntry *p;       /* Current tree root */
32109   struct RowSetEntry *pLeft;   /* Left subtree */
32110
32111   assert( pList!=0 );
32112   p = pList;
32113   pList = p->pRight;
32114   p->pLeft = p->pRight = 0;
32115   for(iDepth=1; pList; iDepth++){
32116     pLeft = p;
32117     p = pList;
32118     pList = p->pRight;
32119     p->pLeft = pLeft;
32120     p->pRight = rowSetNDeepTree(&pList, iDepth);
32121   }
32122   return p;
32123 }
32124
32125 /*
32126 ** Convert the list in p->pEntry into a sorted list if it is not
32127 ** sorted already.  If there is a binary tree on p->pTree, then
32128 ** convert it into a list too and merge it into the p->pEntry list.
32129 */
32130 static void rowSetToList(RowSet *p){
32131   if( !p->isSorted ){
32132     rowSetSort(p);
32133   }
32134   if( p->pTree ){
32135     struct RowSetEntry *pHead, *pTail;
32136     rowSetTreeToList(p->pTree, &pHead, &pTail);
32137     p->pTree = 0;
32138     p->pEntry = rowSetMerge(p->pEntry, pHead);
32139   }
32140 }
32141
32142 /*
32143 ** Extract the smallest element from the RowSet.
32144 ** Write the element into *pRowid.  Return 1 on success.  Return
32145 ** 0 if the RowSet is already empty.
32146 **
32147 ** After this routine has been called, the sqlite3RowSetInsert()
32148 ** routine may not be called again.  
32149 */
32150 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
32151   rowSetToList(p);
32152   if( p->pEntry ){
32153     *pRowid = p->pEntry->v;
32154     p->pEntry = p->pEntry->pRight;
32155     if( p->pEntry==0 ){
32156       sqlite3RowSetClear(p);
32157     }
32158     return 1;
32159   }else{
32160     return 0;
32161   }
32162 }
32163
32164 /*
32165 ** Check to see if element iRowid was inserted into the the rowset as
32166 ** part of any insert batch prior to iBatch.  Return 1 or 0.
32167 */
32168 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, u8 iBatch, sqlite3_int64 iRowid){
32169   struct RowSetEntry *p;
32170   if( iBatch!=pRowSet->iBatch ){
32171     if( pRowSet->pEntry ){
32172       rowSetToList(pRowSet);
32173       pRowSet->pTree = rowSetListToTree(pRowSet->pEntry);
32174       pRowSet->pEntry = 0;
32175       pRowSet->pLast = 0;
32176     }
32177     pRowSet->iBatch = iBatch;
32178   }
32179   p = pRowSet->pTree;
32180   while( p ){
32181     if( p->v<iRowid ){
32182       p = p->pRight;
32183     }else if( p->v>iRowid ){
32184       p = p->pLeft;
32185     }else{
32186       return 1;
32187     }
32188   }
32189   return 0;
32190 }
32191
32192 /************** End of rowset.c **********************************************/
32193 /************** Begin file pager.c *******************************************/
32194 /*
32195 ** 2001 September 15
32196 **
32197 ** The author disclaims copyright to this source code.  In place of
32198 ** a legal notice, here is a blessing:
32199 **
32200 **    May you do good and not evil.
32201 **    May you find forgiveness for yourself and forgive others.
32202 **    May you share freely, never taking more than you give.
32203 **
32204 *************************************************************************
32205 ** This is the implementation of the page cache subsystem or "pager".
32206 ** 
32207 ** The pager is used to access a database disk file.  It implements
32208 ** atomic commit and rollback through the use of a journal file that
32209 ** is separate from the database file.  The pager also implements file
32210 ** locking to prevent two processes from writing the same database
32211 ** file simultaneously, or one process from reading the database while
32212 ** another is writing.
32213 */
32214 #ifndef SQLITE_OMIT_DISKIO
32215
32216 /*
32217 ** Macros for troubleshooting.  Normally turned off
32218 */
32219 #if 0
32220 int sqlite3PagerTrace=1;  /* True to enable tracing */
32221 #define sqlite3DebugPrintf printf
32222 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
32223 #else
32224 #define PAGERTRACE(X)
32225 #endif
32226
32227 /*
32228 ** The following two macros are used within the PAGERTRACE() macros above
32229 ** to print out file-descriptors. 
32230 **
32231 ** PAGERID() takes a pointer to a Pager struct as its argument. The
32232 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
32233 ** struct as its argument.
32234 */
32235 #define PAGERID(p) ((int)(p->fd))
32236 #define FILEHANDLEID(fd) ((int)fd)
32237
32238 /*
32239 ** The page cache as a whole is always in one of the following
32240 ** states:
32241 **
32242 **   PAGER_UNLOCK        The page cache is not currently reading or 
32243 **                       writing the database file.  There is no
32244 **                       data held in memory.  This is the initial
32245 **                       state.
32246 **
32247 **   PAGER_SHARED        The page cache is reading the database.
32248 **                       Writing is not permitted.  There can be
32249 **                       multiple readers accessing the same database
32250 **                       file at the same time.
32251 **
32252 **   PAGER_RESERVED      This process has reserved the database for writing
32253 **                       but has not yet made any changes.  Only one process
32254 **                       at a time can reserve the database.  The original
32255 **                       database file has not been modified so other
32256 **                       processes may still be reading the on-disk
32257 **                       database file.
32258 **
32259 **   PAGER_EXCLUSIVE     The page cache is writing the database.
32260 **                       Access is exclusive.  No other processes or
32261 **                       threads can be reading or writing while one
32262 **                       process is writing.
32263 **
32264 **   PAGER_SYNCED        The pager moves to this state from PAGER_EXCLUSIVE
32265 **                       after all dirty pages have been written to the
32266 **                       database file and the file has been synced to
32267 **                       disk. All that remains to do is to remove or
32268 **                       truncate the journal file and the transaction 
32269 **                       will be committed.
32270 **
32271 ** The page cache comes up in PAGER_UNLOCK.  The first time a
32272 ** sqlite3PagerGet() occurs, the state transitions to PAGER_SHARED.
32273 ** After all pages have been released using sqlite_page_unref(),
32274 ** the state transitions back to PAGER_UNLOCK.  The first time
32275 ** that sqlite3PagerWrite() is called, the state transitions to
32276 ** PAGER_RESERVED.  (Note that sqlite3PagerWrite() can only be
32277 ** called on an outstanding page which means that the pager must
32278 ** be in PAGER_SHARED before it transitions to PAGER_RESERVED.)
32279 ** PAGER_RESERVED means that there is an open rollback journal.
32280 ** The transition to PAGER_EXCLUSIVE occurs before any changes
32281 ** are made to the database file, though writes to the rollback
32282 ** journal occurs with just PAGER_RESERVED.  After an sqlite3PagerRollback()
32283 ** or sqlite3PagerCommitPhaseTwo(), the state can go back to PAGER_SHARED,
32284 ** or it can stay at PAGER_EXCLUSIVE if we are in exclusive access mode.
32285 */
32286 #define PAGER_UNLOCK      0
32287 #define PAGER_SHARED      1   /* same as SHARED_LOCK */
32288 #define PAGER_RESERVED    2   /* same as RESERVED_LOCK */
32289 #define PAGER_EXCLUSIVE   4   /* same as EXCLUSIVE_LOCK */
32290 #define PAGER_SYNCED      5
32291
32292 /*
32293 ** A macro used for invoking the codec if there is one
32294 */
32295 #ifdef SQLITE_HAS_CODEC
32296 # define CODEC1(P,D,N,X,E) \
32297     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
32298 # define CODEC2(P,D,N,X,E,O) \
32299     if( P->xCodec==0 ){ O=(char*)D; }else \
32300     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
32301 #else
32302 # define CODEC1(P,D,N,X,E)   /* NO-OP */
32303 # define CODEC2(P,D,N,X,E,O) O=(char*)D
32304 #endif
32305
32306 /*
32307 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
32308 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
32309 ** This could conceivably cause corruption following a power failure on
32310 ** such a system. This is currently an undocumented limit.
32311 */
32312 #define MAX_SECTOR_SIZE 0x10000
32313
32314 /*
32315 ** An instance of the following structure is allocated for each active
32316 ** savepoint and statement transaction in the system. All such structures
32317 ** are stored in the Pager.aSavepoint[] array, which is allocated and
32318 ** resized using sqlite3Realloc().
32319 **
32320 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
32321 ** set to 0. If a journal-header is written into the main journal while
32322 ** the savepoint is active, then iHdrOffset is set to the byte offset 
32323 ** immediately following the last journal record written into the main
32324 ** journal before the journal-header. This is required during savepoint
32325 ** rollback (see pagerPlaybackSavepoint()).
32326 */
32327 typedef struct PagerSavepoint PagerSavepoint;
32328 struct PagerSavepoint {
32329   i64 iOffset;                 /* Starting offset in main journal */
32330   i64 iHdrOffset;              /* See above */
32331   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
32332   Pgno nOrig;                  /* Original number of pages in file */
32333   Pgno iSubRec;                /* Index of first record in sub-journal */
32334 };
32335
32336 /*
32337 ** A open page cache is an instance of the following structure.
32338 **
32339 ** errCode
32340 **
32341 **   Pager.errCode may be set to SQLITE_IOERR, SQLITE_CORRUPT, or
32342 **   or SQLITE_FULL. Once one of the first three errors occurs, it persists
32343 **   and is returned as the result of every major pager API call.  The
32344 **   SQLITE_FULL return code is slightly different. It persists only until the
32345 **   next successful rollback is performed on the pager cache. Also,
32346 **   SQLITE_FULL does not affect the sqlite3PagerGet() and sqlite3PagerLookup()
32347 **   APIs, they may still be used successfully.
32348 **
32349 ** dbSizeValid, dbSize, dbOrigSize, dbFileSize
32350 **
32351 **   Managing the size of the database file in pages is a little complicated.
32352 **   The variable Pager.dbSize contains the number of pages that the database
32353 **   image currently contains. As the database image grows or shrinks this
32354 **   variable is updated. The variable Pager.dbFileSize contains the number
32355 **   of pages in the database file. This may be different from Pager.dbSize
32356 **   if some pages have been appended to the database image but not yet written
32357 **   out from the cache to the actual file on disk. Or if the image has been
32358 **   truncated by an incremental-vacuum operation. The Pager.dbOrigSize variable
32359 **   contains the number of pages in the database image when the current
32360 **   transaction was opened. The contents of all three of these variables is
32361 **   only guaranteed to be correct if the boolean Pager.dbSizeValid is true.
32362 **
32363 **   TODO: Under what conditions is dbSizeValid set? Cleared?
32364 **
32365 ** changeCountDone
32366 **
32367 **   This boolean variable is used to make sure that the change-counter 
32368 **   (the 4-byte header field at byte offset 24 of the database file) is 
32369 **   not updated more often than necessary. 
32370 **
32371 **   It is set to true when the change-counter field is updated, which 
32372 **   can only happen if an exclusive lock is held on the database file.
32373 **   It is cleared (set to false) whenever an exclusive lock is 
32374 **   relinquished on the database file. Each time a transaction is committed,
32375 **   The changeCountDone flag is inspected. If it is true, the work of
32376 **   updating the change-counter is omitted for the current transaction.
32377 **
32378 **   This mechanism means that when running in exclusive mode, a connection 
32379 **   need only update the change-counter once, for the first transaction
32380 **   committed.
32381 **
32382 ** dbModified
32383 **
32384 **   The dbModified flag is set whenever a database page is dirtied.
32385 **   It is cleared at the end of each transaction.
32386 **
32387 **   It is used when committing or otherwise ending a transaction. If
32388 **   the dbModified flag is clear then less work has to be done.
32389 **
32390 ** journalStarted
32391 **
32392 **   This flag is set whenever the the main journal is synced. 
32393 **
32394 **   The point of this flag is that it must be set after the 
32395 **   first journal header in a journal file has been synced to disk.
32396 **   After this has happened, new pages appended to the database 
32397 **   do not need the PGHDR_NEED_SYNC flag set, as they do not need
32398 **   to wait for a journal sync before they can be written out to
32399 **   the database file (see function pager_write()).
32400 **   
32401 ** setMaster
32402 **
32403 **   This variable is used to ensure that the master journal file name
32404 **   (if any) is only written into the journal file once.
32405 **
32406 **   When committing a transaction, the master journal file name (if any)
32407 **   may be written into the journal file while the pager is still in
32408 **   PAGER_RESERVED state (see CommitPhaseOne() for the action). It
32409 **   then attempts to upgrade to an exclusive lock. If this attempt
32410 **   fails, then SQLITE_BUSY may be returned to the user and the user
32411 **   may attempt to commit the transaction again later (calling
32412 **   CommitPhaseOne() again). This flag is used to ensure that the 
32413 **   master journal name is only written to the journal file the first
32414 **   time CommitPhaseOne() is called.
32415 **
32416 ** doNotSync
32417 **
32418 **   This variable is set and cleared by sqlite3PagerWrite().
32419 **
32420 ** needSync
32421 **
32422 **   TODO: It might be easier to set this variable in writeJournalHdr()
32423 **   and writeMasterJournal() only. Change its meaning to "unsynced data
32424 **   has been written to the journal".
32425 **
32426 ** subjInMemory
32427 **
32428 **   This is a boolean variable. If true, then any required sub-journal
32429 **   is opened as an in-memory journal file. If false, then in-memory
32430 **   sub-journals are only used for in-memory pager files.
32431 */
32432 struct Pager {
32433   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
32434   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
32435   u8 journalMode;             /* On of the PAGER_JOURNALMODE_* values */
32436   u8 useJournal;              /* Use a rollback journal on this file */
32437   u8 noReadlock;              /* Do not bother to obtain readlocks */
32438   u8 noSync;                  /* Do not sync the journal if true */
32439   u8 fullSync;                /* Do extra syncs of the journal for robustness */
32440   u8 sync_flags;              /* One of SYNC_NORMAL or SYNC_FULL */
32441   u8 tempFile;                /* zFilename is a temporary file */
32442   u8 readOnly;                /* True for a read-only database */
32443   u8 memDb;                   /* True to inhibit all file I/O */
32444
32445   /* The following block contains those class members that are dynamically
32446   ** modified during normal operations. The other variables in this structure
32447   ** are either constant throughout the lifetime of the pager, or else
32448   ** used to store configuration parameters that affect the way the pager 
32449   ** operates.
32450   **
32451   ** The 'state' variable is described in more detail along with the
32452   ** descriptions of the values it may take - PAGER_UNLOCK etc. Many of the
32453   ** other variables in this block are described in the comment directly 
32454   ** above this class definition.
32455   */
32456   u8 state;                   /* PAGER_UNLOCK, _SHARED, _RESERVED, etc. */
32457   u8 dbModified;              /* True if there are any changes to the Db */
32458   u8 needSync;                /* True if an fsync() is needed on the journal */
32459   u8 journalStarted;          /* True if header of journal is synced */
32460   u8 changeCountDone;         /* Set after incrementing the change-counter */
32461   u8 setMaster;               /* True if a m-j name has been written to jrnl */
32462   u8 doNotSync;               /* Boolean. While true, do not spill the cache */
32463   u8 dbSizeValid;             /* Set when dbSize is correct */
32464   u8 subjInMemory;            /* True to use in-memory sub-journals */
32465   Pgno dbSize;                /* Number of pages in the database */
32466   Pgno dbOrigSize;            /* dbSize before the current transaction */
32467   Pgno dbFileSize;            /* Number of pages in the database file */
32468   int errCode;                /* One of several kinds of errors */
32469   int nRec;                   /* Pages journalled since last j-header written */
32470   u32 cksumInit;              /* Quasi-random value added to every checksum */
32471   u32 nSubRec;                /* Number of records written to sub-journal */
32472   Bitvec *pInJournal;         /* One bit for each page in the database file */
32473   sqlite3_file *fd;           /* File descriptor for database */
32474   sqlite3_file *jfd;          /* File descriptor for main journal */
32475   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
32476   i64 journalOff;             /* Current write offset in the journal file */
32477   i64 journalHdr;             /* Byte offset to previous journal header */
32478   PagerSavepoint *aSavepoint; /* Array of active savepoints */
32479   int nSavepoint;             /* Number of elements in aSavepoint[] */
32480   char dbFileVers[16];        /* Changes whenever database file changes */
32481   u32 sectorSize;             /* Assumed sector size during rollback */
32482
32483   u16 nExtra;                 /* Add this many bytes to each in-memory page */
32484   i16 nReserve;               /* Number of unused bytes at end of each page */
32485   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
32486   int pageSize;               /* Number of bytes in a page */
32487   Pgno mxPgno;                /* Maximum allowed size of the database */
32488   char *zFilename;            /* Name of the database file */
32489   char *zJournal;             /* Name of the journal file */
32490   int (*xBusyHandler)(void*); /* Function to call when busy */
32491   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
32492 #ifdef SQLITE_TEST
32493   int nHit, nMiss;            /* Cache hits and missing */
32494   int nRead, nWrite;          /* Database pages read/written */
32495 #endif
32496   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
32497 #ifdef SQLITE_HAS_CODEC
32498   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
32499   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
32500   void (*xCodecFree)(void*);             /* Destructor for the codec */
32501   void *pCodec;               /* First argument to xCodec... methods */
32502 #endif
32503   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
32504   i64 journalSizeLimit;       /* Size limit for persistent journal files */
32505   PCache *pPCache;            /* Pointer to page cache object */
32506   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
32507 };
32508
32509 /*
32510 ** The following global variables hold counters used for
32511 ** testing purposes only.  These variables do not exist in
32512 ** a non-testing build.  These variables are not thread-safe.
32513 */
32514 #ifdef SQLITE_TEST
32515 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
32516 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
32517 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
32518 # define PAGER_INCR(v)  v++
32519 #else
32520 # define PAGER_INCR(v)
32521 #endif
32522
32523
32524
32525 /*
32526 ** Journal files begin with the following magic string.  The data
32527 ** was obtained from /dev/random.  It is used only as a sanity check.
32528 **
32529 ** Since version 2.8.0, the journal format contains additional sanity
32530 ** checking information.  If the power fails while the journal is being
32531 ** written, semi-random garbage data might appear in the journal
32532 ** file after power is restored.  If an attempt is then made
32533 ** to roll the journal back, the database could be corrupted.  The additional
32534 ** sanity checking data is an attempt to discover the garbage in the
32535 ** journal and ignore it.
32536 **
32537 ** The sanity checking information for the new journal format consists
32538 ** of a 32-bit checksum on each page of data.  The checksum covers both
32539 ** the page number and the pPager->pageSize bytes of data for the page.
32540 ** This cksum is initialized to a 32-bit random value that appears in the
32541 ** journal file right after the header.  The random initializer is important,
32542 ** because garbage data that appears at the end of a journal is likely
32543 ** data that was once in other files that have now been deleted.  If the
32544 ** garbage data came from an obsolete journal file, the checksums might
32545 ** be correct.  But by initializing the checksum to random value which
32546 ** is different for every journal, we minimize that risk.
32547 */
32548 static const unsigned char aJournalMagic[] = {
32549   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
32550 };
32551
32552 /*
32553 ** The size of the of each page record in the journal is given by
32554 ** the following macro.
32555 */
32556 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
32557
32558 /*
32559 ** The journal header size for this pager. This is usually the same 
32560 ** size as a single disk sector. See also setSectorSize().
32561 */
32562 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
32563
32564 /*
32565 ** The macro MEMDB is true if we are dealing with an in-memory database.
32566 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
32567 ** the value of MEMDB will be a constant and the compiler will optimize
32568 ** out code that would never execute.
32569 */
32570 #ifdef SQLITE_OMIT_MEMORYDB
32571 # define MEMDB 0
32572 #else
32573 # define MEMDB pPager->memDb
32574 #endif
32575
32576 /*
32577 ** The maximum legal page number is (2^31 - 1).
32578 */
32579 #define PAGER_MAX_PGNO 2147483647
32580
32581 #ifndef NDEBUG 
32582 /*
32583 ** Usage:
32584 **
32585 **   assert( assert_pager_state(pPager) );
32586 */
32587 static int assert_pager_state(Pager *pPager){
32588
32589   /* A temp-file is always in PAGER_EXCLUSIVE or PAGER_SYNCED state. */
32590   assert( pPager->tempFile==0 || pPager->state>=PAGER_EXCLUSIVE );
32591
32592   /* The changeCountDone flag is always set for temp-files */
32593   assert( pPager->tempFile==0 || pPager->changeCountDone );
32594
32595   return 1;
32596 }
32597 #endif
32598
32599 /*
32600 ** Return true if it is necessary to write page *pPg into the sub-journal.
32601 ** A page needs to be written into the sub-journal if there exists one
32602 ** or more open savepoints for which:
32603 **
32604 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
32605 **   * The bit corresponding to the page-number is not set in
32606 **     PagerSavepoint.pInSavepoint.
32607 */
32608 static int subjRequiresPage(PgHdr *pPg){
32609   Pgno pgno = pPg->pgno;
32610   Pager *pPager = pPg->pPager;
32611   int i;
32612   for(i=0; i<pPager->nSavepoint; i++){
32613     PagerSavepoint *p = &pPager->aSavepoint[i];
32614     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
32615       return 1;
32616     }
32617   }
32618   return 0;
32619 }
32620
32621 /*
32622 ** Return true if the page is already in the journal file.
32623 */
32624 static int pageInJournal(PgHdr *pPg){
32625   return sqlite3BitvecTest(pPg->pPager->pInJournal, pPg->pgno);
32626 }
32627
32628 /*
32629 ** Read a 32-bit integer from the given file descriptor.  Store the integer
32630 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
32631 ** error code is something goes wrong.
32632 **
32633 ** All values are stored on disk as big-endian.
32634 */
32635 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
32636   unsigned char ac[4];
32637   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
32638   if( rc==SQLITE_OK ){
32639     *pRes = sqlite3Get4byte(ac);
32640   }
32641   return rc;
32642 }
32643
32644 /*
32645 ** Write a 32-bit integer into a string buffer in big-endian byte order.
32646 */
32647 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
32648
32649 /*
32650 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
32651 ** on success or an error code is something goes wrong.
32652 */
32653 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
32654   char ac[4];
32655   put32bits(ac, val);
32656   return sqlite3OsWrite(fd, ac, 4, offset);
32657 }
32658
32659 /*
32660 ** The argument to this macro is a file descriptor (type sqlite3_file*).
32661 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
32662 **
32663 ** This is so that expressions can be written as:
32664 **
32665 **   if( isOpen(pPager->jfd) ){ ...
32666 **
32667 ** instead of
32668 **
32669 **   if( pPager->jfd->pMethods ){ ...
32670 */
32671 #define isOpen(pFd) ((pFd)->pMethods)
32672
32673 /*
32674 ** If file pFd is open, call sqlite3OsUnlock() on it.
32675 */
32676 static int osUnlock(sqlite3_file *pFd, int eLock){
32677   if( !isOpen(pFd) ){
32678     return SQLITE_OK;
32679   }
32680   return sqlite3OsUnlock(pFd, eLock);
32681 }
32682
32683 /*
32684 ** This function determines whether or not the atomic-write optimization
32685 ** can be used with this pager. The optimization can be used if:
32686 **
32687 **  (a) the value returned by OsDeviceCharacteristics() indicates that
32688 **      a database page may be written atomically, and
32689 **  (b) the value returned by OsSectorSize() is less than or equal
32690 **      to the page size.
32691 **
32692 ** The optimization is also always enabled for temporary files. It is
32693 ** an error to call this function if pPager is opened on an in-memory
32694 ** database.
32695 **
32696 ** If the optimization cannot be used, 0 is returned. If it can be used,
32697 ** then the value returned is the size of the journal file when it
32698 ** contains rollback data for exactly one page.
32699 */
32700 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
32701 static int jrnlBufferSize(Pager *pPager){
32702   assert( !MEMDB );
32703   if( !pPager->tempFile ){
32704     int dc;                           /* Device characteristics */
32705     int nSector;                      /* Sector size */
32706     int szPage;                       /* Page size */
32707
32708     assert( isOpen(pPager->fd) );
32709     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
32710     nSector = pPager->sectorSize;
32711     szPage = pPager->pageSize;
32712
32713     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
32714     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
32715     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
32716       return 0;
32717     }
32718   }
32719
32720   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
32721 }
32722 #endif
32723
32724 /*
32725 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
32726 ** on the cache using a hash function.  This is used for testing
32727 ** and debugging only.
32728 */
32729 #ifdef SQLITE_CHECK_PAGES
32730 /*
32731 ** Return a 32-bit hash of the page data for pPage.
32732 */
32733 static u32 pager_datahash(int nByte, unsigned char *pData){
32734   u32 hash = 0;
32735   int i;
32736   for(i=0; i<nByte; i++){
32737     hash = (hash*1039) + pData[i];
32738   }
32739   return hash;
32740 }
32741 static u32 pager_pagehash(PgHdr *pPage){
32742   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
32743 }
32744 static void pager_set_pagehash(PgHdr *pPage){
32745   pPage->pageHash = pager_pagehash(pPage);
32746 }
32747
32748 /*
32749 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
32750 ** is defined, and NDEBUG is not defined, an assert() statement checks
32751 ** that the page is either dirty or still matches the calculated page-hash.
32752 */
32753 #define CHECK_PAGE(x) checkPage(x)
32754 static void checkPage(PgHdr *pPg){
32755   Pager *pPager = pPg->pPager;
32756   assert( !pPg->pageHash || pPager->errCode
32757       || (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
32758 }
32759
32760 #else
32761 #define pager_datahash(X,Y)  0
32762 #define pager_pagehash(X)  0
32763 #define CHECK_PAGE(x)
32764 #endif  /* SQLITE_CHECK_PAGES */
32765
32766 /*
32767 ** When this is called the journal file for pager pPager must be open.
32768 ** This function attempts to read a master journal file name from the 
32769 ** end of the file and, if successful, copies it into memory supplied 
32770 ** by the caller. See comments above writeMasterJournal() for the format
32771 ** used to store a master journal file name at the end of a journal file.
32772 **
32773 ** zMaster must point to a buffer of at least nMaster bytes allocated by
32774 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
32775 ** enough space to write the master journal name). If the master journal
32776 ** name in the journal is longer than nMaster bytes (including a
32777 ** nul-terminator), then this is handled as if no master journal name
32778 ** were present in the journal.
32779 **
32780 ** If a master journal file name is present at the end of the journal
32781 ** file, then it is copied into the buffer pointed to by zMaster. A
32782 ** nul-terminator byte is appended to the buffer following the master
32783 ** journal file name.
32784 **
32785 ** If it is determined that no master journal file name is present 
32786 ** zMaster[0] is set to 0 and SQLITE_OK returned.
32787 **
32788 ** If an error occurs while reading from the journal file, an SQLite
32789 ** error code is returned.
32790 */
32791 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
32792   int rc;                    /* Return code */
32793   u32 len;                   /* Length in bytes of master journal name */
32794   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
32795   u32 cksum;                 /* MJ checksum value read from journal */
32796   u32 u;                     /* Unsigned loop counter */
32797   unsigned char aMagic[8];   /* A buffer to hold the magic header */
32798   zMaster[0] = '\0';
32799
32800   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
32801    || szJ<16
32802    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
32803    || len>=nMaster 
32804    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
32805    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
32806    || memcmp(aMagic, aJournalMagic, 8)
32807    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
32808   ){
32809     return rc;
32810   }
32811
32812   /* See if the checksum matches the master journal name */
32813   for(u=0; u<len; u++){
32814     cksum -= zMaster[u];
32815   }
32816   if( cksum ){
32817     /* If the checksum doesn't add up, then one or more of the disk sectors
32818     ** containing the master journal filename is corrupted. This means
32819     ** definitely roll back, so just return SQLITE_OK and report a (nul)
32820     ** master-journal filename.
32821     */
32822     len = 0;
32823   }
32824   zMaster[len] = '\0';
32825    
32826   return SQLITE_OK;
32827 }
32828
32829 /*
32830 ** Return the offset of the sector boundary at or immediately 
32831 ** following the value in pPager->journalOff, assuming a sector 
32832 ** size of pPager->sectorSize bytes.
32833 **
32834 ** i.e for a sector size of 512:
32835 **
32836 **   Pager.journalOff          Return value
32837 **   ---------------------------------------
32838 **   0                         0
32839 **   512                       512
32840 **   100                       512
32841 **   2000                      2048
32842 ** 
32843 */
32844 static i64 journalHdrOffset(Pager *pPager){
32845   i64 offset = 0;
32846   i64 c = pPager->journalOff;
32847   if( c ){
32848     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
32849   }
32850   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
32851   assert( offset>=c );
32852   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
32853   return offset;
32854 }
32855
32856 /*
32857 ** The journal file must be open when this function is called.
32858 **
32859 ** This function is a no-op if the journal file has not been written to
32860 ** within the current transaction (i.e. if Pager.journalOff==0).
32861 **
32862 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
32863 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
32864 ** zero the 28-byte header at the start of the journal file. In either case, 
32865 ** if the pager is not in no-sync mode, sync the journal file immediately 
32866 ** after writing or truncating it.
32867 **
32868 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
32869 ** following the truncation or zeroing described above the size of the 
32870 ** journal file in bytes is larger than this value, then truncate the
32871 ** journal file to Pager.journalSizeLimit bytes. The journal file does
32872 ** not need to be synced following this operation.
32873 **
32874 ** If an IO error occurs, abandon processing and return the IO error code.
32875 ** Otherwise, return SQLITE_OK.
32876 */
32877 static int zeroJournalHdr(Pager *pPager, int doTruncate){
32878   int rc = SQLITE_OK;                               /* Return code */
32879   assert( isOpen(pPager->jfd) );
32880   if( pPager->journalOff ){
32881     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
32882
32883     IOTRACE(("JZEROHDR %p\n", pPager))
32884     if( doTruncate || iLimit==0 ){
32885       rc = sqlite3OsTruncate(pPager->jfd, 0);
32886     }else{
32887       static const char zeroHdr[28] = {0};
32888       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
32889     }
32890     if( rc==SQLITE_OK && !pPager->noSync ){
32891       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->sync_flags);
32892     }
32893
32894     /* At this point the transaction is committed but the write lock 
32895     ** is still held on the file. If there is a size limit configured for 
32896     ** the persistent journal and the journal file currently consumes more
32897     ** space than that limit allows for, truncate it now. There is no need
32898     ** to sync the file following this operation.
32899     */
32900     if( rc==SQLITE_OK && iLimit>0 ){
32901       i64 sz;
32902       rc = sqlite3OsFileSize(pPager->jfd, &sz);
32903       if( rc==SQLITE_OK && sz>iLimit ){
32904         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
32905       }
32906     }
32907   }
32908   return rc;
32909 }
32910
32911 /*
32912 ** The journal file must be open when this routine is called. A journal
32913 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
32914 ** current location.
32915 **
32916 ** The format for the journal header is as follows:
32917 ** - 8 bytes: Magic identifying journal format.
32918 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
32919 ** - 4 bytes: Random number used for page hash.
32920 ** - 4 bytes: Initial database page count.
32921 ** - 4 bytes: Sector size used by the process that wrote this journal.
32922 ** - 4 bytes: Database page size.
32923 ** 
32924 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
32925 */
32926 static int writeJournalHdr(Pager *pPager){
32927   int rc = SQLITE_OK;                 /* Return code */
32928   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
32929   u32 nHeader = pPager->pageSize;     /* Size of buffer pointed to by zHeader */
32930   u32 nWrite;                         /* Bytes of header sector written */
32931   int ii;                             /* Loop counter */
32932
32933   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
32934
32935   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
32936     nHeader = JOURNAL_HDR_SZ(pPager);
32937   }
32938
32939   /* If there are active savepoints and any of them were created 
32940   ** since the most recent journal header was written, update the 
32941   ** PagerSavepoint.iHdrOffset fields now.
32942   */
32943   for(ii=0; ii<pPager->nSavepoint; ii++){
32944     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
32945       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
32946     }
32947   }
32948
32949   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
32950
32951   /* 
32952   ** Write the nRec Field - the number of page records that follow this
32953   ** journal header. Normally, zero is written to this value at this time.
32954   ** After the records are added to the journal (and the journal synced, 
32955   ** if in full-sync mode), the zero is overwritten with the true number
32956   ** of records (see syncJournal()).
32957   **
32958   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
32959   ** reading the journal this value tells SQLite to assume that the
32960   ** rest of the journal file contains valid page records. This assumption
32961   ** is dangerous, as if a failure occurred whilst writing to the journal
32962   ** file it may contain some garbage data. There are two scenarios
32963   ** where this risk can be ignored:
32964   **
32965   **   * When the pager is in no-sync mode. Corruption can follow a
32966   **     power failure in this case anyway.
32967   **
32968   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
32969   **     that garbage data is never appended to the journal file.
32970   */
32971   assert( isOpen(pPager->fd) || pPager->noSync );
32972   if( (pPager->noSync) || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
32973    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
32974   ){
32975     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
32976     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
32977   }else{
32978     memset(zHeader, 0, sizeof(aJournalMagic)+4);
32979   }
32980
32981   /* The random check-hash initialiser */ 
32982   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
32983   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
32984   /* The initial database size */
32985   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
32986   /* The assumed sector size for this process */
32987   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
32988
32989   /* The page size */
32990   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
32991
32992   /* Initializing the tail of the buffer is not necessary.  Everything
32993   ** works find if the following memset() is omitted.  But initializing
32994   ** the memory prevents valgrind from complaining, so we are willing to
32995   ** take the performance hit.
32996   */
32997   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
32998          nHeader-(sizeof(aJournalMagic)+20));
32999
33000   /* In theory, it is only necessary to write the 28 bytes that the 
33001   ** journal header consumes to the journal file here. Then increment the 
33002   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
33003   ** record is written to the following sector (leaving a gap in the file
33004   ** that will be implicitly filled in by the OS).
33005   **
33006   ** However it has been discovered that on some systems this pattern can 
33007   ** be significantly slower than contiguously writing data to the file,
33008   ** even if that means explicitly writing data to the block of 
33009   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
33010   ** is done. 
33011   **
33012   ** The loop is required here in case the sector-size is larger than the 
33013   ** database page size. Since the zHeader buffer is only Pager.pageSize
33014   ** bytes in size, more than one call to sqlite3OsWrite() may be required
33015   ** to populate the entire journal header sector.
33016   */ 
33017   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
33018     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
33019     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
33020     pPager->journalOff += nHeader;
33021   }
33022
33023   return rc;
33024 }
33025
33026 /*
33027 ** The journal file must be open when this is called. A journal header file
33028 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
33029 ** file. The current location in the journal file is given by
33030 ** pPager->journalOff. See comments above function writeJournalHdr() for
33031 ** a description of the journal header format.
33032 **
33033 ** If the header is read successfully, *pNRec is set to the number of
33034 ** page records following this header and *pDbSize is set to the size of the
33035 ** database before the transaction began, in pages. Also, pPager->cksumInit
33036 ** is set to the value read from the journal header. SQLITE_OK is returned
33037 ** in this case.
33038 **
33039 ** If the journal header file appears to be corrupted, SQLITE_DONE is
33040 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
33041 ** cannot be read from the journal file an error code is returned.
33042 */
33043 static int readJournalHdr(
33044   Pager *pPager,               /* Pager object */
33045   int isHot,
33046   i64 journalSize,             /* Size of the open journal file in bytes */
33047   u32 *pNRec,                  /* OUT: Value read from the nRec field */
33048   u32 *pDbSize                 /* OUT: Value of original database size field */
33049 ){
33050   int rc;                      /* Return code */
33051   unsigned char aMagic[8];     /* A buffer to hold the magic header */
33052   i64 iHdrOff;                 /* Offset of journal header being read */
33053
33054   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
33055
33056   /* Advance Pager.journalOff to the start of the next sector. If the
33057   ** journal file is too small for there to be a header stored at this
33058   ** point, return SQLITE_DONE.
33059   */
33060   pPager->journalOff = journalHdrOffset(pPager);
33061   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
33062     return SQLITE_DONE;
33063   }
33064   iHdrOff = pPager->journalOff;
33065
33066   /* Read in the first 8 bytes of the journal header. If they do not match
33067   ** the  magic string found at the start of each journal header, return
33068   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
33069   ** proceed.
33070   */
33071   if( isHot || iHdrOff!=pPager->journalHdr ){
33072     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
33073     if( rc ){
33074       return rc;
33075     }
33076     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
33077       return SQLITE_DONE;
33078     }
33079   }
33080
33081   /* Read the first three 32-bit fields of the journal header: The nRec
33082   ** field, the checksum-initializer and the database size at the start
33083   ** of the transaction. Return an error code if anything goes wrong.
33084   */
33085   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
33086    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
33087    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
33088   ){
33089     return rc;
33090   }
33091
33092   if( pPager->journalOff==0 ){
33093     u32 iPageSize;               /* Page-size field of journal header */
33094     u32 iSectorSize;             /* Sector-size field of journal header */
33095     u16 iPageSize16;             /* Copy of iPageSize in 16-bit variable */
33096
33097     /* Read the page-size and sector-size journal header fields. */
33098     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
33099      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
33100     ){
33101       return rc;
33102     }
33103
33104     /* Check that the values read from the page-size and sector-size fields
33105     ** are within range. To be 'in range', both values need to be a power
33106     ** of two greater than or equal to 512 or 32, and not greater than their 
33107     ** respective compile time maximum limits.
33108     */
33109     if( iPageSize<512                  || iSectorSize<32
33110      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
33111      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
33112     ){
33113       /* If the either the page-size or sector-size in the journal-header is 
33114       ** invalid, then the process that wrote the journal-header must have 
33115       ** crashed before the header was synced. In this case stop reading 
33116       ** the journal file here.
33117       */
33118       return SQLITE_DONE;
33119     }
33120
33121     /* Update the page-size to match the value read from the journal. 
33122     ** Use a testcase() macro to make sure that malloc failure within 
33123     ** PagerSetPagesize() is tested.
33124     */
33125     iPageSize16 = (u16)iPageSize;
33126     rc = sqlite3PagerSetPagesize(pPager, &iPageSize16, -1);
33127     testcase( rc!=SQLITE_OK );
33128     assert( rc!=SQLITE_OK || iPageSize16==(u16)iPageSize );
33129
33130     /* Update the assumed sector-size to match the value used by 
33131     ** the process that created this journal. If this journal was
33132     ** created by a process other than this one, then this routine
33133     ** is being called from within pager_playback(). The local value
33134     ** of Pager.sectorSize is restored at the end of that routine.
33135     */
33136     pPager->sectorSize = iSectorSize;
33137   }
33138
33139   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
33140   return rc;
33141 }
33142
33143
33144 /*
33145 ** Write the supplied master journal name into the journal file for pager
33146 ** pPager at the current location. The master journal name must be the last
33147 ** thing written to a journal file. If the pager is in full-sync mode, the
33148 ** journal file descriptor is advanced to the next sector boundary before
33149 ** anything is written. The format is:
33150 **
33151 **   + 4 bytes: PAGER_MJ_PGNO.
33152 **   + N bytes: Master journal filename in utf-8.
33153 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
33154 **   + 4 bytes: Master journal name checksum.
33155 **   + 8 bytes: aJournalMagic[].
33156 **
33157 ** The master journal page checksum is the sum of the bytes in the master
33158 ** journal name, where each byte is interpreted as a signed 8-bit integer.
33159 **
33160 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
33161 ** this call is a no-op.
33162 */
33163 static int writeMasterJournal(Pager *pPager, const char *zMaster){
33164   int rc;                          /* Return code */
33165   int nMaster;                     /* Length of string zMaster */
33166   i64 iHdrOff;                     /* Offset of header in journal file */
33167   i64 jrnlSize;                    /* Size of journal file on disk */
33168   u32 cksum = 0;                   /* Checksum of string zMaster */
33169
33170   if( !zMaster || pPager->setMaster
33171    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
33172    || pPager->journalMode==PAGER_JOURNALMODE_OFF 
33173   ){
33174     return SQLITE_OK;
33175   }
33176   pPager->setMaster = 1;
33177   assert( isOpen(pPager->jfd) );
33178
33179   /* Calculate the length in bytes and the checksum of zMaster */
33180   for(nMaster=0; zMaster[nMaster]; nMaster++){
33181     cksum += zMaster[nMaster];
33182   }
33183
33184   /* If in full-sync mode, advance to the next disk sector before writing
33185   ** the master journal name. This is in case the previous page written to
33186   ** the journal has already been synced.
33187   */
33188   if( pPager->fullSync ){
33189     pPager->journalOff = journalHdrOffset(pPager);
33190   }
33191   iHdrOff = pPager->journalOff;
33192
33193   /* Write the master journal data to the end of the journal file. If
33194   ** an error occurs, return the error code to the caller.
33195   */
33196   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
33197    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
33198    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
33199    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
33200    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
33201   ){
33202     return rc;
33203   }
33204   pPager->journalOff += (nMaster+20);
33205   pPager->needSync = !pPager->noSync;
33206
33207   /* If the pager is in peristent-journal mode, then the physical 
33208   ** journal-file may extend past the end of the master-journal name
33209   ** and 8 bytes of magic data just written to the file. This is 
33210   ** dangerous because the code to rollback a hot-journal file
33211   ** will not be able to find the master-journal name to determine 
33212   ** whether or not the journal is hot. 
33213   **
33214   ** Easiest thing to do in this scenario is to truncate the journal 
33215   ** file to the required size.
33216   */ 
33217   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
33218    && jrnlSize>pPager->journalOff
33219   ){
33220     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
33221   }
33222   return rc;
33223 }
33224
33225 /*
33226 ** Find a page in the hash table given its page number. Return
33227 ** a pointer to the page or NULL if the requested page is not 
33228 ** already in memory.
33229 */
33230 static PgHdr *pager_lookup(Pager *pPager, Pgno pgno){
33231   PgHdr *p;                         /* Return value */
33232
33233   /* It is not possible for a call to PcacheFetch() with createFlag==0 to
33234   ** fail, since no attempt to allocate dynamic memory will be made.
33235   */
33236   (void)sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &p);
33237   return p;
33238 }
33239
33240 /*
33241 ** Unless the pager is in error-state, discard all in-memory pages. If
33242 ** the pager is in error-state, then this call is a no-op.
33243 **
33244 ** TODO: Why can we not reset the pager while in error state?
33245 */
33246 static void pager_reset(Pager *pPager){
33247   if( SQLITE_OK==pPager->errCode ){
33248     sqlite3BackupRestart(pPager->pBackup);
33249     sqlite3PcacheClear(pPager->pPCache);
33250     pPager->dbSizeValid = 0;
33251   }
33252 }
33253
33254 /*
33255 ** Free all structures in the Pager.aSavepoint[] array and set both
33256 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
33257 ** if it is open and the pager is not in exclusive mode.
33258 */
33259 static void releaseAllSavepoints(Pager *pPager){
33260   int ii;               /* Iterator for looping through Pager.aSavepoint */
33261   for(ii=0; ii<pPager->nSavepoint; ii++){
33262     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
33263   }
33264   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
33265     sqlite3OsClose(pPager->sjfd);
33266   }
33267   sqlite3_free(pPager->aSavepoint);
33268   pPager->aSavepoint = 0;
33269   pPager->nSavepoint = 0;
33270   pPager->nSubRec = 0;
33271 }
33272
33273 /*
33274 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
33275 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
33276 ** or SQLITE_NOMEM if a malloc failure occurs.
33277 */
33278 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
33279   int ii;                   /* Loop counter */
33280   int rc = SQLITE_OK;       /* Result code */
33281
33282   for(ii=0; ii<pPager->nSavepoint; ii++){
33283     PagerSavepoint *p = &pPager->aSavepoint[ii];
33284     if( pgno<=p->nOrig ){
33285       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
33286       testcase( rc==SQLITE_NOMEM );
33287       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
33288     }
33289   }
33290   return rc;
33291 }
33292
33293 /*
33294 ** Unlock the database file. This function is a no-op if the pager
33295 ** is in exclusive mode.
33296 **
33297 ** If the pager is currently in error state, discard the contents of 
33298 ** the cache and reset the Pager structure internal state. If there is
33299 ** an open journal-file, then the next time a shared-lock is obtained
33300 ** on the pager file (by this or any other process), it will be
33301 ** treated as a hot-journal and rolled back.
33302 */
33303 static void pager_unlock(Pager *pPager){
33304   if( !pPager->exclusiveMode ){
33305     int rc;                      /* Return code */
33306
33307     /* Always close the journal file when dropping the database lock.
33308     ** Otherwise, another connection with journal_mode=delete might
33309     ** delete the file out from under us.
33310     */
33311     sqlite3OsClose(pPager->jfd);
33312     sqlite3BitvecDestroy(pPager->pInJournal);
33313     pPager->pInJournal = 0;
33314     releaseAllSavepoints(pPager);
33315
33316     /* If the file is unlocked, somebody else might change it. The
33317     ** values stored in Pager.dbSize etc. might become invalid if
33318     ** this happens. TODO: Really, this doesn't need to be cleared
33319     ** until the change-counter check fails in PagerSharedLock().
33320     */
33321     pPager->dbSizeValid = 0;
33322
33323     rc = osUnlock(pPager->fd, NO_LOCK);
33324     if( rc ){
33325       pPager->errCode = rc;
33326     }
33327     IOTRACE(("UNLOCK %p\n", pPager))
33328
33329     /* If Pager.errCode is set, the contents of the pager cache cannot be
33330     ** trusted. Now that the pager file is unlocked, the contents of the
33331     ** cache can be discarded and the error code safely cleared.
33332     */
33333     if( pPager->errCode ){
33334       if( rc==SQLITE_OK ){
33335         pPager->errCode = SQLITE_OK;
33336       }
33337       pager_reset(pPager);
33338     }
33339
33340     pPager->changeCountDone = 0;
33341     pPager->state = PAGER_UNLOCK;
33342     pPager->dbModified = 0;
33343   }
33344 }
33345
33346 /*
33347 ** This function should be called when an IOERR, CORRUPT or FULL error
33348 ** may have occurred. The first argument is a pointer to the pager 
33349 ** structure, the second the error-code about to be returned by a pager 
33350 ** API function. The value returned is a copy of the second argument 
33351 ** to this function. 
33352 **
33353 ** If the second argument is SQLITE_IOERR, SQLITE_CORRUPT, or SQLITE_FULL
33354 ** the error becomes persistent. Until the persisten error is cleared,
33355 ** subsequent API calls on this Pager will immediately return the same 
33356 ** error code.
33357 **
33358 ** A persistent error indicates that the contents of the pager-cache 
33359 ** cannot be trusted. This state can be cleared by completely discarding 
33360 ** the contents of the pager-cache. If a transaction was active when
33361 ** the persistent error occurred, then the rollback journal may need
33362 ** to be replayed to restore the contents of the database file (as if
33363 ** it were a hot-journal).
33364 */
33365 static int pager_error(Pager *pPager, int rc){
33366   int rc2 = rc & 0xff;
33367   assert( rc==SQLITE_OK || !MEMDB );
33368   assert(
33369        pPager->errCode==SQLITE_FULL ||
33370        pPager->errCode==SQLITE_OK ||
33371        (pPager->errCode & 0xff)==SQLITE_IOERR
33372   );
33373   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
33374     pPager->errCode = rc;
33375   }
33376   return rc;
33377 }
33378
33379 /*
33380 ** Execute a rollback if a transaction is active and unlock the 
33381 ** database file. 
33382 **
33383 ** If the pager has already entered the error state, do not attempt 
33384 ** the rollback at this time. Instead, pager_unlock() is called. The
33385 ** call to pager_unlock() will discard all in-memory pages, unlock
33386 ** the database file and clear the error state. If this means that
33387 ** there is a hot-journal left in the file-system, the next connection
33388 ** to obtain a shared lock on the pager (which may be this one) will
33389 ** roll it back.
33390 **
33391 ** If the pager has not already entered the error state, but an IO or
33392 ** malloc error occurs during a rollback, then this will itself cause 
33393 ** the pager to enter the error state. Which will be cleared by the
33394 ** call to pager_unlock(), as described above.
33395 */
33396 static void pagerUnlockAndRollback(Pager *pPager){
33397   if( pPager->errCode==SQLITE_OK && pPager->state>=PAGER_RESERVED ){
33398     sqlite3BeginBenignMalloc();
33399     sqlite3PagerRollback(pPager);
33400     sqlite3EndBenignMalloc();
33401   }
33402   pager_unlock(pPager);
33403 }
33404
33405 /*
33406 ** This routine ends a transaction. A transaction is usually ended by 
33407 ** either a COMMIT or a ROLLBACK operation. This routine may be called 
33408 ** after rollback of a hot-journal, or if an error occurs while opening
33409 ** the journal file or writing the very first journal-header of a
33410 ** database transaction.
33411 ** 
33412 ** If the pager is in PAGER_SHARED or PAGER_UNLOCK state when this
33413 ** routine is called, it is a no-op (returns SQLITE_OK).
33414 **
33415 ** Otherwise, any active savepoints are released.
33416 **
33417 ** If the journal file is open, then it is "finalized". Once a journal 
33418 ** file has been finalized it is not possible to use it to roll back a 
33419 ** transaction. Nor will it be considered to be a hot-journal by this
33420 ** or any other database connection. Exactly how a journal is finalized
33421 ** depends on whether or not the pager is running in exclusive mode and
33422 ** the current journal-mode (Pager.journalMode value), as follows:
33423 **
33424 **   journalMode==MEMORY
33425 **     Journal file descriptor is simply closed. This destroys an 
33426 **     in-memory journal.
33427 **
33428 **   journalMode==TRUNCATE
33429 **     Journal file is truncated to zero bytes in size.
33430 **
33431 **   journalMode==PERSIST
33432 **     The first 28 bytes of the journal file are zeroed. This invalidates
33433 **     the first journal header in the file, and hence the entire journal
33434 **     file. An invalid journal file cannot be rolled back.
33435 **
33436 **   journalMode==DELETE
33437 **     The journal file is closed and deleted using sqlite3OsDelete().
33438 **
33439 **     If the pager is running in exclusive mode, this method of finalizing
33440 **     the journal file is never used. Instead, if the journalMode is
33441 **     DELETE and the pager is in exclusive mode, the method described under
33442 **     journalMode==PERSIST is used instead.
33443 **
33444 ** After the journal is finalized, if running in non-exclusive mode, the
33445 ** pager moves to PAGER_SHARED state (and downgrades the lock on the
33446 ** database file accordingly).
33447 **
33448 ** If the pager is running in exclusive mode and is in PAGER_SYNCED state,
33449 ** it moves to PAGER_EXCLUSIVE. No locks are downgraded when running in
33450 ** exclusive mode.
33451 **
33452 ** SQLITE_OK is returned if no error occurs. If an error occurs during
33453 ** any of the IO operations to finalize the journal file or unlock the
33454 ** database then the IO error code is returned to the user. If the 
33455 ** operation to finalize the journal file fails, then the code still
33456 ** tries to unlock the database file if not in exclusive mode. If the
33457 ** unlock operation fails as well, then the first error code related
33458 ** to the first error encountered (the journal finalization one) is
33459 ** returned.
33460 */
33461 static int pager_end_transaction(Pager *pPager, int hasMaster){
33462   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
33463   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
33464
33465   if( pPager->state<PAGER_RESERVED ){
33466     return SQLITE_OK;
33467   }
33468   releaseAllSavepoints(pPager);
33469
33470   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
33471   if( isOpen(pPager->jfd) ){
33472
33473     /* Finalize the journal file. */
33474     if( sqlite3IsMemJournal(pPager->jfd) ){
33475       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
33476       sqlite3OsClose(pPager->jfd);
33477     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
33478       if( pPager->journalOff==0 ){
33479         rc = SQLITE_OK;
33480       }else{
33481         rc = sqlite3OsTruncate(pPager->jfd, 0);
33482       }
33483       pPager->journalOff = 0;
33484       pPager->journalStarted = 0;
33485     }else if( pPager->exclusiveMode 
33486      || pPager->journalMode==PAGER_JOURNALMODE_PERSIST
33487     ){
33488       rc = zeroJournalHdr(pPager, hasMaster);
33489       pager_error(pPager, rc);
33490       pPager->journalOff = 0;
33491       pPager->journalStarted = 0;
33492     }else{
33493       /* This branch may be executed with Pager.journalMode==MEMORY if
33494       ** a hot-journal was just rolled back. In this case the journal
33495       ** file should be closed and deleted. If this connection writes to
33496       ** the database file, it will do so using an in-memory journal.  */
33497       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
33498            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
33499       );
33500       sqlite3OsClose(pPager->jfd);
33501       if( !pPager->tempFile ){
33502         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
33503       }
33504     }
33505
33506 #ifdef SQLITE_CHECK_PAGES
33507     sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
33508 #endif
33509
33510     sqlite3PcacheCleanAll(pPager->pPCache);
33511     sqlite3BitvecDestroy(pPager->pInJournal);
33512     pPager->pInJournal = 0;
33513     pPager->nRec = 0;
33514   }
33515
33516   if( !pPager->exclusiveMode ){
33517     rc2 = osUnlock(pPager->fd, SHARED_LOCK);
33518     pPager->state = PAGER_SHARED;
33519     pPager->changeCountDone = 0;
33520   }else if( pPager->state==PAGER_SYNCED ){
33521     pPager->state = PAGER_EXCLUSIVE;
33522   }
33523   pPager->setMaster = 0;
33524   pPager->needSync = 0;
33525   pPager->dbModified = 0;
33526
33527   /* TODO: Is this optimal? Why is the db size invalidated here 
33528   ** when the database file is not unlocked? */
33529   pPager->dbOrigSize = 0;
33530   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
33531   if( !MEMDB ){
33532     pPager->dbSizeValid = 0;
33533   }
33534
33535   return (rc==SQLITE_OK?rc2:rc);
33536 }
33537
33538 /*
33539 ** Parameter aData must point to a buffer of pPager->pageSize bytes
33540 ** of data. Compute and return a checksum based ont the contents of the 
33541 ** page of data and the current value of pPager->cksumInit.
33542 **
33543 ** This is not a real checksum. It is really just the sum of the 
33544 ** random initial value (pPager->cksumInit) and every 200th byte
33545 ** of the page data, starting with byte offset (pPager->pageSize%200).
33546 ** Each byte is interpreted as an 8-bit unsigned integer.
33547 **
33548 ** Changing the formula used to compute this checksum results in an
33549 ** incompatible journal file format.
33550 **
33551 ** If journal corruption occurs due to a power failure, the most likely 
33552 ** scenario is that one end or the other of the record will be changed. 
33553 ** It is much less likely that the two ends of the journal record will be
33554 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
33555 ** though fast and simple, catches the mostly likely kind of corruption.
33556 */
33557 static u32 pager_cksum(Pager *pPager, const u8 *aData){
33558   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
33559   int i = pPager->pageSize-200;          /* Loop counter */
33560   while( i>0 ){
33561     cksum += aData[i];
33562     i -= 200;
33563   }
33564   return cksum;
33565 }
33566
33567 /*
33568 ** Read a single page from either the journal file (if isMainJrnl==1) or
33569 ** from the sub-journal (if isMainJrnl==0) and playback that page.
33570 ** The page begins at offset *pOffset into the file. The *pOffset
33571 ** value is increased to the start of the next page in the journal.
33572 **
33573 ** The isMainJrnl flag is true if this is the main rollback journal and
33574 ** false for the statement journal.  The main rollback journal uses
33575 ** checksums - the statement journal does not.
33576 **
33577 ** If the page number of the page record read from the (sub-)journal file
33578 ** is greater than the current value of Pager.dbSize, then playback is
33579 ** skipped and SQLITE_OK is returned.
33580 **
33581 ** If pDone is not NULL, then it is a record of pages that have already
33582 ** been played back.  If the page at *pOffset has already been played back
33583 ** (if the corresponding pDone bit is set) then skip the playback.
33584 ** Make sure the pDone bit corresponding to the *pOffset page is set
33585 ** prior to returning.
33586 **
33587 ** If the page record is successfully read from the (sub-)journal file
33588 ** and played back, then SQLITE_OK is returned. If an IO error occurs
33589 ** while reading the record from the (sub-)journal file or while writing
33590 ** to the database file, then the IO error code is returned. If data
33591 ** is successfully read from the (sub-)journal file but appears to be
33592 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
33593 ** two circumstances:
33594 ** 
33595 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
33596 **   * If the record is being rolled back from the main journal file
33597 **     and the checksum field does not match the record content.
33598 **
33599 ** Neither of these two scenarios are possible during a savepoint rollback.
33600 **
33601 ** If this is a savepoint rollback, then memory may have to be dynamically
33602 ** allocated by this function. If this is the case and an allocation fails,
33603 ** SQLITE_NOMEM is returned.
33604 */
33605 static int pager_playback_one_page(
33606   Pager *pPager,                /* The pager being played back */
33607   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
33608   int isUnsync,                 /* True if reading from unsynced main journal */
33609   i64 *pOffset,                 /* Offset of record to playback */
33610   int isSavepnt,                /* True for a savepoint rollback */
33611   Bitvec *pDone                 /* Bitvec of pages already played back */
33612 ){
33613   int rc;
33614   PgHdr *pPg;                   /* An existing page in the cache */
33615   Pgno pgno;                    /* The page number of a page in journal */
33616   u32 cksum;                    /* Checksum used for sanity checking */
33617   char *aData;                  /* Temporary storage for the page */
33618   sqlite3_file *jfd;            /* The file descriptor for the journal file */
33619
33620   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
33621   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
33622   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
33623   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
33624
33625   aData = pPager->pTmpSpace;
33626   assert( aData );         /* Temp storage must have already been allocated */
33627
33628   /* Read the page number and page data from the journal or sub-journal
33629   ** file. Return an error code to the caller if an IO error occurs.
33630   */
33631   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
33632   rc = read32bits(jfd, *pOffset, &pgno);
33633   if( rc!=SQLITE_OK ) return rc;
33634   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
33635   if( rc!=SQLITE_OK ) return rc;
33636   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
33637
33638   /* Sanity checking on the page.  This is more important that I originally
33639   ** thought.  If a power failure occurs while the journal is being written,
33640   ** it could cause invalid data to be written into the journal.  We need to
33641   ** detect this invalid data (with high probability) and ignore it.
33642   */
33643   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
33644     assert( !isSavepnt );
33645     return SQLITE_DONE;
33646   }
33647   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
33648     return SQLITE_OK;
33649   }
33650   if( isMainJrnl ){
33651     rc = read32bits(jfd, (*pOffset)-4, &cksum);
33652     if( rc ) return rc;
33653     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
33654       return SQLITE_DONE;
33655     }
33656   }
33657
33658   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
33659     return rc;
33660   }
33661
33662   assert( pPager->state==PAGER_RESERVED || pPager->state>=PAGER_EXCLUSIVE );
33663
33664   /* If the pager is in RESERVED state, then there must be a copy of this
33665   ** page in the pager cache. In this case just update the pager cache,
33666   ** not the database file. The page is left marked dirty in this case.
33667   **
33668   ** An exception to the above rule: If the database is in no-sync mode
33669   ** and a page is moved during an incremental vacuum then the page may
33670   ** not be in the pager cache. Later: if a malloc() or IO error occurs
33671   ** during a Movepage() call, then the page may not be in the cache
33672   ** either. So the condition described in the above paragraph is not
33673   ** assert()able.
33674   **
33675   ** If in EXCLUSIVE state, then we update the pager cache if it exists
33676   ** and the main file. The page is then marked not dirty.
33677   **
33678   ** Ticket #1171:  The statement journal might contain page content that is
33679   ** different from the page content at the start of the transaction.
33680   ** This occurs when a page is changed prior to the start of a statement
33681   ** then changed again within the statement.  When rolling back such a
33682   ** statement we must not write to the original database unless we know
33683   ** for certain that original page contents are synced into the main rollback
33684   ** journal.  Otherwise, a power loss might leave modified data in the
33685   ** database file without an entry in the rollback journal that can
33686   ** restore the database to its original form.  Two conditions must be
33687   ** met before writing to the database files. (1) the database must be
33688   ** locked.  (2) we know that the original page content is fully synced
33689   ** in the main journal either because the page is not in cache or else
33690   ** the page is marked as needSync==0.
33691   **
33692   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
33693   ** is possible to fail a statement on a database that does not yet exist.
33694   ** Do not attempt to write if database file has never been opened.
33695   */
33696   pPg = pager_lookup(pPager, pgno);
33697   assert( pPg || !MEMDB );
33698   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
33699            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
33700            (isMainJrnl?"main-journal":"sub-journal")
33701   ));
33702   if( (pPager->state>=PAGER_EXCLUSIVE)
33703    && (pPg==0 || 0==(pPg->flags&PGHDR_NEED_SYNC))
33704    && isOpen(pPager->fd)
33705    && !isUnsync
33706   ){
33707     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
33708     rc = sqlite3OsWrite(pPager->fd, (u8*)aData, pPager->pageSize, ofst);
33709     if( pgno>pPager->dbFileSize ){
33710       pPager->dbFileSize = pgno;
33711     }
33712     if( pPager->pBackup ){
33713       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
33714       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
33715       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
33716     }
33717   }else if( !isMainJrnl && pPg==0 ){
33718     /* If this is a rollback of a savepoint and data was not written to
33719     ** the database and the page is not in-memory, there is a potential
33720     ** problem. When the page is next fetched by the b-tree layer, it 
33721     ** will be read from the database file, which may or may not be 
33722     ** current. 
33723     **
33724     ** There are a couple of different ways this can happen. All are quite
33725     ** obscure. When running in synchronous mode, this can only happen 
33726     ** if the page is on the free-list at the start of the transaction, then
33727     ** populated, then moved using sqlite3PagerMovepage().
33728     **
33729     ** The solution is to add an in-memory page to the cache containing
33730     ** the data just read from the sub-journal. Mark the page as dirty 
33731     ** and if the pager requires a journal-sync, then mark the page as 
33732     ** requiring a journal-sync before it is written.
33733     */
33734     assert( isSavepnt );
33735     if( (rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1))!=SQLITE_OK ){
33736       return rc;
33737     }
33738     pPg->flags &= ~PGHDR_NEED_READ;
33739     sqlite3PcacheMakeDirty(pPg);
33740   }
33741   if( pPg ){
33742     /* No page should ever be explicitly rolled back that is in use, except
33743     ** for page 1 which is held in use in order to keep the lock on the
33744     ** database active. However such a page may be rolled back as a result
33745     ** of an internal error resulting in an automatic call to
33746     ** sqlite3PagerRollback().
33747     */
33748     void *pData;
33749     pData = pPg->pData;
33750     memcpy(pData, (u8*)aData, pPager->pageSize);
33751     pPager->xReiniter(pPg);
33752     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
33753       /* If the contents of this page were just restored from the main 
33754       ** journal file, then its content must be as they were when the 
33755       ** transaction was first opened. In this case we can mark the page
33756       ** as clean, since there will be no need to write it out to the.
33757       **
33758       ** There is one exception to this rule. If the page is being rolled
33759       ** back as part of a savepoint (or statement) rollback from an 
33760       ** unsynced portion of the main journal file, then it is not safe
33761       ** to mark the page as clean. This is because marking the page as
33762       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
33763       ** already in the journal file (recorded in Pager.pInJournal) and
33764       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
33765       ** again within this transaction, it will be marked as dirty but
33766       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
33767       ** be written out into the database file before its journal file
33768       ** segment is synced. If a crash occurs during or following this,
33769       ** database corruption may ensue.
33770       */
33771       sqlite3PcacheMakeClean(pPg);
33772     }
33773 #ifdef SQLITE_CHECK_PAGES
33774     pPg->pageHash = pager_pagehash(pPg);
33775 #endif
33776     /* If this was page 1, then restore the value of Pager.dbFileVers.
33777     ** Do this before any decoding. */
33778     if( pgno==1 ){
33779       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
33780     }
33781
33782     /* Decode the page just read from disk */
33783     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
33784     sqlite3PcacheRelease(pPg);
33785   }
33786   return rc;
33787 }
33788
33789 /*
33790 ** Parameter zMaster is the name of a master journal file. A single journal
33791 ** file that referred to the master journal file has just been rolled back.
33792 ** This routine checks if it is possible to delete the master journal file,
33793 ** and does so if it is.
33794 **
33795 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
33796 ** available for use within this function.
33797 **
33798 ** When a master journal file is created, it is populated with the names 
33799 ** of all of its child journals, one after another, formatted as utf-8 
33800 ** encoded text. The end of each child journal file is marked with a 
33801 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
33802 ** file for a transaction involving two databases might be:
33803 **
33804 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
33805 **
33806 ** A master journal file may only be deleted once all of its child 
33807 ** journals have been rolled back.
33808 **
33809 ** This function reads the contents of the master-journal file into 
33810 ** memory and loops through each of the child journal names. For
33811 ** each child journal, it checks if:
33812 **
33813 **   * if the child journal exists, and if so
33814 **   * if the child journal contains a reference to master journal 
33815 **     file zMaster
33816 **
33817 ** If a child journal can be found that matches both of the criteria
33818 ** above, this function returns without doing anything. Otherwise, if
33819 ** no such child journal can be found, file zMaster is deleted from
33820 ** the file-system using sqlite3OsDelete().
33821 **
33822 ** If an IO error within this function, an error code is returned. This
33823 ** function allocates memory by calling sqlite3Malloc(). If an allocation
33824 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
33825 ** occur, SQLITE_OK is returned.
33826 **
33827 ** TODO: This function allocates a single block of memory to load
33828 ** the entire contents of the master journal file. This could be
33829 ** a couple of kilobytes or so - potentially larger than the page 
33830 ** size.
33831 */
33832 static int pager_delmaster(Pager *pPager, const char *zMaster){
33833   sqlite3_vfs *pVfs = pPager->pVfs;
33834   int rc;                   /* Return code */
33835   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
33836   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
33837   char *zMasterJournal = 0; /* Contents of master journal file */
33838   i64 nMasterJournal;       /* Size of master journal file */
33839
33840   /* Allocate space for both the pJournal and pMaster file descriptors.
33841   ** If successful, open the master journal file for reading.
33842   */
33843   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
33844   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
33845   if( !pMaster ){
33846     rc = SQLITE_NOMEM;
33847   }else{
33848     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
33849     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
33850   }
33851   if( rc!=SQLITE_OK ) goto delmaster_out;
33852
33853   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
33854   if( rc!=SQLITE_OK ) goto delmaster_out;
33855
33856   if( nMasterJournal>0 ){
33857     char *zJournal;
33858     char *zMasterPtr = 0;
33859     int nMasterPtr = pVfs->mxPathname+1;
33860
33861     /* Load the entire master journal file into space obtained from
33862     ** sqlite3_malloc() and pointed to by zMasterJournal. 
33863     */
33864     zMasterJournal = sqlite3Malloc((int)nMasterJournal + nMasterPtr + 1);
33865     if( !zMasterJournal ){
33866       rc = SQLITE_NOMEM;
33867       goto delmaster_out;
33868     }
33869     zMasterPtr = &zMasterJournal[nMasterJournal+1];
33870     rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
33871     if( rc!=SQLITE_OK ) goto delmaster_out;
33872     zMasterJournal[nMasterJournal] = 0;
33873
33874     zJournal = zMasterJournal;
33875     while( (zJournal-zMasterJournal)<nMasterJournal ){
33876       int exists;
33877       rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
33878       if( rc!=SQLITE_OK ){
33879         goto delmaster_out;
33880       }
33881       if( exists ){
33882         /* One of the journals pointed to by the master journal exists.
33883         ** Open it and check if it points at the master journal. If
33884         ** so, return without deleting the master journal file.
33885         */
33886         int c;
33887         int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
33888         rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
33889         if( rc!=SQLITE_OK ){
33890           goto delmaster_out;
33891         }
33892
33893         rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
33894         sqlite3OsClose(pJournal);
33895         if( rc!=SQLITE_OK ){
33896           goto delmaster_out;
33897         }
33898
33899         c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
33900         if( c ){
33901           /* We have a match. Do not delete the master journal file. */
33902           goto delmaster_out;
33903         }
33904       }
33905       zJournal += (sqlite3Strlen30(zJournal)+1);
33906     }
33907   }
33908   
33909   rc = sqlite3OsDelete(pVfs, zMaster, 0);
33910
33911 delmaster_out:
33912   if( zMasterJournal ){
33913     sqlite3_free(zMasterJournal);
33914   }  
33915   if( pMaster ){
33916     sqlite3OsClose(pMaster);
33917     assert( !isOpen(pJournal) );
33918   }
33919   sqlite3_free(pMaster);
33920   return rc;
33921 }
33922
33923
33924 /*
33925 ** This function is used to change the actual size of the database 
33926 ** file in the file-system. This only happens when committing a transaction,
33927 ** or rolling back a transaction (including rolling back a hot-journal).
33928 **
33929 ** If the main database file is not open, or an exclusive lock is not
33930 ** held, this function is a no-op. Otherwise, the size of the file is
33931 ** changed to nPage pages (nPage*pPager->pageSize bytes). If the file
33932 ** on disk is currently larger than nPage pages, then use the VFS
33933 ** xTruncate() method to truncate it.
33934 **
33935 ** Or, it might might be the case that the file on disk is smaller than 
33936 ** nPage pages. Some operating system implementations can get confused if 
33937 ** you try to truncate a file to some size that is larger than it 
33938 ** currently is, so detect this case and write a single zero byte to 
33939 ** the end of the new file instead.
33940 **
33941 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
33942 ** the database file, return the error code to the caller.
33943 */
33944 static int pager_truncate(Pager *pPager, Pgno nPage){
33945   int rc = SQLITE_OK;
33946   if( pPager->state>=PAGER_EXCLUSIVE && isOpen(pPager->fd) ){
33947     i64 currentSize, newSize;
33948     /* TODO: Is it safe to use Pager.dbFileSize here? */
33949     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
33950     newSize = pPager->pageSize*(i64)nPage;
33951     if( rc==SQLITE_OK && currentSize!=newSize ){
33952       if( currentSize>newSize ){
33953         rc = sqlite3OsTruncate(pPager->fd, newSize);
33954       }else{
33955         rc = sqlite3OsWrite(pPager->fd, "", 1, newSize-1);
33956       }
33957       if( rc==SQLITE_OK ){
33958         pPager->dbFileSize = nPage;
33959       }
33960     }
33961   }
33962   return rc;
33963 }
33964
33965 /*
33966 ** Set the value of the Pager.sectorSize variable for the given
33967 ** pager based on the value returned by the xSectorSize method
33968 ** of the open database file. The sector size will be used used 
33969 ** to determine the size and alignment of journal header and 
33970 ** master journal pointers within created journal files.
33971 **
33972 ** For temporary files the effective sector size is always 512 bytes.
33973 **
33974 ** Otherwise, for non-temporary files, the effective sector size is
33975 ** the value returned by the xSectorSize() method rounded up to 32 if
33976 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
33977 ** is greater than MAX_SECTOR_SIZE.
33978 */
33979 static void setSectorSize(Pager *pPager){
33980   assert( isOpen(pPager->fd) || pPager->tempFile );
33981
33982   if( !pPager->tempFile ){
33983     /* Sector size doesn't matter for temporary files. Also, the file
33984     ** may not have been opened yet, in which case the OsSectorSize()
33985     ** call will segfault.
33986     */
33987     pPager->sectorSize = sqlite3OsSectorSize(pPager->fd);
33988   }
33989   if( pPager->sectorSize<32 ){
33990     pPager->sectorSize = 512;
33991   }
33992   if( pPager->sectorSize>MAX_SECTOR_SIZE ){
33993     assert( MAX_SECTOR_SIZE>=512 );
33994     pPager->sectorSize = MAX_SECTOR_SIZE;
33995   }
33996 }
33997
33998 /*
33999 ** Playback the journal and thus restore the database file to
34000 ** the state it was in before we started making changes.  
34001 **
34002 ** The journal file format is as follows: 
34003 **
34004 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
34005 **  (2)  4 byte big-endian integer which is the number of valid page records
34006 **       in the journal.  If this value is 0xffffffff, then compute the
34007 **       number of page records from the journal size.
34008 **  (3)  4 byte big-endian integer which is the initial value for the 
34009 **       sanity checksum.
34010 **  (4)  4 byte integer which is the number of pages to truncate the
34011 **       database to during a rollback.
34012 **  (5)  4 byte big-endian integer which is the sector size.  The header
34013 **       is this many bytes in size.
34014 **  (6)  4 byte big-endian integer which is the page size.
34015 **  (7)  zero padding out to the next sector size.
34016 **  (8)  Zero or more pages instances, each as follows:
34017 **        +  4 byte page number.
34018 **        +  pPager->pageSize bytes of data.
34019 **        +  4 byte checksum
34020 **
34021 ** When we speak of the journal header, we mean the first 7 items above.
34022 ** Each entry in the journal is an instance of the 8th item.
34023 **
34024 ** Call the value from the second bullet "nRec".  nRec is the number of
34025 ** valid page entries in the journal.  In most cases, you can compute the
34026 ** value of nRec from the size of the journal file.  But if a power
34027 ** failure occurred while the journal was being written, it could be the
34028 ** case that the size of the journal file had already been increased but
34029 ** the extra entries had not yet made it safely to disk.  In such a case,
34030 ** the value of nRec computed from the file size would be too large.  For
34031 ** that reason, we always use the nRec value in the header.
34032 **
34033 ** If the nRec value is 0xffffffff it means that nRec should be computed
34034 ** from the file size.  This value is used when the user selects the
34035 ** no-sync option for the journal.  A power failure could lead to corruption
34036 ** in this case.  But for things like temporary table (which will be
34037 ** deleted when the power is restored) we don't care.  
34038 **
34039 ** If the file opened as the journal file is not a well-formed
34040 ** journal file then all pages up to the first corrupted page are rolled
34041 ** back (or no pages if the journal header is corrupted). The journal file
34042 ** is then deleted and SQLITE_OK returned, just as if no corruption had
34043 ** been encountered.
34044 **
34045 ** If an I/O or malloc() error occurs, the journal-file is not deleted
34046 ** and an error code is returned.
34047 **
34048 ** The isHot parameter indicates that we are trying to rollback a journal
34049 ** that might be a hot journal.  Or, it could be that the journal is 
34050 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
34051 ** If the journal really is hot, reset the pager cache prior rolling
34052 ** back any content.  If the journal is merely persistent, no reset is
34053 ** needed.
34054 */
34055 static int pager_playback(Pager *pPager, int isHot){
34056   sqlite3_vfs *pVfs = pPager->pVfs;
34057   i64 szJ;                 /* Size of the journal file in bytes */
34058   u32 nRec;                /* Number of Records in the journal */
34059   u32 u;                   /* Unsigned loop counter */
34060   Pgno mxPg = 0;           /* Size of the original file in pages */
34061   int rc;                  /* Result code of a subroutine */
34062   int res = 1;             /* Value returned by sqlite3OsAccess() */
34063   char *zMaster = 0;       /* Name of master journal file if any */
34064   int needPagerReset;      /* True to reset page prior to first page rollback */
34065
34066   /* Figure out how many records are in the journal.  Abort early if
34067   ** the journal is empty.
34068   */
34069   assert( isOpen(pPager->jfd) );
34070   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
34071   if( rc!=SQLITE_OK || szJ==0 ){
34072     goto end_playback;
34073   }
34074
34075   /* Read the master journal name from the journal, if it is present.
34076   ** If a master journal file name is specified, but the file is not
34077   ** present on disk, then the journal is not hot and does not need to be
34078   ** played back.
34079   **
34080   ** TODO: Technically the following is an error because it assumes that
34081   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
34082   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
34083   **  mxPathname is 512, which is the same as the minimum allowable value
34084   ** for pageSize.
34085   */
34086   zMaster = pPager->pTmpSpace;
34087   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
34088   if( rc==SQLITE_OK && zMaster[0] ){
34089     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
34090   }
34091   zMaster = 0;
34092   if( rc!=SQLITE_OK || !res ){
34093     goto end_playback;
34094   }
34095   pPager->journalOff = 0;
34096   needPagerReset = isHot;
34097
34098   /* This loop terminates either when a readJournalHdr() or 
34099   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
34100   ** occurs. 
34101   */
34102   while( 1 ){
34103     int isUnsync = 0;
34104
34105     /* Read the next journal header from the journal file.  If there are
34106     ** not enough bytes left in the journal file for a complete header, or
34107     ** it is corrupted, then a process must of failed while writing it.
34108     ** This indicates nothing more needs to be rolled back.
34109     */
34110     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
34111     if( rc!=SQLITE_OK ){ 
34112       if( rc==SQLITE_DONE ){
34113         rc = SQLITE_OK;
34114       }
34115       goto end_playback;
34116     }
34117
34118     /* If nRec is 0xffffffff, then this journal was created by a process
34119     ** working in no-sync mode. This means that the rest of the journal
34120     ** file consists of pages, there are no more journal headers. Compute
34121     ** the value of nRec based on this assumption.
34122     */
34123     if( nRec==0xffffffff ){
34124       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
34125       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
34126     }
34127
34128     /* If nRec is 0 and this rollback is of a transaction created by this
34129     ** process and if this is the final header in the journal, then it means
34130     ** that this part of the journal was being filled but has not yet been
34131     ** synced to disk.  Compute the number of pages based on the remaining
34132     ** size of the file.
34133     **
34134     ** The third term of the test was added to fix ticket #2565.
34135     ** When rolling back a hot journal, nRec==0 always means that the next
34136     ** chunk of the journal contains zero pages to be rolled back.  But
34137     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
34138     ** the journal, it means that the journal might contain additional
34139     ** pages that need to be rolled back and that the number of pages 
34140     ** should be computed based on the journal file size.
34141     */
34142     if( nRec==0 && !isHot &&
34143         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
34144       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
34145       isUnsync = 1;
34146     }
34147
34148     /* If this is the first header read from the journal, truncate the
34149     ** database file back to its original size.
34150     */
34151     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
34152       rc = pager_truncate(pPager, mxPg);
34153       if( rc!=SQLITE_OK ){
34154         goto end_playback;
34155       }
34156       pPager->dbSize = mxPg;
34157     }
34158
34159     /* Copy original pages out of the journal and back into the 
34160     ** database file and/or page cache.
34161     */
34162     for(u=0; u<nRec; u++){
34163       if( needPagerReset ){
34164         pager_reset(pPager);
34165         needPagerReset = 0;
34166       }
34167       rc = pager_playback_one_page(pPager,1,isUnsync,&pPager->journalOff,0,0);
34168       if( rc!=SQLITE_OK ){
34169         if( rc==SQLITE_DONE ){
34170           rc = SQLITE_OK;
34171           pPager->journalOff = szJ;
34172           break;
34173         }else{
34174           /* If we are unable to rollback, quit and return the error
34175           ** code.  This will cause the pager to enter the error state
34176           ** so that no further harm will be done.  Perhaps the next
34177           ** process to come along will be able to rollback the database.
34178           */
34179           goto end_playback;
34180         }
34181       }
34182     }
34183   }
34184   /*NOTREACHED*/
34185   assert( 0 );
34186
34187 end_playback:
34188   /* Following a rollback, the database file should be back in its original
34189   ** state prior to the start of the transaction, so invoke the
34190   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
34191   ** assertion that the transaction counter was modified.
34192   */
34193   assert(
34194     pPager->fd->pMethods==0 ||
34195     sqlite3OsFileControl(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0)>=SQLITE_OK
34196   );
34197
34198   /* If this playback is happening automatically as a result of an IO or 
34199   ** malloc error that occurred after the change-counter was updated but 
34200   ** before the transaction was committed, then the change-counter 
34201   ** modification may just have been reverted. If this happens in exclusive 
34202   ** mode, then subsequent transactions performed by the connection will not
34203   ** update the change-counter at all. This may lead to cache inconsistency
34204   ** problems for other processes at some point in the future. So, just
34205   ** in case this has happened, clear the changeCountDone flag now.
34206   */
34207   pPager->changeCountDone = pPager->tempFile;
34208
34209   if( rc==SQLITE_OK ){
34210     zMaster = pPager->pTmpSpace;
34211     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
34212     testcase( rc!=SQLITE_OK );
34213   }
34214   if( rc==SQLITE_OK && pPager->noSync==0 && pPager->state>=PAGER_EXCLUSIVE ){
34215     rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
34216   }
34217   if( rc==SQLITE_OK ){
34218     rc = pager_end_transaction(pPager, zMaster[0]!='\0');
34219     testcase( rc!=SQLITE_OK );
34220   }
34221   if( rc==SQLITE_OK && zMaster[0] && res ){
34222     /* If there was a master journal and this routine will return success,
34223     ** see if it is possible to delete the master journal.
34224     */
34225     rc = pager_delmaster(pPager, zMaster);
34226     testcase( rc!=SQLITE_OK );
34227   }
34228
34229   /* The Pager.sectorSize variable may have been updated while rolling
34230   ** back a journal created by a process with a different sector size
34231   ** value. Reset it to the correct value for this process.
34232   */
34233   setSectorSize(pPager);
34234   return rc;
34235 }
34236
34237 /*
34238 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
34239 ** the entire master journal file. The case pSavepoint==NULL occurs when 
34240 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
34241 ** savepoint.
34242 **
34243 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
34244 ** being rolled back), then the rollback consists of up to three stages,
34245 ** performed in the order specified:
34246 **
34247 **   * Pages are played back from the main journal starting at byte
34248 **     offset PagerSavepoint.iOffset and continuing to 
34249 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
34250 **     file if PagerSavepoint.iHdrOffset is zero.
34251 **
34252 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
34253 **     back starting from the journal header immediately following 
34254 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
34255 **
34256 **   * Pages are then played back from the sub-journal file, starting
34257 **     with the PagerSavepoint.iSubRec and continuing to the end of
34258 **     the journal file.
34259 **
34260 ** Throughout the rollback process, each time a page is rolled back, the
34261 ** corresponding bit is set in a bitvec structure (variable pDone in the
34262 ** implementation below). This is used to ensure that a page is only
34263 ** rolled back the first time it is encountered in either journal.
34264 **
34265 ** If pSavepoint is NULL, then pages are only played back from the main
34266 ** journal file. There is no need for a bitvec in this case.
34267 **
34268 ** In either case, before playback commences the Pager.dbSize variable
34269 ** is reset to the value that it held at the start of the savepoint 
34270 ** (or transaction). No page with a page-number greater than this value
34271 ** is played back. If one is encountered it is simply skipped.
34272 */
34273 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
34274   i64 szJ;                 /* Effective size of the main journal */
34275   i64 iHdrOff;             /* End of first segment of main-journal records */
34276   int rc = SQLITE_OK;      /* Return code */
34277   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
34278
34279   assert( pPager->state>=PAGER_SHARED );
34280
34281   /* Allocate a bitvec to use to store the set of pages rolled back */
34282   if( pSavepoint ){
34283     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
34284     if( !pDone ){
34285       return SQLITE_NOMEM;
34286     }
34287   }
34288
34289   /* Set the database size back to the value it was before the savepoint 
34290   ** being reverted was opened.
34291   */
34292   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
34293
34294   /* Use pPager->journalOff as the effective size of the main rollback
34295   ** journal.  The actual file might be larger than this in
34296   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
34297   ** past pPager->journalOff is off-limits to us.
34298   */
34299   szJ = pPager->journalOff;
34300
34301   /* Begin by rolling back records from the main journal starting at
34302   ** PagerSavepoint.iOffset and continuing to the next journal header.
34303   ** There might be records in the main journal that have a page number
34304   ** greater than the current database size (pPager->dbSize) but those
34305   ** will be skipped automatically.  Pages are added to pDone as they
34306   ** are played back.
34307   */
34308   if( pSavepoint ){
34309     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
34310     pPager->journalOff = pSavepoint->iOffset;
34311     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
34312       rc = pager_playback_one_page(pPager, 1, 0, &pPager->journalOff, 1, pDone);
34313     }
34314     assert( rc!=SQLITE_DONE );
34315   }else{
34316     pPager->journalOff = 0;
34317   }
34318
34319   /* Continue rolling back records out of the main journal starting at
34320   ** the first journal header seen and continuing until the effective end
34321   ** of the main journal file.  Continue to skip out-of-range pages and
34322   ** continue adding pages rolled back to pDone.
34323   */
34324   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
34325     u32 ii;            /* Loop counter */
34326     u32 nJRec = 0;     /* Number of Journal Records */
34327     u32 dummy;
34328     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
34329     assert( rc!=SQLITE_DONE );
34330
34331     /*
34332     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
34333     ** test is related to ticket #2565.  See the discussion in the
34334     ** pager_playback() function for additional information.
34335     */
34336     if( nJRec==0 
34337      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
34338     ){
34339       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
34340     }
34341     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
34342       rc = pager_playback_one_page(pPager, 1, 0, &pPager->journalOff, 1, pDone);
34343     }
34344     assert( rc!=SQLITE_DONE );
34345   }
34346   assert( rc!=SQLITE_OK || pPager->journalOff==szJ );
34347
34348   /* Finally,  rollback pages from the sub-journal.  Page that were
34349   ** previously rolled back out of the main journal (and are hence in pDone)
34350   ** will be skipped.  Out-of-range pages are also skipped.
34351   */
34352   if( pSavepoint ){
34353     u32 ii;            /* Loop counter */
34354     i64 offset = pSavepoint->iSubRec*(4+pPager->pageSize);
34355     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
34356       assert( offset==ii*(4+pPager->pageSize) );
34357       rc = pager_playback_one_page(pPager, 0, 0, &offset, 1, pDone);
34358     }
34359     assert( rc!=SQLITE_DONE );
34360   }
34361
34362   sqlite3BitvecDestroy(pDone);
34363   if( rc==SQLITE_OK ){
34364     pPager->journalOff = szJ;
34365   }
34366   return rc;
34367 }
34368
34369 /*
34370 ** Change the maximum number of in-memory pages that are allowed.
34371 */
34372 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
34373   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
34374 }
34375
34376 /*
34377 ** Adjust the robustness of the database to damage due to OS crashes
34378 ** or power failures by changing the number of syncs()s when writing
34379 ** the rollback journal.  There are three levels:
34380 **
34381 **    OFF       sqlite3OsSync() is never called.  This is the default
34382 **              for temporary and transient files.
34383 **
34384 **    NORMAL    The journal is synced once before writes begin on the
34385 **              database.  This is normally adequate protection, but
34386 **              it is theoretically possible, though very unlikely,
34387 **              that an inopertune power failure could leave the journal
34388 **              in a state which would cause damage to the database
34389 **              when it is rolled back.
34390 **
34391 **    FULL      The journal is synced twice before writes begin on the
34392 **              database (with some additional information - the nRec field
34393 **              of the journal header - being written in between the two
34394 **              syncs).  If we assume that writing a
34395 **              single disk sector is atomic, then this mode provides
34396 **              assurance that the journal will not be corrupted to the
34397 **              point of causing damage to the database during rollback.
34398 **
34399 ** Numeric values associated with these states are OFF==1, NORMAL=2,
34400 ** and FULL=3.
34401 */
34402 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
34403 SQLITE_PRIVATE void sqlite3PagerSetSafetyLevel(Pager *pPager, int level, int bFullFsync){
34404   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
34405   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
34406   pPager->sync_flags = (bFullFsync?SQLITE_SYNC_FULL:SQLITE_SYNC_NORMAL);
34407   if( pPager->noSync ) pPager->needSync = 0;
34408 }
34409 #endif
34410
34411 /*
34412 ** The following global variable is incremented whenever the library
34413 ** attempts to open a temporary file.  This information is used for
34414 ** testing and analysis only.  
34415 */
34416 #ifdef SQLITE_TEST
34417 SQLITE_API int sqlite3_opentemp_count = 0;
34418 #endif
34419
34420 /*
34421 ** Open a temporary file.
34422 **
34423 ** Write the file descriptor into *pFile. Return SQLITE_OK on success 
34424 ** or some other error code if we fail. The OS will automatically 
34425 ** delete the temporary file when it is closed.
34426 **
34427 ** The flags passed to the VFS layer xOpen() call are those specified
34428 ** by parameter vfsFlags ORed with the following:
34429 **
34430 **     SQLITE_OPEN_READWRITE
34431 **     SQLITE_OPEN_CREATE
34432 **     SQLITE_OPEN_EXCLUSIVE
34433 **     SQLITE_OPEN_DELETEONCLOSE
34434 */
34435 static int pagerOpentemp(
34436   Pager *pPager,        /* The pager object */
34437   sqlite3_file *pFile,  /* Write the file descriptor here */
34438   int vfsFlags          /* Flags passed through to the VFS */
34439 ){
34440   int rc;               /* Return code */
34441
34442 #ifdef SQLITE_TEST
34443   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
34444 #endif
34445
34446   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
34447             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
34448   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
34449   assert( rc!=SQLITE_OK || isOpen(pFile) );
34450   return rc;
34451 }
34452
34453 /*
34454 ** Set the busy handler function.
34455 **
34456 ** The pager invokes the busy-handler if sqlite3OsLock() returns 
34457 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
34458 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
34459 ** lock. It does *not* invoke the busy handler when upgrading from
34460 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
34461 ** (which occurs during hot-journal rollback). Summary:
34462 **
34463 **   Transition                        | Invokes xBusyHandler
34464 **   --------------------------------------------------------
34465 **   NO_LOCK       -> SHARED_LOCK      | Yes
34466 **   SHARED_LOCK   -> RESERVED_LOCK    | No
34467 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
34468 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
34469 **
34470 ** If the busy-handler callback returns non-zero, the lock is 
34471 ** retried. If it returns zero, then the SQLITE_BUSY error is
34472 ** returned to the caller of the pager API function.
34473 */
34474 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
34475   Pager *pPager,                       /* Pager object */
34476   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
34477   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
34478 ){  
34479   pPager->xBusyHandler = xBusyHandler;
34480   pPager->pBusyHandlerArg = pBusyHandlerArg;
34481 }
34482
34483 /*
34484 ** Report the current page size and number of reserved bytes back
34485 ** to the codec.
34486 */
34487 #ifdef SQLITE_HAS_CODEC
34488 static void pagerReportSize(Pager *pPager){
34489   if( pPager->xCodecSizeChng ){
34490     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
34491                            (int)pPager->nReserve);
34492   }
34493 }
34494 #else
34495 # define pagerReportSize(X)     /* No-op if we do not support a codec */
34496 #endif
34497
34498 /*
34499 ** Change the page size used by the Pager object. The new page size 
34500 ** is passed in *pPageSize.
34501 **
34502 ** If the pager is in the error state when this function is called, it
34503 ** is a no-op. The value returned is the error state error code (i.e. 
34504 ** one of SQLITE_IOERR, SQLITE_CORRUPT or SQLITE_FULL).
34505 **
34506 ** Otherwise, if all of the following are true:
34507 **
34508 **   * the new page size (value of *pPageSize) is valid (a power 
34509 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
34510 **
34511 **   * there are no outstanding page references, and
34512 **
34513 **   * the database is either not an in-memory database or it is
34514 **     an in-memory database that currently consists of zero pages.
34515 **
34516 ** then the pager object page size is set to *pPageSize.
34517 **
34518 ** If the page size is changed, then this function uses sqlite3PagerMalloc() 
34519 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
34520 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
34521 ** In all other cases, SQLITE_OK is returned.
34522 **
34523 ** If the page size is not changed, either because one of the enumerated
34524 ** conditions above is not true, the pager was in error state when this
34525 ** function was called, or because the memory allocation attempt failed, 
34526 ** then *pPageSize is set to the old, retained page size before returning.
34527 */
34528 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u16 *pPageSize, int nReserve){
34529   int rc = pPager->errCode;
34530
34531   if( rc==SQLITE_OK ){
34532     u16 pageSize = *pPageSize;
34533     assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
34534     if( (pPager->memDb==0 || pPager->dbSize==0)
34535      && sqlite3PcacheRefCount(pPager->pPCache)==0 
34536      && pageSize && pageSize!=pPager->pageSize 
34537     ){
34538       char *pNew = (char *)sqlite3PageMalloc(pageSize);
34539       if( !pNew ){
34540         rc = SQLITE_NOMEM;
34541       }else{
34542         pager_reset(pPager);
34543         pPager->pageSize = pageSize;
34544         sqlite3PageFree(pPager->pTmpSpace);
34545         pPager->pTmpSpace = pNew;
34546         sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
34547       }
34548     }
34549     *pPageSize = (u16)pPager->pageSize;
34550     if( nReserve<0 ) nReserve = pPager->nReserve;
34551     assert( nReserve>=0 && nReserve<1000 );
34552     pPager->nReserve = (i16)nReserve;
34553     pagerReportSize(pPager);
34554   }
34555   return rc;
34556 }
34557
34558 /*
34559 ** Return a pointer to the "temporary page" buffer held internally
34560 ** by the pager.  This is a buffer that is big enough to hold the
34561 ** entire content of a database page.  This buffer is used internally
34562 ** during rollback and will be overwritten whenever a rollback
34563 ** occurs.  But other modules are free to use it too, as long as
34564 ** no rollbacks are happening.
34565 */
34566 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
34567   return pPager->pTmpSpace;
34568 }
34569
34570 /*
34571 ** Attempt to set the maximum database page count if mxPage is positive. 
34572 ** Make no changes if mxPage is zero or negative.  And never reduce the
34573 ** maximum page count below the current size of the database.
34574 **
34575 ** Regardless of mxPage, return the current maximum page count.
34576 */
34577 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
34578   if( mxPage>0 ){
34579     pPager->mxPgno = mxPage;
34580   }
34581   sqlite3PagerPagecount(pPager, 0);
34582   return pPager->mxPgno;
34583 }
34584
34585 /*
34586 ** The following set of routines are used to disable the simulated
34587 ** I/O error mechanism.  These routines are used to avoid simulated
34588 ** errors in places where we do not care about errors.
34589 **
34590 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
34591 ** and generate no code.
34592 */
34593 #ifdef SQLITE_TEST
34594 SQLITE_API extern int sqlite3_io_error_pending;
34595 SQLITE_API extern int sqlite3_io_error_hit;
34596 static int saved_cnt;
34597 void disable_simulated_io_errors(void){
34598   saved_cnt = sqlite3_io_error_pending;
34599   sqlite3_io_error_pending = -1;
34600 }
34601 void enable_simulated_io_errors(void){
34602   sqlite3_io_error_pending = saved_cnt;
34603 }
34604 #else
34605 # define disable_simulated_io_errors()
34606 # define enable_simulated_io_errors()
34607 #endif
34608
34609 /*
34610 ** Read the first N bytes from the beginning of the file into memory
34611 ** that pDest points to. 
34612 **
34613 ** If the pager was opened on a transient file (zFilename==""), or
34614 ** opened on a file less than N bytes in size, the output buffer is
34615 ** zeroed and SQLITE_OK returned. The rationale for this is that this 
34616 ** function is used to read database headers, and a new transient or
34617 ** zero sized database has a header than consists entirely of zeroes.
34618 **
34619 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
34620 ** the error code is returned to the caller and the contents of the
34621 ** output buffer undefined.
34622 */
34623 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
34624   int rc = SQLITE_OK;
34625   memset(pDest, 0, N);
34626   assert( isOpen(pPager->fd) || pPager->tempFile );
34627   if( isOpen(pPager->fd) ){
34628     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
34629     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
34630     if( rc==SQLITE_IOERR_SHORT_READ ){
34631       rc = SQLITE_OK;
34632     }
34633   }
34634   return rc;
34635 }
34636
34637 /*
34638 ** Return the total number of pages in the database file associated 
34639 ** with pPager. Normally, this is calculated as (<db file size>/<page-size>).
34640 ** However, if the file is between 1 and <page-size> bytes in size, then 
34641 ** this is considered a 1 page file.
34642 **
34643 ** If the pager is in error state when this function is called, then the
34644 ** error state error code is returned and *pnPage left unchanged. Or,
34645 ** if the file system has to be queried for the size of the file and
34646 ** the query attempt returns an IO error, the IO error code is returned
34647 ** and *pnPage is left unchanged.
34648 **
34649 ** Otherwise, if everything is successful, then SQLITE_OK is returned
34650 ** and *pnPage is set to the number of pages in the database.
34651 */
34652 SQLITE_PRIVATE int sqlite3PagerPagecount(Pager *pPager, int *pnPage){
34653   Pgno nPage;               /* Value to return via *pnPage */
34654
34655   /* If the pager is already in the error state, return the error code. */
34656   if( pPager->errCode ){
34657     return pPager->errCode;
34658   }
34659
34660   /* Determine the number of pages in the file. Store this in nPage. */
34661   if( pPager->dbSizeValid ){
34662     nPage = pPager->dbSize;
34663   }else{
34664     int rc;                 /* Error returned by OsFileSize() */
34665     i64 n = 0;              /* File size in bytes returned by OsFileSize() */
34666
34667     assert( isOpen(pPager->fd) || pPager->tempFile );
34668     if( isOpen(pPager->fd) && (0 != (rc = sqlite3OsFileSize(pPager->fd, &n))) ){
34669       pager_error(pPager, rc);
34670       return rc;
34671     }
34672     if( n>0 && n<pPager->pageSize ){
34673       nPage = 1;
34674     }else{
34675       nPage = (Pgno)(n / pPager->pageSize);
34676     }
34677     if( pPager->state!=PAGER_UNLOCK ){
34678       pPager->dbSize = nPage;
34679       pPager->dbFileSize = nPage;
34680       pPager->dbSizeValid = 1;
34681     }
34682   }
34683
34684   /* If the current number of pages in the file is greater than the 
34685   ** configured maximum pager number, increase the allowed limit so
34686   ** that the file can be read.
34687   */
34688   if( nPage>pPager->mxPgno ){
34689     pPager->mxPgno = (Pgno)nPage;
34690   }
34691
34692   /* Set the output variable and return SQLITE_OK */
34693   if( pnPage ){
34694     *pnPage = nPage;
34695   }
34696   return SQLITE_OK;
34697 }
34698
34699
34700 /*
34701 ** Try to obtain a lock of type locktype on the database file. If
34702 ** a similar or greater lock is already held, this function is a no-op
34703 ** (returning SQLITE_OK immediately).
34704 **
34705 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
34706 ** the busy callback if the lock is currently not available. Repeat 
34707 ** until the busy callback returns false or until the attempt to 
34708 ** obtain the lock succeeds.
34709 **
34710 ** Return SQLITE_OK on success and an error code if we cannot obtain
34711 ** the lock. If the lock is obtained successfully, set the Pager.state 
34712 ** variable to locktype before returning.
34713 */
34714 static int pager_wait_on_lock(Pager *pPager, int locktype){
34715   int rc;                              /* Return code */
34716
34717   /* The OS lock values must be the same as the Pager lock values */
34718   assert( PAGER_SHARED==SHARED_LOCK );
34719   assert( PAGER_RESERVED==RESERVED_LOCK );
34720   assert( PAGER_EXCLUSIVE==EXCLUSIVE_LOCK );
34721
34722   /* If the file is currently unlocked then the size must be unknown. It
34723   ** must not have been modified at this point.
34724   */
34725   assert( pPager->state>=PAGER_SHARED || pPager->dbSizeValid==0 );
34726   assert( pPager->state>=PAGER_SHARED || pPager->dbModified==0 );
34727
34728   /* Check that this is either a no-op (because the requested lock is 
34729   ** already held, or one of the transistions that the busy-handler
34730   ** may be invoked during, according to the comment above
34731   ** sqlite3PagerSetBusyhandler().
34732   */
34733   assert( (pPager->state>=locktype)
34734        || (pPager->state==PAGER_UNLOCK && locktype==PAGER_SHARED)
34735        || (pPager->state==PAGER_RESERVED && locktype==PAGER_EXCLUSIVE)
34736   );
34737
34738   if( pPager->state>=locktype ){
34739     rc = SQLITE_OK;
34740   }else{
34741     do {
34742       rc = sqlite3OsLock(pPager->fd, locktype);
34743     }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
34744     if( rc==SQLITE_OK ){
34745       pPager->state = (u8)locktype;
34746       IOTRACE(("LOCK %p %d\n", pPager, locktype))
34747     }
34748   }
34749   return rc;
34750 }
34751
34752 /*
34753 ** Function assertTruncateConstraint(pPager) checks that one of the 
34754 ** following is true for all dirty pages currently in the page-cache:
34755 **
34756 **   a) The page number is less than or equal to the size of the 
34757 **      current database image, in pages, OR
34758 **
34759 **   b) if the page content were written at this time, it would not
34760 **      be necessary to write the current content out to the sub-journal
34761 **      (as determined by function subjRequiresPage()).
34762 **
34763 ** If the condition asserted by this function were not true, and the
34764 ** dirty page were to be discarded from the cache via the pagerStress()
34765 ** routine, pagerStress() would not write the current page content to
34766 ** the database file. If a savepoint transaction were rolled back after
34767 ** this happened, the correct behaviour would be to restore the current
34768 ** content of the page. However, since this content is not present in either
34769 ** the database file or the portion of the rollback journal and 
34770 ** sub-journal rolled back the content could not be restored and the
34771 ** database image would become corrupt. It is therefore fortunate that 
34772 ** this circumstance cannot arise.
34773 */
34774 #if defined(SQLITE_DEBUG)
34775 static void assertTruncateConstraintCb(PgHdr *pPg){
34776   assert( pPg->flags&PGHDR_DIRTY );
34777   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
34778 }
34779 static void assertTruncateConstraint(Pager *pPager){
34780   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
34781 }
34782 #else
34783 # define assertTruncateConstraint(pPager)
34784 #endif
34785
34786 /*
34787 ** Truncate the in-memory database file image to nPage pages. This 
34788 ** function does not actually modify the database file on disk. It 
34789 ** just sets the internal state of the pager object so that the 
34790 ** truncation will be done when the current transaction is committed.
34791 */
34792 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
34793   assert( pPager->dbSizeValid );
34794   assert( pPager->dbSize>=nPage );
34795   assert( pPager->state>=PAGER_RESERVED );
34796   pPager->dbSize = nPage;
34797   assertTruncateConstraint(pPager);
34798 }
34799
34800 /*
34801 ** Shutdown the page cache.  Free all memory and close all files.
34802 **
34803 ** If a transaction was in progress when this routine is called, that
34804 ** transaction is rolled back.  All outstanding pages are invalidated
34805 ** and their memory is freed.  Any attempt to use a page associated
34806 ** with this page cache after this function returns will likely
34807 ** result in a coredump.
34808 **
34809 ** This function always succeeds. If a transaction is active an attempt
34810 ** is made to roll it back. If an error occurs during the rollback 
34811 ** a hot journal may be left in the filesystem but no error is returned
34812 ** to the caller.
34813 */
34814 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
34815   disable_simulated_io_errors();
34816   sqlite3BeginBenignMalloc();
34817   pPager->errCode = 0;
34818   pPager->exclusiveMode = 0;
34819   pager_reset(pPager);
34820   if( MEMDB ){
34821     pager_unlock(pPager);
34822   }else{
34823     /* Set Pager.journalHdr to -1 for the benefit of the pager_playback() 
34824     ** call which may be made from within pagerUnlockAndRollback(). If it
34825     ** is not -1, then the unsynced portion of an open journal file may
34826     ** be played back into the database. If a power failure occurs while
34827     ** this is happening, the database may become corrupt.
34828     */
34829     pPager->journalHdr = -1;
34830     pagerUnlockAndRollback(pPager);
34831   }
34832   sqlite3EndBenignMalloc();
34833   enable_simulated_io_errors();
34834   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
34835   IOTRACE(("CLOSE %p\n", pPager))
34836   sqlite3OsClose(pPager->fd);
34837   sqlite3PageFree(pPager->pTmpSpace);
34838   sqlite3PcacheClose(pPager->pPCache);
34839
34840 #ifdef SQLITE_HAS_CODEC
34841   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
34842 #endif
34843
34844   assert( !pPager->aSavepoint && !pPager->pInJournal );
34845   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
34846
34847   sqlite3_free(pPager);
34848   return SQLITE_OK;
34849 }
34850
34851 #if !defined(NDEBUG) || defined(SQLITE_TEST)
34852 /*
34853 ** Return the page number for page pPg.
34854 */
34855 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
34856   return pPg->pgno;
34857 }
34858 #endif
34859
34860 /*
34861 ** Increment the reference count for page pPg.
34862 */
34863 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
34864   sqlite3PcacheRef(pPg);
34865 }
34866
34867 /*
34868 ** Sync the journal. In other words, make sure all the pages that have
34869 ** been written to the journal have actually reached the surface of the
34870 ** disk and can be restored in the event of a hot-journal rollback.
34871 **
34872 ** If the Pager.needSync flag is not set, then this function is a
34873 ** no-op. Otherwise, the actions required depend on the journal-mode
34874 ** and the device characteristics of the the file-system, as follows:
34875 **
34876 **   * If the journal file is an in-memory journal file, no action need
34877 **     be taken.
34878 **
34879 **   * Otherwise, if the device does not support the SAFE_APPEND property,
34880 **     then the nRec field of the most recently written journal header
34881 **     is updated to contain the number of journal records that have
34882 **     been written following it. If the pager is operating in full-sync
34883 **     mode, then the journal file is synced before this field is updated.
34884 **
34885 **   * If the device does not support the SEQUENTIAL property, then 
34886 **     journal file is synced.
34887 **
34888 ** Or, in pseudo-code:
34889 **
34890 **   if( NOT <in-memory journal> ){
34891 **     if( NOT SAFE_APPEND ){
34892 **       if( <full-sync mode> ) xSync(<journal file>);
34893 **       <update nRec field>
34894 **     } 
34895 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
34896 **   }
34897 **
34898 ** The Pager.needSync flag is never be set for temporary files, or any
34899 ** file operating in no-sync mode (Pager.noSync set to non-zero).
34900 **
34901 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
34902 ** page currently held in memory before returning SQLITE_OK. If an IO
34903 ** error is encountered, then the IO error code is returned to the caller.
34904 */
34905 static int syncJournal(Pager *pPager){
34906   if( pPager->needSync ){
34907     assert( !pPager->tempFile );
34908     if( pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
34909       int rc;                              /* Return code */
34910       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
34911       assert( isOpen(pPager->jfd) );
34912
34913       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
34914         /* This block deals with an obscure problem. If the last connection
34915         ** that wrote to this database was operating in persistent-journal
34916         ** mode, then the journal file may at this point actually be larger
34917         ** than Pager.journalOff bytes. If the next thing in the journal
34918         ** file happens to be a journal-header (written as part of the
34919         ** previous connections transaction), and a crash or power-failure 
34920         ** occurs after nRec is updated but before this connection writes 
34921         ** anything else to the journal file (or commits/rolls back its 
34922         ** transaction), then SQLite may become confused when doing the 
34923         ** hot-journal rollback following recovery. It may roll back all
34924         ** of this connections data, then proceed to rolling back the old,
34925         ** out-of-date data that follows it. Database corruption.
34926         **
34927         ** To work around this, if the journal file does appear to contain
34928         ** a valid header following Pager.journalOff, then write a 0x00
34929         ** byte to the start of it to prevent it from being recognized.
34930         **
34931         ** Variable iNextHdrOffset is set to the offset at which this
34932         ** problematic header will occur, if it exists. aMagic is used 
34933         ** as a temporary buffer to inspect the first couple of bytes of
34934         ** the potential journal header.
34935         */
34936         i64 iNextHdrOffset;
34937         u8 aMagic[8];
34938         u8 zHeader[sizeof(aJournalMagic)+4];
34939
34940         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
34941         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
34942
34943         iNextHdrOffset = journalHdrOffset(pPager);
34944         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
34945         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
34946           static const u8 zerobyte = 0;
34947           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
34948         }
34949         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
34950           return rc;
34951         }
34952
34953         /* Write the nRec value into the journal file header. If in
34954         ** full-synchronous mode, sync the journal first. This ensures that
34955         ** all data has really hit the disk before nRec is updated to mark
34956         ** it as a candidate for rollback.
34957         **
34958         ** This is not required if the persistent media supports the
34959         ** SAFE_APPEND property. Because in this case it is not possible 
34960         ** for garbage data to be appended to the file, the nRec field
34961         ** is populated with 0xFFFFFFFF when the journal header is written
34962         ** and never needs to be updated.
34963         */
34964         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
34965           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
34966           IOTRACE(("JSYNC %p\n", pPager))
34967           rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags);
34968           if( rc!=SQLITE_OK ) return rc;
34969         }
34970         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
34971         rc = sqlite3OsWrite(
34972             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
34973         );
34974         if( rc!=SQLITE_OK ) return rc;
34975       }
34976       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
34977         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
34978         IOTRACE(("JSYNC %p\n", pPager))
34979         rc = sqlite3OsSync(pPager->jfd, pPager->sync_flags| 
34980           (pPager->sync_flags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
34981         );
34982         if( rc!=SQLITE_OK ) return rc;
34983       }
34984     }
34985
34986     /* The journal file was just successfully synced. Set Pager.needSync 
34987     ** to zero and clear the PGHDR_NEED_SYNC flag on all pagess.
34988     */
34989     pPager->needSync = 0;
34990     pPager->journalStarted = 1;
34991     sqlite3PcacheClearSyncFlags(pPager->pPCache);
34992   }
34993
34994   return SQLITE_OK;
34995 }
34996
34997 /*
34998 ** The argument is the first in a linked list of dirty pages connected
34999 ** by the PgHdr.pDirty pointer. This function writes each one of the
35000 ** in-memory pages in the list to the database file. The argument may
35001 ** be NULL, representing an empty list. In this case this function is
35002 ** a no-op.
35003 **
35004 ** The pager must hold at least a RESERVED lock when this function
35005 ** is called. Before writing anything to the database file, this lock
35006 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
35007 ** SQLITE_BUSY is returned and no data is written to the database file.
35008 ** 
35009 ** If the pager is a temp-file pager and the actual file-system file
35010 ** is not yet open, it is created and opened before any data is 
35011 ** written out.
35012 **
35013 ** Once the lock has been upgraded and, if necessary, the file opened,
35014 ** the pages are written out to the database file in list order. Writing
35015 ** a page is skipped if it meets either of the following criteria:
35016 **
35017 **   * The page number is greater than Pager.dbSize, or
35018 **   * The PGHDR_DONT_WRITE flag is set on the page.
35019 **
35020 ** If writing out a page causes the database file to grow, Pager.dbFileSize
35021 ** is updated accordingly. If page 1 is written out, then the value cached
35022 ** in Pager.dbFileVers[] is updated to match the new value stored in
35023 ** the database file.
35024 **
35025 ** If everything is successful, SQLITE_OK is returned. If an IO error 
35026 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
35027 ** be obtained, SQLITE_BUSY is returned.
35028 */
35029 static int pager_write_pagelist(PgHdr *pList){
35030   Pager *pPager;                       /* Pager object */
35031   int rc;                              /* Return code */
35032
35033   if( NEVER(pList==0) ) return SQLITE_OK;
35034   pPager = pList->pPager;
35035
35036   /* At this point there may be either a RESERVED or EXCLUSIVE lock on the
35037   ** database file. If there is already an EXCLUSIVE lock, the following
35038   ** call is a no-op.
35039   **
35040   ** Moving the lock from RESERVED to EXCLUSIVE actually involves going
35041   ** through an intermediate state PENDING.   A PENDING lock prevents new
35042   ** readers from attaching to the database but is unsufficient for us to
35043   ** write.  The idea of a PENDING lock is to prevent new readers from
35044   ** coming in while we wait for existing readers to clear.
35045   **
35046   ** While the pager is in the RESERVED state, the original database file
35047   ** is unchanged and we can rollback without having to playback the
35048   ** journal into the original database file.  Once we transition to
35049   ** EXCLUSIVE, it means the database file has been changed and any rollback
35050   ** will require a journal playback.
35051   */
35052   assert( pPager->state>=PAGER_RESERVED );
35053   rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
35054
35055   /* If the file is a temp-file has not yet been opened, open it now. It
35056   ** is not possible for rc to be other than SQLITE_OK if this branch
35057   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
35058   */
35059   if( !isOpen(pPager->fd) ){
35060     assert( pPager->tempFile && rc==SQLITE_OK );
35061     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
35062   }
35063
35064   while( rc==SQLITE_OK && pList ){
35065     Pgno pgno = pList->pgno;
35066
35067     /* If there are dirty pages in the page cache with page numbers greater
35068     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
35069     ** make the file smaller (presumably by auto-vacuum code). Do not write
35070     ** any such pages to the file.
35071     **
35072     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
35073     ** set (set by sqlite3PagerDontWrite()).
35074     */
35075     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
35076       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
35077       char *pData;                                   /* Data to write */    
35078
35079       /* Encode the database */
35080       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
35081
35082       /* Write out the page data. */
35083       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
35084
35085       /* If page 1 was just written, update Pager.dbFileVers to match
35086       ** the value now stored in the database file. If writing this 
35087       ** page caused the database file to grow, update dbFileSize. 
35088       */
35089       if( pgno==1 ){
35090         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
35091       }
35092       if( pgno>pPager->dbFileSize ){
35093         pPager->dbFileSize = pgno;
35094       }
35095
35096       /* Update any backup objects copying the contents of this pager. */
35097       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
35098
35099       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
35100                    PAGERID(pPager), pgno, pager_pagehash(pList)));
35101       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
35102       PAGER_INCR(sqlite3_pager_writedb_count);
35103       PAGER_INCR(pPager->nWrite);
35104     }else{
35105       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
35106     }
35107 #ifdef SQLITE_CHECK_PAGES
35108     pList->pageHash = pager_pagehash(pList);
35109 #endif
35110     pList = pList->pDirty;
35111   }
35112
35113   return rc;
35114 }
35115
35116 /*
35117 ** Append a record of the current state of page pPg to the sub-journal. 
35118 ** It is the callers responsibility to use subjRequiresPage() to check 
35119 ** that it is really required before calling this function.
35120 **
35121 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
35122 ** for all open savepoints before returning.
35123 **
35124 ** This function returns SQLITE_OK if everything is successful, an IO
35125 ** error code if the attempt to write to the sub-journal fails, or 
35126 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
35127 ** bitvec.
35128 */
35129 static int subjournalPage(PgHdr *pPg){
35130   int rc = SQLITE_OK;
35131   Pager *pPager = pPg->pPager;
35132   if( isOpen(pPager->sjfd) ){
35133     void *pData = pPg->pData;
35134     i64 offset = pPager->nSubRec*(4+pPager->pageSize);
35135     char *pData2;
35136
35137     CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
35138     PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
35139   
35140     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
35141     rc = write32bits(pPager->sjfd, offset, pPg->pgno);
35142     if( rc==SQLITE_OK ){
35143       rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
35144     }
35145   }
35146   if( rc==SQLITE_OK ){
35147     pPager->nSubRec++;
35148     assert( pPager->nSavepoint>0 );
35149     rc = addToSavepointBitvecs(pPager, pPg->pgno);
35150   }
35151   return rc;
35152 }
35153
35154
35155 /*
35156 ** This function is called by the pcache layer when it has reached some
35157 ** soft memory limit. The first argument is a pointer to a Pager object
35158 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
35159 ** database). The second argument is a reference to a page that is 
35160 ** currently dirty but has no outstanding references. The page
35161 ** is always associated with the Pager object passed as the first 
35162 ** argument.
35163 **
35164 ** The job of this function is to make pPg clean by writing its contents
35165 ** out to the database file, if possible. This may involve syncing the
35166 ** journal file. 
35167 **
35168 ** If successful, sqlite3PcacheMakeClean() is called on the page and
35169 ** SQLITE_OK returned. If an IO error occurs while trying to make the
35170 ** page clean, the IO error code is returned. If the page cannot be
35171 ** made clean for some other reason, but no error occurs, then SQLITE_OK
35172 ** is returned by sqlite3PcacheMakeClean() is not called.
35173 */
35174 static int pagerStress(void *p, PgHdr *pPg){
35175   Pager *pPager = (Pager *)p;
35176   int rc = SQLITE_OK;
35177
35178   assert( pPg->pPager==pPager );
35179   assert( pPg->flags&PGHDR_DIRTY );
35180
35181   /* The doNotSync flag is set by the sqlite3PagerWrite() function while it
35182   ** is journalling a set of two or more database pages that are stored
35183   ** on the same disk sector. Syncing the journal is not allowed while
35184   ** this is happening as it is important that all members of such a
35185   ** set of pages are synced to disk together. So, if the page this function
35186   ** is trying to make clean will require a journal sync and the doNotSync
35187   ** flag is set, return without doing anything. The pcache layer will
35188   ** just have to go ahead and allocate a new page buffer instead of
35189   ** reusing pPg.
35190   **
35191   ** Similarly, if the pager has already entered the error state, do not
35192   ** try to write the contents of pPg to disk.
35193   */
35194   if( NEVER(pPager->errCode)
35195    || (pPager->doNotSync && pPg->flags&PGHDR_NEED_SYNC)
35196   ){
35197     return SQLITE_OK;
35198   }
35199
35200   /* Sync the journal file if required. */
35201   if( pPg->flags&PGHDR_NEED_SYNC ){
35202     rc = syncJournal(pPager);
35203     if( rc==SQLITE_OK && pPager->fullSync && 
35204       !(pPager->journalMode==PAGER_JOURNALMODE_MEMORY) &&
35205       !(sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
35206     ){
35207       pPager->nRec = 0;
35208       rc = writeJournalHdr(pPager);
35209     }
35210   }
35211
35212   /* If the page number of this page is larger than the current size of
35213   ** the database image, it may need to be written to the sub-journal.
35214   ** This is because the call to pager_write_pagelist() below will not
35215   ** actually write data to the file in this case.
35216   **
35217   ** Consider the following sequence of events:
35218   **
35219   **   BEGIN;
35220   **     <journal page X>
35221   **     <modify page X>
35222   **     SAVEPOINT sp;
35223   **       <shrink database file to Y pages>
35224   **       pagerStress(page X)
35225   **     ROLLBACK TO sp;
35226   **
35227   ** If (X>Y), then when pagerStress is called page X will not be written
35228   ** out to the database file, but will be dropped from the cache. Then,
35229   ** following the "ROLLBACK TO sp" statement, reading page X will read
35230   ** data from the database file. This will be the copy of page X as it
35231   ** was when the transaction started, not as it was when "SAVEPOINT sp"
35232   ** was executed.
35233   **
35234   ** The solution is to write the current data for page X into the 
35235   ** sub-journal file now (if it is not already there), so that it will
35236   ** be restored to its current value when the "ROLLBACK TO sp" is 
35237   ** executed.
35238   */
35239   if( NEVER(
35240       rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
35241   ) ){
35242     rc = subjournalPage(pPg);
35243   }
35244
35245   /* Write the contents of the page out to the database file. */
35246   if( rc==SQLITE_OK ){
35247     pPg->pDirty = 0;
35248     rc = pager_write_pagelist(pPg);
35249   }
35250
35251   /* Mark the page as clean. */
35252   if( rc==SQLITE_OK ){
35253     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
35254     sqlite3PcacheMakeClean(pPg);
35255   }
35256
35257   return pager_error(pPager, rc);
35258 }
35259
35260
35261 /*
35262 ** Allocate and initialize a new Pager object and put a pointer to it
35263 ** in *ppPager. The pager should eventually be freed by passing it
35264 ** to sqlite3PagerClose().
35265 **
35266 ** The zFilename argument is the path to the database file to open.
35267 ** If zFilename is NULL then a randomly-named temporary file is created
35268 ** and used as the file to be cached. Temporary files are be deleted
35269 ** automatically when they are closed. If zFilename is ":memory:" then 
35270 ** all information is held in cache. It is never written to disk. 
35271 ** This can be used to implement an in-memory database.
35272 **
35273 ** The nExtra parameter specifies the number of bytes of space allocated
35274 ** along with each page reference. This space is available to the user
35275 ** via the sqlite3PagerGetExtra() API.
35276 **
35277 ** The flags argument is used to specify properties that affect the
35278 ** operation of the pager. It should be passed some bitwise combination
35279 ** of the PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK flags.
35280 **
35281 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
35282 ** of the xOpen() method of the supplied VFS when opening files. 
35283 **
35284 ** If the pager object is allocated and the specified file opened 
35285 ** successfully, SQLITE_OK is returned and *ppPager set to point to
35286 ** the new pager object. If an error occurs, *ppPager is set to NULL
35287 ** and error code returned. This function may return SQLITE_NOMEM
35288 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
35289 ** various SQLITE_IO_XXX errors.
35290 */
35291 SQLITE_PRIVATE int sqlite3PagerOpen(
35292   sqlite3_vfs *pVfs,       /* The virtual file system to use */
35293   Pager **ppPager,         /* OUT: Return the Pager structure here */
35294   const char *zFilename,   /* Name of the database file to open */
35295   int nExtra,              /* Extra bytes append to each in-memory page */
35296   int flags,               /* flags controlling this file */
35297   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
35298   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
35299 ){
35300   u8 *pPtr;
35301   Pager *pPager = 0;       /* Pager object to allocate and return */
35302   int rc = SQLITE_OK;      /* Return code */
35303   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
35304   int memDb = 0;           /* True if this is an in-memory file */
35305   int readOnly = 0;        /* True if this is a read-only file */
35306   int journalFileSize;     /* Bytes to allocate for each journal fd */
35307   char *zPathname = 0;     /* Full path to database file */
35308   int nPathname = 0;       /* Number of bytes in zPathname */
35309   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
35310   int noReadlock = (flags & PAGER_NO_READLOCK)!=0;  /* True to omit read-lock */
35311   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
35312   u16 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
35313
35314   /* Figure out how much space is required for each journal file-handle
35315   ** (there are two of them, the main journal and the sub-journal). This
35316   ** is the maximum space required for an in-memory journal file handle 
35317   ** and a regular journal file-handle. Note that a "regular journal-handle"
35318   ** may be a wrapper capable of caching the first portion of the journal
35319   ** file in memory to implement the atomic-write optimization (see 
35320   ** source file journal.c).
35321   */
35322   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
35323     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
35324   }else{
35325     journalFileSize = ROUND8(sqlite3MemJournalSize());
35326   }
35327
35328   /* Set the output variable to NULL in case an error occurs. */
35329   *ppPager = 0;
35330
35331   /* Compute and store the full pathname in an allocated buffer pointed
35332   ** to by zPathname, length nPathname. Or, if this is a temporary file,
35333   ** leave both nPathname and zPathname set to 0.
35334   */
35335   if( zFilename && zFilename[0] ){
35336     nPathname = pVfs->mxPathname+1;
35337     zPathname = sqlite3Malloc(nPathname*2);
35338     if( zPathname==0 ){
35339       return SQLITE_NOMEM;
35340     }
35341 #ifndef SQLITE_OMIT_MEMORYDB
35342     if( strcmp(zFilename,":memory:")==0 ){
35343       memDb = 1;
35344       zPathname[0] = 0;
35345     }else
35346 #endif
35347     {
35348       zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
35349       rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
35350     }
35351
35352     nPathname = sqlite3Strlen30(zPathname);
35353     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
35354       /* This branch is taken when the journal path required by
35355       ** the database being opened will be more than pVfs->mxPathname
35356       ** bytes in length. This means the database cannot be opened,
35357       ** as it will not be possible to open the journal file or even
35358       ** check for a hot-journal before reading.
35359       */
35360       rc = SQLITE_CANTOPEN_BKPT;
35361     }
35362     if( rc!=SQLITE_OK ){
35363       sqlite3_free(zPathname);
35364       return rc;
35365     }
35366   }
35367
35368   /* Allocate memory for the Pager structure, PCache object, the
35369   ** three file descriptors, the database file name and the journal 
35370   ** file name. The layout in memory is as follows:
35371   **
35372   **     Pager object                    (sizeof(Pager) bytes)
35373   **     PCache object                   (sqlite3PcacheSize() bytes)
35374   **     Database file handle            (pVfs->szOsFile bytes)
35375   **     Sub-journal file handle         (journalFileSize bytes)
35376   **     Main journal file handle        (journalFileSize bytes)
35377   **     Database file name              (nPathname+1 bytes)
35378   **     Journal file name               (nPathname+8+1 bytes)
35379   */
35380   pPtr = (u8 *)sqlite3MallocZero(
35381     ROUND8(sizeof(*pPager)) +      /* Pager structure */
35382     ROUND8(pcacheSize) +           /* PCache object */
35383     ROUND8(pVfs->szOsFile) +       /* The main db file */
35384     journalFileSize * 2 +          /* The two journal files */ 
35385     nPathname + 1 +                /* zFilename */
35386     nPathname + 8 + 1              /* zJournal */
35387   );
35388   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
35389   if( !pPtr ){
35390     sqlite3_free(zPathname);
35391     return SQLITE_NOMEM;
35392   }
35393   pPager =              (Pager*)(pPtr);
35394   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
35395   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
35396   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
35397   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
35398   pPager->zFilename =    (char*)(pPtr += journalFileSize);
35399   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
35400
35401   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
35402   if( zPathname ){
35403     pPager->zJournal =   (char*)(pPtr += nPathname + 1);
35404     memcpy(pPager->zFilename, zPathname, nPathname);
35405     memcpy(pPager->zJournal, zPathname, nPathname);
35406     memcpy(&pPager->zJournal[nPathname], "-journal", 8);
35407     if( pPager->zFilename[0]==0 ) pPager->zJournal[0] = 0;
35408     sqlite3_free(zPathname);
35409   }
35410   pPager->pVfs = pVfs;
35411   pPager->vfsFlags = vfsFlags;
35412
35413   /* Open the pager file.
35414   */
35415   if( zFilename && zFilename[0] && !memDb ){
35416     int fout = 0;                    /* VFS flags returned by xOpen() */
35417     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
35418     readOnly = (fout&SQLITE_OPEN_READONLY);
35419
35420     /* If the file was successfully opened for read/write access,
35421     ** choose a default page size in case we have to create the
35422     ** database file. The default page size is the maximum of:
35423     **
35424     **    + SQLITE_DEFAULT_PAGE_SIZE,
35425     **    + The value returned by sqlite3OsSectorSize()
35426     **    + The largest page size that can be written atomically.
35427     */
35428     if( rc==SQLITE_OK && !readOnly ){
35429       setSectorSize(pPager);
35430       assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
35431       if( szPageDflt<pPager->sectorSize ){
35432         if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
35433           szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
35434         }else{
35435           szPageDflt = (u16)pPager->sectorSize;
35436         }
35437       }
35438 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
35439       {
35440         int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
35441         int ii;
35442         assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
35443         assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
35444         assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
35445         for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
35446           if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
35447             szPageDflt = ii;
35448           }
35449         }
35450       }
35451 #endif
35452     }
35453   }else{
35454     /* If a temporary file is requested, it is not opened immediately.
35455     ** In this case we accept the default page size and delay actually
35456     ** opening the file until the first call to OsWrite().
35457     **
35458     ** This branch is also run for an in-memory database. An in-memory
35459     ** database is the same as a temp-file that is never written out to
35460     ** disk and uses an in-memory rollback journal.
35461     */ 
35462     tempFile = 1;
35463     pPager->state = PAGER_EXCLUSIVE;
35464     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
35465   }
35466
35467   /* The following call to PagerSetPagesize() serves to set the value of 
35468   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
35469   */
35470   if( rc==SQLITE_OK ){
35471     assert( pPager->memDb==0 );
35472     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
35473     testcase( rc!=SQLITE_OK );
35474   }
35475
35476   /* If an error occurred in either of the blocks above, free the 
35477   ** Pager structure and close the file.
35478   */
35479   if( rc!=SQLITE_OK ){
35480     assert( !pPager->pTmpSpace );
35481     sqlite3OsClose(pPager->fd);
35482     sqlite3_free(pPager);
35483     return rc;
35484   }
35485
35486   /* Initialize the PCache object. */
35487   assert( nExtra<1000 );
35488   nExtra = ROUND8(nExtra);
35489   sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
35490                     !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
35491
35492   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
35493   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
35494
35495   pPager->useJournal = (u8)useJournal;
35496   pPager->noReadlock = (noReadlock && readOnly) ?1:0;
35497   /* pPager->stmtOpen = 0; */
35498   /* pPager->stmtInUse = 0; */
35499   /* pPager->nRef = 0; */
35500   pPager->dbSizeValid = (u8)memDb;
35501   /* pPager->stmtSize = 0; */
35502   /* pPager->stmtJSize = 0; */
35503   /* pPager->nPage = 0; */
35504   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
35505   /* pPager->state = PAGER_UNLOCK; */
35506   assert( pPager->state == (tempFile ? PAGER_EXCLUSIVE : PAGER_UNLOCK) );
35507   /* pPager->errMask = 0; */
35508   pPager->tempFile = (u8)tempFile;
35509   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
35510           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
35511   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
35512   pPager->exclusiveMode = (u8)tempFile; 
35513   pPager->changeCountDone = pPager->tempFile;
35514   pPager->memDb = (u8)memDb;
35515   pPager->readOnly = (u8)readOnly;
35516   /* pPager->needSync = 0; */
35517   assert( useJournal || pPager->tempFile );
35518   pPager->noSync = pPager->tempFile;
35519   pPager->fullSync = pPager->noSync ?0:1;
35520   pPager->sync_flags = SQLITE_SYNC_NORMAL;
35521   /* pPager->pFirst = 0; */
35522   /* pPager->pFirstSynced = 0; */
35523   /* pPager->pLast = 0; */
35524   pPager->nExtra = (u16)nExtra;
35525   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
35526   assert( isOpen(pPager->fd) || tempFile );
35527   setSectorSize(pPager);
35528   if( !useJournal ){
35529     pPager->journalMode = PAGER_JOURNALMODE_OFF;
35530   }else if( memDb ){
35531     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
35532   }
35533   /* pPager->xBusyHandler = 0; */
35534   /* pPager->pBusyHandlerArg = 0; */
35535   pPager->xReiniter = xReinit;
35536   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
35537
35538   *ppPager = pPager;
35539   return SQLITE_OK;
35540 }
35541
35542
35543
35544 /*
35545 ** This function is called after transitioning from PAGER_UNLOCK to
35546 ** PAGER_SHARED state. It tests if there is a hot journal present in
35547 ** the file-system for the given pager. A hot journal is one that 
35548 ** needs to be played back. According to this function, a hot-journal
35549 ** file exists if the following criteria are met:
35550 **
35551 **   * The journal file exists in the file system, and
35552 **   * No process holds a RESERVED or greater lock on the database file, and
35553 **   * The database file itself is greater than 0 bytes in size, and
35554 **   * The first byte of the journal file exists and is not 0x00.
35555 **
35556 ** If the current size of the database file is 0 but a journal file
35557 ** exists, that is probably an old journal left over from a prior
35558 ** database with the same name. In this case the journal file is
35559 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
35560 ** is returned.
35561 **
35562 ** This routine does not check if there is a master journal filename
35563 ** at the end of the file. If there is, and that master journal file
35564 ** does not exist, then the journal file is not really hot. In this
35565 ** case this routine will return a false-positive. The pager_playback()
35566 ** routine will discover that the journal file is not really hot and 
35567 ** will not roll it back. 
35568 **
35569 ** If a hot-journal file is found to exist, *pExists is set to 1 and 
35570 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
35571 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
35572 ** to determine whether or not a hot-journal file exists, the IO error
35573 ** code is returned and the value of *pExists is undefined.
35574 */
35575 static int hasHotJournal(Pager *pPager, int *pExists){
35576   sqlite3_vfs * const pVfs = pPager->pVfs;
35577   int rc;                       /* Return code */
35578   int exists;                   /* True if a journal file is present */
35579
35580   assert( pPager!=0 );
35581   assert( pPager->useJournal );
35582   assert( isOpen(pPager->fd) );
35583   assert( !isOpen(pPager->jfd) );
35584   assert( pPager->state <= PAGER_SHARED );
35585
35586   *pExists = 0;
35587   rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
35588   if( rc==SQLITE_OK && exists ){
35589     int locked;                 /* True if some process holds a RESERVED lock */
35590
35591     /* Race condition here:  Another process might have been holding the
35592     ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
35593     ** call above, but then delete the journal and drop the lock before
35594     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
35595     ** is the case, this routine might think there is a hot journal when
35596     ** in fact there is none.  This results in a false-positive which will
35597     ** be dealt with by the playback routine.  Ticket #3883.
35598     */
35599     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
35600     if( rc==SQLITE_OK && !locked ){
35601       int nPage;
35602
35603       /* Check the size of the database file. If it consists of 0 pages,
35604       ** then delete the journal file. See the header comment above for 
35605       ** the reasoning here.  Delete the obsolete journal file under
35606       ** a RESERVED lock to avoid race conditions and to avoid violating
35607       ** [H33020].
35608       */
35609       rc = sqlite3PagerPagecount(pPager, &nPage);
35610       if( rc==SQLITE_OK ){
35611         if( nPage==0 ){
35612           sqlite3BeginBenignMalloc();
35613           if( sqlite3OsLock(pPager->fd, RESERVED_LOCK)==SQLITE_OK ){
35614             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
35615             sqlite3OsUnlock(pPager->fd, SHARED_LOCK);
35616           }
35617           sqlite3EndBenignMalloc();
35618         }else{
35619           /* The journal file exists and no other connection has a reserved
35620           ** or greater lock on the database file. Now check that there is
35621           ** at least one non-zero bytes at the start of the journal file.
35622           ** If there is, then we consider this journal to be hot. If not, 
35623           ** it can be ignored.
35624           */
35625           int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
35626           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
35627           if( rc==SQLITE_OK ){
35628             u8 first = 0;
35629             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
35630             if( rc==SQLITE_IOERR_SHORT_READ ){
35631               rc = SQLITE_OK;
35632             }
35633             sqlite3OsClose(pPager->jfd);
35634             *pExists = (first!=0);
35635           }else if( rc==SQLITE_CANTOPEN ){
35636             /* If we cannot open the rollback journal file in order to see if
35637             ** its has a zero header, that might be due to an I/O error, or
35638             ** it might be due to the race condition described above and in
35639             ** ticket #3883.  Either way, assume that the journal is hot.
35640             ** This might be a false positive.  But if it is, then the
35641             ** automatic journal playback and recovery mechanism will deal
35642             ** with it under an EXCLUSIVE lock where we do not need to
35643             ** worry so much with race conditions.
35644             */
35645             *pExists = 1;
35646             rc = SQLITE_OK;
35647           }
35648         }
35649       }
35650     }
35651   }
35652
35653   return rc;
35654 }
35655
35656 /*
35657 ** Read the content for page pPg out of the database file and into 
35658 ** pPg->pData. A shared lock or greater must be held on the database
35659 ** file before this function is called.
35660 **
35661 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
35662 ** the value read from the database file.
35663 **
35664 ** If an IO error occurs, then the IO error is returned to the caller.
35665 ** Otherwise, SQLITE_OK is returned.
35666 */
35667 static int readDbPage(PgHdr *pPg){
35668   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
35669   Pgno pgno = pPg->pgno;       /* Page number to read */
35670   int rc;                      /* Return code */
35671   i64 iOffset;                 /* Byte offset of file to read from */
35672
35673   assert( pPager->state>=PAGER_SHARED && !MEMDB );
35674   assert( isOpen(pPager->fd) );
35675
35676   if( NEVER(!isOpen(pPager->fd)) ){
35677     assert( pPager->tempFile );
35678     memset(pPg->pData, 0, pPager->pageSize);
35679     return SQLITE_OK;
35680   }
35681   iOffset = (pgno-1)*(i64)pPager->pageSize;
35682   rc = sqlite3OsRead(pPager->fd, pPg->pData, pPager->pageSize, iOffset);
35683   if( rc==SQLITE_IOERR_SHORT_READ ){
35684     rc = SQLITE_OK;
35685   }
35686   if( pgno==1 ){
35687     if( rc ){
35688       /* If the read is unsuccessful, set the dbFileVers[] to something
35689       ** that will never be a valid file version.  dbFileVers[] is a copy
35690       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
35691       ** zero.  Bytes 32..35 and 35..39 should be page numbers which are
35692       ** never 0xffffffff.  So filling pPager->dbFileVers[] with all 0xff
35693       ** bytes should suffice.
35694       **
35695       ** For an encrypted database, the situation is more complex:  bytes
35696       ** 24..39 of the database are white noise.  But the probability of
35697       ** white noising equaling 16 bytes of 0xff is vanishingly small so
35698       ** we should still be ok.
35699       */
35700       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
35701     }else{
35702       u8 *dbFileVers = &((u8*)pPg->pData)[24];
35703       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
35704     }
35705   }
35706   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
35707
35708   PAGER_INCR(sqlite3_pager_readdb_count);
35709   PAGER_INCR(pPager->nRead);
35710   IOTRACE(("PGIN %p %d\n", pPager, pgno));
35711   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
35712                PAGERID(pPager), pgno, pager_pagehash(pPg)));
35713
35714   return rc;
35715 }
35716
35717 /*
35718 ** This function is called to obtain a shared lock on the database file.
35719 ** It is illegal to call sqlite3PagerAcquire() until after this function
35720 ** has been successfully called. If a shared-lock is already held when
35721 ** this function is called, it is a no-op.
35722 **
35723 ** The following operations are also performed by this function.
35724 **
35725 **   1) If the pager is currently in PAGER_UNLOCK state (no lock held
35726 **      on the database file), then an attempt is made to obtain a
35727 **      SHARED lock on the database file. Immediately after obtaining
35728 **      the SHARED lock, the file-system is checked for a hot-journal,
35729 **      which is played back if present. Following any hot-journal 
35730 **      rollback, the contents of the cache are validated by checking
35731 **      the 'change-counter' field of the database file header and
35732 **      discarded if they are found to be invalid.
35733 **
35734 **   2) If the pager is running in exclusive-mode, and there are currently
35735 **      no outstanding references to any pages, and is in the error state,
35736 **      then an attempt is made to clear the error state by discarding
35737 **      the contents of the page cache and rolling back any open journal
35738 **      file.
35739 **
35740 ** If the operation described by (2) above is not attempted, and if the
35741 ** pager is in an error state other than SQLITE_FULL when this is called,
35742 ** the error state error code is returned. It is permitted to read the
35743 ** database when in SQLITE_FULL error state.
35744 **
35745 ** Otherwise, if everything is successful, SQLITE_OK is returned. If an
35746 ** IO error occurs while locking the database, checking for a hot-journal
35747 ** file or rolling back a journal file, the IO error code is returned.
35748 */
35749 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
35750   int rc = SQLITE_OK;                /* Return code */
35751   int isErrorReset = 0;              /* True if recovering from error state */
35752
35753   /* This routine is only called from b-tree and only when there are no
35754   ** outstanding pages */
35755   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
35756   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
35757
35758   /* If this database is in an error-state, now is a chance to clear
35759   ** the error. Discard the contents of the pager-cache and rollback
35760   ** any hot journal in the file-system.
35761   */
35762   if( pPager->errCode ){
35763     if( isOpen(pPager->jfd) || pPager->zJournal ){
35764       isErrorReset = 1;
35765     }
35766     pPager->errCode = SQLITE_OK;
35767     pager_reset(pPager);
35768   }
35769
35770   if( pPager->state==PAGER_UNLOCK || isErrorReset ){
35771     sqlite3_vfs * const pVfs = pPager->pVfs;
35772     int isHotJournal = 0;
35773     assert( !MEMDB );
35774     assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
35775     if( pPager->noReadlock ){
35776       assert( pPager->readOnly );
35777       pPager->state = PAGER_SHARED;
35778     }else{
35779       rc = pager_wait_on_lock(pPager, SHARED_LOCK);
35780       if( rc!=SQLITE_OK ){
35781         assert( pPager->state==PAGER_UNLOCK );
35782         return pager_error(pPager, rc);
35783       }
35784     }
35785     assert( pPager->state>=SHARED_LOCK );
35786
35787     /* If a journal file exists, and there is no RESERVED lock on the
35788     ** database file, then it either needs to be played back or deleted.
35789     */
35790     if( !isErrorReset ){
35791       assert( pPager->state <= PAGER_SHARED );
35792       rc = hasHotJournal(pPager, &isHotJournal);
35793       if( rc!=SQLITE_OK ){
35794         goto failed;
35795       }
35796     }
35797     if( isErrorReset || isHotJournal ){
35798       /* Get an EXCLUSIVE lock on the database file. At this point it is
35799       ** important that a RESERVED lock is not obtained on the way to the
35800       ** EXCLUSIVE lock. If it were, another process might open the
35801       ** database file, detect the RESERVED lock, and conclude that the
35802       ** database is safe to read while this process is still rolling the 
35803       ** hot-journal back.
35804       ** 
35805       ** Because the intermediate RESERVED lock is not requested, any
35806       ** other process attempting to access the database file will get to 
35807       ** this point in the code and fail to obtain its own EXCLUSIVE lock 
35808       ** on the database file.
35809       */
35810       if( pPager->state<EXCLUSIVE_LOCK ){
35811         rc = sqlite3OsLock(pPager->fd, EXCLUSIVE_LOCK);
35812         if( rc!=SQLITE_OK ){
35813           rc = pager_error(pPager, rc);
35814           goto failed;
35815         }
35816         pPager->state = PAGER_EXCLUSIVE;
35817       }
35818  
35819       /* Open the journal for read/write access. This is because in 
35820       ** exclusive-access mode the file descriptor will be kept open and
35821       ** possibly used for a transaction later on. On some systems, the
35822       ** OsTruncate() call used in exclusive-access mode also requires
35823       ** a read/write file handle.
35824       */
35825       if( !isOpen(pPager->jfd) ){
35826         int res;
35827         rc = sqlite3OsAccess(pVfs,pPager->zJournal,SQLITE_ACCESS_EXISTS,&res);
35828         if( rc==SQLITE_OK ){
35829           if( res ){
35830             int fout = 0;
35831             int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
35832             assert( !pPager->tempFile );
35833             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
35834             assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
35835             if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
35836               rc = SQLITE_CANTOPEN_BKPT;
35837               sqlite3OsClose(pPager->jfd);
35838             }
35839           }else{
35840             /* If the journal does not exist, it usually means that some 
35841             ** other connection managed to get in and roll it back before 
35842             ** this connection obtained the exclusive lock above. Or, it 
35843             ** may mean that the pager was in the error-state when this
35844             ** function was called and the journal file does not exist.  */
35845             rc = pager_end_transaction(pPager, 0);
35846           }
35847         }
35848       }
35849       if( rc!=SQLITE_OK ){
35850         goto failed;
35851       }
35852
35853       /* TODO: Why are these cleared here? Is it necessary? */
35854       pPager->journalStarted = 0;
35855       pPager->journalOff = 0;
35856       pPager->setMaster = 0;
35857       pPager->journalHdr = 0;
35858  
35859       /* Playback and delete the journal.  Drop the database write
35860       ** lock and reacquire the read lock. Purge the cache before
35861       ** playing back the hot-journal so that we don't end up with
35862       ** an inconsistent cache.
35863       */
35864       if( isOpen(pPager->jfd) ){
35865         rc = pager_playback(pPager, 1);
35866         if( rc!=SQLITE_OK ){
35867           rc = pager_error(pPager, rc);
35868           goto failed;
35869         }
35870       }
35871       assert( (pPager->state==PAGER_SHARED)
35872            || (pPager->exclusiveMode && pPager->state>PAGER_SHARED)
35873       );
35874     }
35875
35876     if( pPager->pBackup || sqlite3PcachePagecount(pPager->pPCache)>0 ){
35877       /* The shared-lock has just been acquired on the database file
35878       ** and there are already pages in the cache (from a previous
35879       ** read or write transaction).  Check to see if the database
35880       ** has been modified.  If the database has changed, flush the
35881       ** cache.
35882       **
35883       ** Database changes is detected by looking at 15 bytes beginning
35884       ** at offset 24 into the file.  The first 4 of these 16 bytes are
35885       ** a 32-bit counter that is incremented with each change.  The
35886       ** other bytes change randomly with each file change when
35887       ** a codec is in use.
35888       ** 
35889       ** There is a vanishingly small chance that a change will not be 
35890       ** detected.  The chance of an undetected change is so small that
35891       ** it can be neglected.
35892       */
35893       char dbFileVers[sizeof(pPager->dbFileVers)];
35894       sqlite3PagerPagecount(pPager, 0);
35895
35896       if( pPager->errCode ){
35897         rc = pPager->errCode;
35898         goto failed;
35899       }
35900
35901       assert( pPager->dbSizeValid );
35902       if( pPager->dbSize>0 ){
35903         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
35904         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
35905         if( rc!=SQLITE_OK ){
35906           goto failed;
35907         }
35908       }else{
35909         memset(dbFileVers, 0, sizeof(dbFileVers));
35910       }
35911
35912       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
35913         pager_reset(pPager);
35914       }
35915     }
35916     assert( pPager->exclusiveMode || pPager->state==PAGER_SHARED );
35917   }
35918
35919  failed:
35920   if( rc!=SQLITE_OK ){
35921     /* pager_unlock() is a no-op for exclusive mode and in-memory databases. */
35922     pager_unlock(pPager);
35923   }
35924   return rc;
35925 }
35926
35927 /*
35928 ** If the reference count has reached zero, rollback any active
35929 ** transaction and unlock the pager.
35930 **
35931 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
35932 ** the rollback journal, the unlock is not performed and there is
35933 ** nothing to rollback, so this routine is a no-op.
35934 */ 
35935 static void pagerUnlockIfUnused(Pager *pPager){
35936   if( (sqlite3PcacheRefCount(pPager->pPCache)==0)
35937    && (!pPager->exclusiveMode || pPager->journalOff>0) 
35938   ){
35939     pagerUnlockAndRollback(pPager);
35940   }
35941 }
35942
35943 /*
35944 ** Acquire a reference to page number pgno in pager pPager (a page
35945 ** reference has type DbPage*). If the requested reference is 
35946 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
35947 **
35948 ** If the requested page is already in the cache, it is returned. 
35949 ** Otherwise, a new page object is allocated and populated with data
35950 ** read from the database file. In some cases, the pcache module may
35951 ** choose not to allocate a new page object and may reuse an existing
35952 ** object with no outstanding references.
35953 **
35954 ** The extra data appended to a page is always initialized to zeros the 
35955 ** first time a page is loaded into memory. If the page requested is 
35956 ** already in the cache when this function is called, then the extra
35957 ** data is left as it was when the page object was last used.
35958 **
35959 ** If the database image is smaller than the requested page or if a 
35960 ** non-zero value is passed as the noContent parameter and the 
35961 ** requested page is not already stored in the cache, then no 
35962 ** actual disk read occurs. In this case the memory image of the 
35963 ** page is initialized to all zeros. 
35964 **
35965 ** If noContent is true, it means that we do not care about the contents
35966 ** of the page. This occurs in two seperate scenarios:
35967 **
35968 **   a) When reading a free-list leaf page from the database, and
35969 **
35970 **   b) When a savepoint is being rolled back and we need to load
35971 **      a new page into the cache to populate with the data read
35972 **      from the savepoint journal.
35973 **
35974 ** If noContent is true, then the data returned is zeroed instead of
35975 ** being read from the database. Additionally, the bits corresponding
35976 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
35977 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
35978 ** savepoints are set. This means if the page is made writable at any
35979 ** point in the future, using a call to sqlite3PagerWrite(), its contents
35980 ** will not be journaled. This saves IO.
35981 **
35982 ** The acquisition might fail for several reasons.  In all cases,
35983 ** an appropriate error code is returned and *ppPage is set to NULL.
35984 **
35985 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
35986 ** to find a page in the in-memory cache first.  If the page is not already
35987 ** in memory, this routine goes to disk to read it in whereas Lookup()
35988 ** just returns 0.  This routine acquires a read-lock the first time it
35989 ** has to go to disk, and could also playback an old journal if necessary.
35990 ** Since Lookup() never goes to disk, it never has to deal with locks
35991 ** or journal files.
35992 */
35993 SQLITE_PRIVATE int sqlite3PagerAcquire(
35994   Pager *pPager,      /* The pager open on the database file */
35995   Pgno pgno,          /* Page number to fetch */
35996   DbPage **ppPage,    /* Write a pointer to the page here */
35997   int noContent       /* Do not bother reading content from disk if true */
35998 ){
35999   int rc;
36000   PgHdr *pPg;
36001
36002   assert( assert_pager_state(pPager) );
36003   assert( pPager->state>PAGER_UNLOCK );
36004
36005   if( pgno==0 ){
36006     return SQLITE_CORRUPT_BKPT;
36007   }
36008
36009   /* If the pager is in the error state, return an error immediately. 
36010   ** Otherwise, request the page from the PCache layer. */
36011   if( pPager->errCode!=SQLITE_OK && pPager->errCode!=SQLITE_FULL ){
36012     rc = pPager->errCode;
36013   }else{
36014     rc = sqlite3PcacheFetch(pPager->pPCache, pgno, 1, ppPage);
36015   }
36016
36017   if( rc!=SQLITE_OK ){
36018     /* Either the call to sqlite3PcacheFetch() returned an error or the
36019     ** pager was already in the error-state when this function was called.
36020     ** Set pPg to 0 and jump to the exception handler.  */
36021     pPg = 0;
36022     goto pager_acquire_err;
36023   }
36024   assert( (*ppPage)->pgno==pgno );
36025   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
36026
36027   if( (*ppPage)->pPager ){
36028     /* In this case the pcache already contains an initialized copy of
36029     ** the page. Return without further ado.  */
36030     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
36031     PAGER_INCR(pPager->nHit);
36032     return SQLITE_OK;
36033
36034   }else{
36035     /* The pager cache has created a new page. Its content needs to 
36036     ** be initialized.  */
36037     int nMax;
36038
36039     PAGER_INCR(pPager->nMiss);
36040     pPg = *ppPage;
36041     pPg->pPager = pPager;
36042
36043     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
36044     ** number greater than this, or the unused locking-page, is requested. */
36045     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
36046       rc = SQLITE_CORRUPT_BKPT;
36047       goto pager_acquire_err;
36048     }
36049
36050     rc = sqlite3PagerPagecount(pPager, &nMax);
36051     if( rc!=SQLITE_OK ){
36052       goto pager_acquire_err;
36053     }
36054
36055     if( MEMDB || nMax<(int)pgno || noContent || !isOpen(pPager->fd) ){
36056       if( pgno>pPager->mxPgno ){
36057         rc = SQLITE_FULL;
36058         goto pager_acquire_err;
36059       }
36060       if( noContent ){
36061         /* Failure to set the bits in the InJournal bit-vectors is benign.
36062         ** It merely means that we might do some extra work to journal a 
36063         ** page that does not need to be journaled.  Nevertheless, be sure 
36064         ** to test the case where a malloc error occurs while trying to set 
36065         ** a bit in a bit vector.
36066         */
36067         sqlite3BeginBenignMalloc();
36068         if( pgno<=pPager->dbOrigSize ){
36069           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
36070           testcase( rc==SQLITE_NOMEM );
36071         }
36072         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
36073         testcase( rc==SQLITE_NOMEM );
36074         sqlite3EndBenignMalloc();
36075       }
36076       memset(pPg->pData, 0, pPager->pageSize);
36077       IOTRACE(("ZERO %p %d\n", pPager, pgno));
36078     }else{
36079       assert( pPg->pPager==pPager );
36080       rc = readDbPage(pPg);
36081       if( rc!=SQLITE_OK ){
36082         goto pager_acquire_err;
36083       }
36084     }
36085 #ifdef SQLITE_CHECK_PAGES
36086     pPg->pageHash = pager_pagehash(pPg);
36087 #endif
36088   }
36089
36090   return SQLITE_OK;
36091
36092 pager_acquire_err:
36093   assert( rc!=SQLITE_OK );
36094   if( pPg ){
36095     sqlite3PcacheDrop(pPg);
36096   }
36097   pagerUnlockIfUnused(pPager);
36098
36099   *ppPage = 0;
36100   return rc;
36101 }
36102
36103 /*
36104 ** Acquire a page if it is already in the in-memory cache.  Do
36105 ** not read the page from disk.  Return a pointer to the page,
36106 ** or 0 if the page is not in cache. Also, return 0 if the 
36107 ** pager is in PAGER_UNLOCK state when this function is called,
36108 ** or if the pager is in an error state other than SQLITE_FULL.
36109 **
36110 ** See also sqlite3PagerGet().  The difference between this routine
36111 ** and sqlite3PagerGet() is that _get() will go to the disk and read
36112 ** in the page if the page is not already in cache.  This routine
36113 ** returns NULL if the page is not in cache or if a disk I/O error 
36114 ** has ever happened.
36115 */
36116 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
36117   PgHdr *pPg = 0;
36118   assert( pPager!=0 );
36119   assert( pgno!=0 );
36120   assert( pPager->pPCache!=0 );
36121   assert( pPager->state > PAGER_UNLOCK );
36122   sqlite3PcacheFetch(pPager->pPCache, pgno, 0, &pPg);
36123   return pPg;
36124 }
36125
36126 /*
36127 ** Release a page reference.
36128 **
36129 ** If the number of references to the page drop to zero, then the
36130 ** page is added to the LRU list.  When all references to all pages
36131 ** are released, a rollback occurs and the lock on the database is
36132 ** removed.
36133 */
36134 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
36135   if( pPg ){
36136     Pager *pPager = pPg->pPager;
36137     sqlite3PcacheRelease(pPg);
36138     pagerUnlockIfUnused(pPager);
36139   }
36140 }
36141
36142 /*
36143 ** If the main journal file has already been opened, ensure that the
36144 ** sub-journal file is open too. If the main journal is not open,
36145 ** this function is a no-op.
36146 **
36147 ** SQLITE_OK is returned if everything goes according to plan. 
36148 ** An SQLITE_IOERR_XXX error code is returned if a call to 
36149 ** sqlite3OsOpen() fails.
36150 */
36151 static int openSubJournal(Pager *pPager){
36152   int rc = SQLITE_OK;
36153   if( isOpen(pPager->jfd) && !isOpen(pPager->sjfd) ){
36154     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
36155       sqlite3MemJournalOpen(pPager->sjfd);
36156     }else{
36157       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
36158     }
36159   }
36160   return rc;
36161 }
36162
36163 /*
36164 ** This function is called at the start of every write transaction.
36165 ** There must already be a RESERVED or EXCLUSIVE lock on the database 
36166 ** file when this routine is called.
36167 **
36168 ** Open the journal file for pager pPager and write a journal header
36169 ** to the start of it. If there are active savepoints, open the sub-journal
36170 ** as well. This function is only used when the journal file is being 
36171 ** opened to write a rollback log for a transaction. It is not used 
36172 ** when opening a hot journal file to roll it back.
36173 **
36174 ** If the journal file is already open (as it may be in exclusive mode),
36175 ** then this function just writes a journal header to the start of the
36176 ** already open file. 
36177 **
36178 ** Whether or not the journal file is opened by this function, the
36179 ** Pager.pInJournal bitvec structure is allocated.
36180 **
36181 ** Return SQLITE_OK if everything is successful. Otherwise, return 
36182 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
36183 ** an IO error code if opening or writing the journal file fails.
36184 */
36185 static int pager_open_journal(Pager *pPager){
36186   int rc = SQLITE_OK;                        /* Return code */
36187   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
36188
36189   assert( pPager->state>=PAGER_RESERVED );
36190   assert( pPager->useJournal );
36191   assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF );
36192   assert( pPager->pInJournal==0 );
36193   
36194   /* If already in the error state, this function is a no-op.  But on
36195   ** the other hand, this routine is never called if we are already in
36196   ** an error state. */
36197   if( NEVER(pPager->errCode) ) return pPager->errCode;
36198
36199   /* TODO: Is it really possible to get here with dbSizeValid==0? If not,
36200   ** the call to PagerPagecount() can be removed.
36201   */
36202   testcase( pPager->dbSizeValid==0 );
36203   sqlite3PagerPagecount(pPager, 0);
36204
36205   pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
36206   if( pPager->pInJournal==0 ){
36207     return SQLITE_NOMEM;
36208   }
36209
36210   /* Open the journal file if it is not already open. */
36211   if( !isOpen(pPager->jfd) ){
36212     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
36213       sqlite3MemJournalOpen(pPager->jfd);
36214     }else{
36215       const int flags =                   /* VFS flags to open journal file */
36216         SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
36217         (pPager->tempFile ? 
36218           (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
36219           (SQLITE_OPEN_MAIN_JOURNAL)
36220         );
36221 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
36222       rc = sqlite3JournalOpen(
36223           pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
36224       );
36225 #else
36226       rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
36227 #endif
36228     }
36229     assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
36230   }
36231
36232
36233   /* Write the first journal header to the journal file and open 
36234   ** the sub-journal if necessary.
36235   */
36236   if( rc==SQLITE_OK ){
36237     /* TODO: Check if all of these are really required. */
36238     pPager->dbOrigSize = pPager->dbSize;
36239     pPager->journalStarted = 0;
36240     pPager->needSync = 0;
36241     pPager->nRec = 0;
36242     pPager->journalOff = 0;
36243     pPager->setMaster = 0;
36244     pPager->journalHdr = 0;
36245     rc = writeJournalHdr(pPager);
36246   }
36247   if( rc==SQLITE_OK && pPager->nSavepoint ){
36248     rc = openSubJournal(pPager);
36249   }
36250
36251   if( rc!=SQLITE_OK ){
36252     sqlite3BitvecDestroy(pPager->pInJournal);
36253     pPager->pInJournal = 0;
36254   }
36255   return rc;
36256 }
36257
36258 /*
36259 ** Begin a write-transaction on the specified pager object. If a 
36260 ** write-transaction has already been opened, this function is a no-op.
36261 **
36262 ** If the exFlag argument is false, then acquire at least a RESERVED
36263 ** lock on the database file. If exFlag is true, then acquire at least
36264 ** an EXCLUSIVE lock. If such a lock is already held, no locking 
36265 ** functions need be called.
36266 **
36267 ** If this is not a temporary or in-memory file and, the journal file is 
36268 ** opened if it has not been already. For a temporary file, the opening 
36269 ** of the journal file is deferred until there is an actual need to 
36270 ** write to the journal. TODO: Why handle temporary files differently?
36271 **
36272 ** If the journal file is opened (or if it is already open), then a
36273 ** journal-header is written to the start of it.
36274 **
36275 ** If the subjInMemory argument is non-zero, then any sub-journal opened
36276 ** within this transaction will be opened as an in-memory file. This
36277 ** has no effect if the sub-journal is already opened (as it may be when
36278 ** running in exclusive mode) or if the transaction does not require a
36279 ** sub-journal. If the subjInMemory argument is zero, then any required
36280 ** sub-journal is implemented in-memory if pPager is an in-memory database, 
36281 ** or using a temporary file otherwise.
36282 */
36283 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
36284   int rc = SQLITE_OK;
36285   assert( pPager->state!=PAGER_UNLOCK );
36286   pPager->subjInMemory = (u8)subjInMemory;
36287   if( pPager->state==PAGER_SHARED ){
36288     assert( pPager->pInJournal==0 );
36289     assert( !MEMDB && !pPager->tempFile );
36290
36291     /* Obtain a RESERVED lock on the database file. If the exFlag parameter
36292     ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
36293     ** busy-handler callback can be used when upgrading to the EXCLUSIVE
36294     ** lock, but not when obtaining the RESERVED lock.
36295     */
36296     rc = sqlite3OsLock(pPager->fd, RESERVED_LOCK);
36297     if( rc==SQLITE_OK ){
36298       pPager->state = PAGER_RESERVED;
36299       if( exFlag ){
36300         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
36301       }
36302     }
36303
36304     /* If the required locks were successfully obtained, open the journal
36305     ** file and write the first journal-header to it.
36306     */
36307     if( rc==SQLITE_OK && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
36308       rc = pager_open_journal(pPager);
36309     }
36310   }else if( isOpen(pPager->jfd) && pPager->journalOff==0 ){
36311     /* This happens when the pager was in exclusive-access mode the last
36312     ** time a (read or write) transaction was successfully concluded
36313     ** by this connection. Instead of deleting the journal file it was 
36314     ** kept open and either was truncated to 0 bytes or its header was
36315     ** overwritten with zeros.
36316     */
36317     assert( pPager->nRec==0 );
36318     assert( pPager->dbOrigSize==0 );
36319     assert( pPager->pInJournal==0 );
36320     rc = pager_open_journal(pPager);
36321   }
36322
36323   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
36324   assert( !isOpen(pPager->jfd) || pPager->journalOff>0 || rc!=SQLITE_OK );
36325   if( rc!=SQLITE_OK ){
36326     assert( !pPager->dbModified );
36327     /* Ignore any IO error that occurs within pager_end_transaction(). The
36328     ** purpose of this call is to reset the internal state of the pager
36329     ** sub-system. It doesn't matter if the journal-file is not properly
36330     ** finalized at this point (since it is not a valid journal file anyway).
36331     */
36332     pager_end_transaction(pPager, 0);
36333   }
36334   return rc;
36335 }
36336
36337 /*
36338 ** Mark a single data page as writeable. The page is written into the 
36339 ** main journal or sub-journal as required. If the page is written into
36340 ** one of the journals, the corresponding bit is set in the 
36341 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
36342 ** of any open savepoints as appropriate.
36343 */
36344 static int pager_write(PgHdr *pPg){
36345   void *pData = pPg->pData;
36346   Pager *pPager = pPg->pPager;
36347   int rc = SQLITE_OK;
36348
36349   /* This routine is not called unless a transaction has already been
36350   ** started.
36351   */
36352   assert( pPager->state>=PAGER_RESERVED );
36353
36354   /* If an error has been previously detected, we should not be
36355   ** calling this routine.  Repeat the error for robustness.
36356   */
36357   if( NEVER(pPager->errCode) )  return pPager->errCode;
36358
36359   /* Higher-level routines never call this function if database is not
36360   ** writable.  But check anyway, just for robustness. */
36361   if( NEVER(pPager->readOnly) ) return SQLITE_PERM;
36362
36363   assert( !pPager->setMaster );
36364
36365   CHECK_PAGE(pPg);
36366
36367   /* Mark the page as dirty.  If the page has already been written
36368   ** to the journal then we can return right away.
36369   */
36370   sqlite3PcacheMakeDirty(pPg);
36371   if( pageInJournal(pPg) && !subjRequiresPage(pPg) ){
36372     pPager->dbModified = 1;
36373   }else{
36374
36375     /* If we get this far, it means that the page needs to be
36376     ** written to the transaction journal or the ckeckpoint journal
36377     ** or both.
36378     **
36379     ** Higher level routines should have already started a transaction,
36380     ** which means they have acquired the necessary locks and opened
36381     ** a rollback journal.  Double-check to makes sure this is the case.
36382     */
36383     rc = sqlite3PagerBegin(pPager, 0, pPager->subjInMemory);
36384     if( NEVER(rc!=SQLITE_OK) ){
36385       return rc;
36386     }
36387     if( !isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
36388       assert( pPager->useJournal );
36389       rc = pager_open_journal(pPager);
36390       if( rc!=SQLITE_OK ) return rc;
36391     }
36392     pPager->dbModified = 1;
36393   
36394     /* The transaction journal now exists and we have a RESERVED or an
36395     ** EXCLUSIVE lock on the main database file.  Write the current page to
36396     ** the transaction journal if it is not there already.
36397     */
36398     if( !pageInJournal(pPg) && isOpen(pPager->jfd) ){
36399       if( pPg->pgno<=pPager->dbOrigSize ){
36400         u32 cksum;
36401         char *pData2;
36402
36403         /* We should never write to the journal file the page that
36404         ** contains the database locks.  The following assert verifies
36405         ** that we do not. */
36406         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
36407         CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
36408         cksum = pager_cksum(pPager, (u8*)pData2);
36409         rc = write32bits(pPager->jfd, pPager->journalOff, pPg->pgno);
36410         if( rc==SQLITE_OK ){
36411           rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize,
36412                               pPager->journalOff + 4);
36413           pPager->journalOff += pPager->pageSize+4;
36414         }
36415         if( rc==SQLITE_OK ){
36416           rc = write32bits(pPager->jfd, pPager->journalOff, cksum);
36417           pPager->journalOff += 4;
36418         }
36419         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
36420                  pPager->journalOff, pPager->pageSize));
36421         PAGER_INCR(sqlite3_pager_writej_count);
36422         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
36423              PAGERID(pPager), pPg->pgno, 
36424              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
36425
36426         /* Even if an IO or diskfull error occurred while journalling the
36427         ** page in the block above, set the need-sync flag for the page.
36428         ** Otherwise, when the transaction is rolled back, the logic in
36429         ** playback_one_page() will think that the page needs to be restored
36430         ** in the database file. And if an IO error occurs while doing so,
36431         ** then corruption may follow.
36432         */
36433         if( !pPager->noSync ){
36434           pPg->flags |= PGHDR_NEED_SYNC;
36435           pPager->needSync = 1;
36436         }
36437
36438         /* An error has occurred writing to the journal file. The 
36439         ** transaction will be rolled back by the layer above.
36440         */
36441         if( rc!=SQLITE_OK ){
36442           return rc;
36443         }
36444
36445         pPager->nRec++;
36446         assert( pPager->pInJournal!=0 );
36447         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
36448         testcase( rc==SQLITE_NOMEM );
36449         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
36450         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
36451         if( rc!=SQLITE_OK ){
36452           assert( rc==SQLITE_NOMEM );
36453           return rc;
36454         }
36455       }else{
36456         if( !pPager->journalStarted && !pPager->noSync ){
36457           pPg->flags |= PGHDR_NEED_SYNC;
36458           pPager->needSync = 1;
36459         }
36460         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
36461                 PAGERID(pPager), pPg->pgno,
36462                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
36463       }
36464     }
36465   
36466     /* If the statement journal is open and the page is not in it,
36467     ** then write the current page to the statement journal.  Note that
36468     ** the statement journal format differs from the standard journal format
36469     ** in that it omits the checksums and the header.
36470     */
36471     if( subjRequiresPage(pPg) ){
36472       rc = subjournalPage(pPg);
36473     }
36474   }
36475
36476   /* Update the database size and return.
36477   */
36478   assert( pPager->state>=PAGER_SHARED );
36479   if( pPager->dbSize<pPg->pgno ){
36480     pPager->dbSize = pPg->pgno;
36481   }
36482   return rc;
36483 }
36484
36485 /*
36486 ** Mark a data page as writeable. This routine must be called before 
36487 ** making changes to a page. The caller must check the return value 
36488 ** of this function and be careful not to change any page data unless 
36489 ** this routine returns SQLITE_OK.
36490 **
36491 ** The difference between this function and pager_write() is that this
36492 ** function also deals with the special case where 2 or more pages
36493 ** fit on a single disk sector. In this case all co-resident pages
36494 ** must have been written to the journal file before returning.
36495 **
36496 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
36497 ** as appropriate. Otherwise, SQLITE_OK.
36498 */
36499 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage *pDbPage){
36500   int rc = SQLITE_OK;
36501
36502   PgHdr *pPg = pDbPage;
36503   Pager *pPager = pPg->pPager;
36504   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
36505
36506   if( nPagePerSector>1 ){
36507     Pgno nPageCount;          /* Total number of pages in database file */
36508     Pgno pg1;                 /* First page of the sector pPg is located on. */
36509     int nPage;                /* Number of pages starting at pg1 to journal */
36510     int ii;                   /* Loop counter */
36511     int needSync = 0;         /* True if any page has PGHDR_NEED_SYNC */
36512
36513     /* Set the doNotSync flag to 1. This is because we cannot allow a journal
36514     ** header to be written between the pages journaled by this function.
36515     */
36516     assert( !MEMDB );
36517     assert( pPager->doNotSync==0 );
36518     pPager->doNotSync = 1;
36519
36520     /* This trick assumes that both the page-size and sector-size are
36521     ** an integer power of 2. It sets variable pg1 to the identifier
36522     ** of the first page of the sector pPg is located on.
36523     */
36524     pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
36525
36526     sqlite3PagerPagecount(pPager, (int *)&nPageCount);
36527     if( pPg->pgno>nPageCount ){
36528       nPage = (pPg->pgno - pg1)+1;
36529     }else if( (pg1+nPagePerSector-1)>nPageCount ){
36530       nPage = nPageCount+1-pg1;
36531     }else{
36532       nPage = nPagePerSector;
36533     }
36534     assert(nPage>0);
36535     assert(pg1<=pPg->pgno);
36536     assert((pg1+nPage)>pPg->pgno);
36537
36538     for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
36539       Pgno pg = pg1+ii;
36540       PgHdr *pPage;
36541       if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
36542         if( pg!=PAGER_MJ_PGNO(pPager) ){
36543           rc = sqlite3PagerGet(pPager, pg, &pPage);
36544           if( rc==SQLITE_OK ){
36545             rc = pager_write(pPage);
36546             if( pPage->flags&PGHDR_NEED_SYNC ){
36547               needSync = 1;
36548               assert(pPager->needSync);
36549             }
36550             sqlite3PagerUnref(pPage);
36551           }
36552         }
36553       }else if( (pPage = pager_lookup(pPager, pg))!=0 ){
36554         if( pPage->flags&PGHDR_NEED_SYNC ){
36555           needSync = 1;
36556         }
36557         sqlite3PagerUnref(pPage);
36558       }
36559     }
36560
36561     /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
36562     ** starting at pg1, then it needs to be set for all of them. Because
36563     ** writing to any of these nPage pages may damage the others, the
36564     ** journal file must contain sync()ed copies of all of them
36565     ** before any of them can be written out to the database file.
36566     */
36567     if( rc==SQLITE_OK && needSync ){
36568       assert( !MEMDB && pPager->noSync==0 );
36569       for(ii=0; ii<nPage; ii++){
36570         PgHdr *pPage = pager_lookup(pPager, pg1+ii);
36571         if( pPage ){
36572           pPage->flags |= PGHDR_NEED_SYNC;
36573           sqlite3PagerUnref(pPage);
36574         }
36575       }
36576       assert(pPager->needSync);
36577     }
36578
36579     assert( pPager->doNotSync==1 );
36580     pPager->doNotSync = 0;
36581   }else{
36582     rc = pager_write(pDbPage);
36583   }
36584   return rc;
36585 }
36586
36587 /*
36588 ** Return TRUE if the page given in the argument was previously passed
36589 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
36590 ** to change the content of the page.
36591 */
36592 #ifndef NDEBUG
36593 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
36594   return pPg->flags&PGHDR_DIRTY;
36595 }
36596 #endif
36597
36598 /*
36599 ** A call to this routine tells the pager that it is not necessary to
36600 ** write the information on page pPg back to the disk, even though
36601 ** that page might be marked as dirty.  This happens, for example, when
36602 ** the page has been added as a leaf of the freelist and so its
36603 ** content no longer matters.
36604 **
36605 ** The overlying software layer calls this routine when all of the data
36606 ** on the given page is unused. The pager marks the page as clean so
36607 ** that it does not get written to disk.
36608 **
36609 ** Tests show that this optimization can quadruple the speed of large 
36610 ** DELETE operations.
36611 */
36612 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
36613   Pager *pPager = pPg->pPager;
36614   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
36615     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
36616     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
36617     pPg->flags |= PGHDR_DONT_WRITE;
36618 #ifdef SQLITE_CHECK_PAGES
36619     pPg->pageHash = pager_pagehash(pPg);
36620 #endif
36621   }
36622 }
36623
36624 /*
36625 ** This routine is called to increment the value of the database file 
36626 ** change-counter, stored as a 4-byte big-endian integer starting at 
36627 ** byte offset 24 of the pager file.
36628 **
36629 ** If the isDirectMode flag is zero, then this is done by calling 
36630 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
36631 ** page data. In this case the file will be updated when the current
36632 ** transaction is committed.
36633 **
36634 ** The isDirectMode flag may only be non-zero if the library was compiled
36635 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
36636 ** if isDirect is non-zero, then the database file is updated directly
36637 ** by writing an updated version of page 1 using a call to the 
36638 ** sqlite3OsWrite() function.
36639 */
36640 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
36641   int rc = SQLITE_OK;
36642
36643   /* Declare and initialize constant integer 'isDirect'. If the
36644   ** atomic-write optimization is enabled in this build, then isDirect
36645   ** is initialized to the value passed as the isDirectMode parameter
36646   ** to this function. Otherwise, it is always set to zero.
36647   **
36648   ** The idea is that if the atomic-write optimization is not
36649   ** enabled at compile time, the compiler can omit the tests of
36650   ** 'isDirect' below, as well as the block enclosed in the
36651   ** "if( isDirect )" condition.
36652   */
36653 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
36654 # define DIRECT_MODE 0
36655   assert( isDirectMode==0 );
36656   UNUSED_PARAMETER(isDirectMode);
36657 #else
36658 # define DIRECT_MODE isDirectMode
36659 #endif
36660
36661   assert( pPager->state>=PAGER_RESERVED );
36662   if( !pPager->changeCountDone && pPager->dbSize>0 ){
36663     PgHdr *pPgHdr;                /* Reference to page 1 */
36664     u32 change_counter;           /* Initial value of change-counter field */
36665
36666     assert( !pPager->tempFile && isOpen(pPager->fd) );
36667
36668     /* Open page 1 of the file for writing. */
36669     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
36670     assert( pPgHdr==0 || rc==SQLITE_OK );
36671
36672     /* If page one was fetched successfully, and this function is not
36673     ** operating in direct-mode, make page 1 writable.  When not in 
36674     ** direct mode, page 1 is always held in cache and hence the PagerGet()
36675     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
36676     */
36677     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
36678       rc = sqlite3PagerWrite(pPgHdr);
36679     }
36680
36681     if( rc==SQLITE_OK ){
36682       /* Increment the value just read and write it back to byte 24. */
36683       change_counter = sqlite3Get4byte((u8*)pPager->dbFileVers);
36684       change_counter++;
36685       put32bits(((char*)pPgHdr->pData)+24, change_counter);
36686
36687       /* If running in direct mode, write the contents of page 1 to the file. */
36688       if( DIRECT_MODE ){
36689         const void *zBuf = pPgHdr->pData;
36690         assert( pPager->dbFileSize>0 );
36691         rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
36692         if( rc==SQLITE_OK ){
36693           pPager->changeCountDone = 1;
36694         }
36695       }else{
36696         pPager->changeCountDone = 1;
36697       }
36698     }
36699
36700     /* Release the page reference. */
36701     sqlite3PagerUnref(pPgHdr);
36702   }
36703   return rc;
36704 }
36705
36706 /*
36707 ** Sync the pager file to disk. This is a no-op for in-memory files
36708 ** or pages with the Pager.noSync flag set.
36709 **
36710 ** If successful, or called on a pager for which it is a no-op, this
36711 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
36712 */
36713 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager){
36714   int rc;                              /* Return code */
36715   assert( !MEMDB );
36716   if( pPager->noSync ){
36717     rc = SQLITE_OK;
36718   }else{
36719     rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
36720   }
36721   return rc;
36722 }
36723
36724 /*
36725 ** Sync the database file for the pager pPager. zMaster points to the name
36726 ** of a master journal file that should be written into the individual
36727 ** journal file. zMaster may be NULL, which is interpreted as no master
36728 ** journal (a single database transaction).
36729 **
36730 ** This routine ensures that:
36731 **
36732 **   * The database file change-counter is updated,
36733 **   * the journal is synced (unless the atomic-write optimization is used),
36734 **   * all dirty pages are written to the database file, 
36735 **   * the database file is truncated (if required), and
36736 **   * the database file synced. 
36737 **
36738 ** The only thing that remains to commit the transaction is to finalize 
36739 ** (delete, truncate or zero the first part of) the journal file (or 
36740 ** delete the master journal file if specified).
36741 **
36742 ** Note that if zMaster==NULL, this does not overwrite a previous value
36743 ** passed to an sqlite3PagerCommitPhaseOne() call.
36744 **
36745 ** If the final parameter - noSync - is true, then the database file itself
36746 ** is not synced. The caller must call sqlite3PagerSync() directly to
36747 ** sync the database file before calling CommitPhaseTwo() to delete the
36748 ** journal file in this case.
36749 */
36750 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
36751   Pager *pPager,                  /* Pager object */
36752   const char *zMaster,            /* If not NULL, the master journal name */
36753   int noSync                      /* True to omit the xSync on the db file */
36754 ){
36755   int rc = SQLITE_OK;             /* Return code */
36756
36757   /* The dbOrigSize is never set if journal_mode=OFF */
36758   assert( pPager->journalMode!=PAGER_JOURNALMODE_OFF || pPager->dbOrigSize==0 );
36759
36760   /* If a prior error occurred, this routine should not be called.  ROLLBACK
36761   ** is the appropriate response to an error, not COMMIT.  Guard against
36762   ** coding errors by repeating the prior error. */
36763   if( NEVER(pPager->errCode) ) return pPager->errCode;
36764
36765   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
36766       pPager->zFilename, zMaster, pPager->dbSize));
36767
36768   if( MEMDB && pPager->dbModified ){
36769     /* If this is an in-memory db, or no pages have been written to, or this
36770     ** function has already been called, it is mostly a no-op.  However, any
36771     ** backup in progress needs to be restarted.
36772     */
36773     sqlite3BackupRestart(pPager->pBackup);
36774   }else if( pPager->state!=PAGER_SYNCED && pPager->dbModified ){
36775
36776     /* The following block updates the change-counter. Exactly how it
36777     ** does this depends on whether or not the atomic-update optimization
36778     ** was enabled at compile time, and if this transaction meets the 
36779     ** runtime criteria to use the operation: 
36780     **
36781     **    * The file-system supports the atomic-write property for
36782     **      blocks of size page-size, and 
36783     **    * This commit is not part of a multi-file transaction, and
36784     **    * Exactly one page has been modified and store in the journal file.
36785     **
36786     ** If the optimization was not enabled at compile time, then the
36787     ** pager_incr_changecounter() function is called to update the change
36788     ** counter in 'indirect-mode'. If the optimization is compiled in but
36789     ** is not applicable to this transaction, call sqlite3JournalCreate()
36790     ** to make sure the journal file has actually been created, then call
36791     ** pager_incr_changecounter() to update the change-counter in indirect
36792     ** mode. 
36793     **
36794     ** Otherwise, if the optimization is both enabled and applicable,
36795     ** then call pager_incr_changecounter() to update the change-counter
36796     ** in 'direct' mode. In this case the journal file will never be
36797     ** created for this transaction.
36798     */
36799 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
36800     PgHdr *pPg;
36801     assert( isOpen(pPager->jfd) || pPager->journalMode==PAGER_JOURNALMODE_OFF );
36802     if( !zMaster && isOpen(pPager->jfd) 
36803      && pPager->journalOff==jrnlBufferSize(pPager) 
36804      && pPager->dbSize>=pPager->dbFileSize
36805      && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
36806     ){
36807       /* Update the db file change counter via the direct-write method. The 
36808       ** following call will modify the in-memory representation of page 1 
36809       ** to include the updated change counter and then write page 1 
36810       ** directly to the database file. Because of the atomic-write 
36811       ** property of the host file-system, this is safe.
36812       */
36813       rc = pager_incr_changecounter(pPager, 1);
36814     }else{
36815       rc = sqlite3JournalCreate(pPager->jfd);
36816       if( rc==SQLITE_OK ){
36817         rc = pager_incr_changecounter(pPager, 0);
36818       }
36819     }
36820 #else
36821     rc = pager_incr_changecounter(pPager, 0);
36822 #endif
36823     if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
36824
36825     /* If this transaction has made the database smaller, then all pages
36826     ** being discarded by the truncation must be written to the journal
36827     ** file. This can only happen in auto-vacuum mode.
36828     **
36829     ** Before reading the pages with page numbers larger than the 
36830     ** current value of Pager.dbSize, set dbSize back to the value
36831     ** that it took at the start of the transaction. Otherwise, the
36832     ** calls to sqlite3PagerGet() return zeroed pages instead of 
36833     ** reading data from the database file.
36834     **
36835     ** When journal_mode==OFF the dbOrigSize is always zero, so this
36836     ** block never runs if journal_mode=OFF.
36837     */
36838 #ifndef SQLITE_OMIT_AUTOVACUUM
36839     if( pPager->dbSize<pPager->dbOrigSize 
36840      && ALWAYS(pPager->journalMode!=PAGER_JOURNALMODE_OFF)
36841     ){
36842       Pgno i;                                   /* Iterator variable */
36843       const Pgno iSkip = PAGER_MJ_PGNO(pPager); /* Pending lock page */
36844       const Pgno dbSize = pPager->dbSize;       /* Database image size */ 
36845       pPager->dbSize = pPager->dbOrigSize;
36846       for( i=dbSize+1; i<=pPager->dbOrigSize; i++ ){
36847         if( !sqlite3BitvecTest(pPager->pInJournal, i) && i!=iSkip ){
36848           PgHdr *pPage;             /* Page to journal */
36849           rc = sqlite3PagerGet(pPager, i, &pPage);
36850           if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
36851           rc = sqlite3PagerWrite(pPage);
36852           sqlite3PagerUnref(pPage);
36853           if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
36854         }
36855       } 
36856       pPager->dbSize = dbSize;
36857     }
36858 #endif
36859
36860     /* Write the master journal name into the journal file. If a master 
36861     ** journal file name has already been written to the journal file, 
36862     ** or if zMaster is NULL (no master journal), then this call is a no-op.
36863     */
36864     rc = writeMasterJournal(pPager, zMaster);
36865     if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
36866
36867     /* Sync the journal file. If the atomic-update optimization is being
36868     ** used, this call will not create the journal file or perform any
36869     ** real IO.
36870     */
36871     rc = syncJournal(pPager);
36872     if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
36873
36874     /* Write all dirty pages to the database file. */
36875     rc = pager_write_pagelist(sqlite3PcacheDirtyList(pPager->pPCache));
36876     if( rc!=SQLITE_OK ){
36877       assert( rc!=SQLITE_IOERR_BLOCKED );
36878       goto commit_phase_one_exit;
36879     }
36880     sqlite3PcacheCleanAll(pPager->pPCache);
36881
36882     /* If the file on disk is not the same size as the database image,
36883     ** then use pager_truncate to grow or shrink the file here.
36884     */
36885     if( pPager->dbSize!=pPager->dbFileSize ){
36886       Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
36887       assert( pPager->state>=PAGER_EXCLUSIVE );
36888       rc = pager_truncate(pPager, nNew);
36889       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
36890     }
36891
36892     /* Finally, sync the database file. */
36893     if( !pPager->noSync && !noSync ){
36894       rc = sqlite3OsSync(pPager->fd, pPager->sync_flags);
36895     }
36896     IOTRACE(("DBSYNC %p\n", pPager))
36897
36898     pPager->state = PAGER_SYNCED;
36899   }
36900
36901 commit_phase_one_exit:
36902   return rc;
36903 }
36904
36905
36906 /*
36907 ** When this function is called, the database file has been completely
36908 ** updated to reflect the changes made by the current transaction and
36909 ** synced to disk. The journal file still exists in the file-system 
36910 ** though, and if a failure occurs at this point it will eventually
36911 ** be used as a hot-journal and the current transaction rolled back.
36912 **
36913 ** This function finalizes the journal file, either by deleting, 
36914 ** truncating or partially zeroing it, so that it cannot be used 
36915 ** for hot-journal rollback. Once this is done the transaction is
36916 ** irrevocably committed.
36917 **
36918 ** If an error occurs, an IO error code is returned and the pager
36919 ** moves into the error state. Otherwise, SQLITE_OK is returned.
36920 */
36921 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
36922   int rc = SQLITE_OK;                  /* Return code */
36923
36924   /* This routine should not be called if a prior error has occurred.
36925   ** But if (due to a coding error elsewhere in the system) it does get
36926   ** called, just return the same error code without doing anything. */
36927   if( NEVER(pPager->errCode) ) return pPager->errCode;
36928
36929   /* This function should not be called if the pager is not in at least
36930   ** PAGER_RESERVED state. And indeed SQLite never does this. But it is
36931   ** nice to have this defensive test here anyway.
36932   */
36933   if( NEVER(pPager->state<PAGER_RESERVED) ) return SQLITE_ERROR;
36934
36935   /* An optimization. If the database was not actually modified during
36936   ** this transaction, the pager is running in exclusive-mode and is
36937   ** using persistent journals, then this function is a no-op.
36938   **
36939   ** The start of the journal file currently contains a single journal 
36940   ** header with the nRec field set to 0. If such a journal is used as
36941   ** a hot-journal during hot-journal rollback, 0 changes will be made
36942   ** to the database file. So there is no need to zero the journal 
36943   ** header. Since the pager is in exclusive mode, there is no need
36944   ** to drop any locks either.
36945   */
36946   if( pPager->dbModified==0 && pPager->exclusiveMode 
36947    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
36948   ){
36949     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
36950     return SQLITE_OK;
36951   }
36952
36953   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
36954   assert( pPager->state==PAGER_SYNCED || MEMDB || !pPager->dbModified );
36955   rc = pager_end_transaction(pPager, pPager->setMaster);
36956   return pager_error(pPager, rc);
36957 }
36958
36959 /*
36960 ** Rollback all changes. The database falls back to PAGER_SHARED mode.
36961 **
36962 ** This function performs two tasks:
36963 **
36964 **   1) It rolls back the journal file, restoring all database file and 
36965 **      in-memory cache pages to the state they were in when the transaction
36966 **      was opened, and
36967 **   2) It finalizes the journal file, so that it is not used for hot
36968 **      rollback at any point in the future.
36969 **
36970 ** subject to the following qualifications:
36971 **
36972 ** * If the journal file is not yet open when this function is called,
36973 **   then only (2) is performed. In this case there is no journal file
36974 **   to roll back.
36975 **
36976 ** * If in an error state other than SQLITE_FULL, then task (1) is 
36977 **   performed. If successful, task (2). Regardless of the outcome
36978 **   of either, the error state error code is returned to the caller
36979 **   (i.e. either SQLITE_IOERR or SQLITE_CORRUPT).
36980 **
36981 ** * If the pager is in PAGER_RESERVED state, then attempt (1). Whether
36982 **   or not (1) is succussful, also attempt (2). If successful, return
36983 **   SQLITE_OK. Otherwise, enter the error state and return the first 
36984 **   error code encountered. 
36985 **
36986 **   In this case there is no chance that the database was written to. 
36987 **   So is safe to finalize the journal file even if the playback 
36988 **   (operation 1) failed. However the pager must enter the error state
36989 **   as the contents of the in-memory cache are now suspect.
36990 **
36991 ** * Finally, if in PAGER_EXCLUSIVE state, then attempt (1). Only
36992 **   attempt (2) if (1) is successful. Return SQLITE_OK if successful,
36993 **   otherwise enter the error state and return the error code from the 
36994 **   failing operation.
36995 **
36996 **   In this case the database file may have been written to. So if the
36997 **   playback operation did not succeed it would not be safe to finalize
36998 **   the journal file. It needs to be left in the file-system so that
36999 **   some other process can use it to restore the database state (by
37000 **   hot-journal rollback).
37001 */
37002 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
37003   int rc = SQLITE_OK;                  /* Return code */
37004   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
37005   if( !pPager->dbModified || !isOpen(pPager->jfd) ){
37006     rc = pager_end_transaction(pPager, pPager->setMaster);
37007   }else if( pPager->errCode && pPager->errCode!=SQLITE_FULL ){
37008     if( pPager->state>=PAGER_EXCLUSIVE ){
37009       pager_playback(pPager, 0);
37010     }
37011     rc = pPager->errCode;
37012   }else{
37013     if( pPager->state==PAGER_RESERVED ){
37014       int rc2;
37015       rc = pager_playback(pPager, 0);
37016       rc2 = pager_end_transaction(pPager, pPager->setMaster);
37017       if( rc==SQLITE_OK ){
37018         rc = rc2;
37019       }
37020     }else{
37021       rc = pager_playback(pPager, 0);
37022     }
37023
37024     if( !MEMDB ){
37025       pPager->dbSizeValid = 0;
37026     }
37027
37028     /* If an error occurs during a ROLLBACK, we can no longer trust the pager
37029     ** cache. So call pager_error() on the way out to make any error 
37030     ** persistent.
37031     */
37032     rc = pager_error(pPager, rc);
37033   }
37034   return rc;
37035 }
37036
37037 /*
37038 ** Return TRUE if the database file is opened read-only.  Return FALSE
37039 ** if the database is (in theory) writable.
37040 */
37041 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
37042   return pPager->readOnly;
37043 }
37044
37045 /*
37046 ** Return the number of references to the pager.
37047 */
37048 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
37049   return sqlite3PcacheRefCount(pPager->pPCache);
37050 }
37051
37052 /*
37053 ** Return the number of references to the specified page.
37054 */
37055 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
37056   return sqlite3PcachePageRefcount(pPage);
37057 }
37058
37059 #ifdef SQLITE_TEST
37060 /*
37061 ** This routine is used for testing and analysis only.
37062 */
37063 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
37064   static int a[11];
37065   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
37066   a[1] = sqlite3PcachePagecount(pPager->pPCache);
37067   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
37068   a[3] = pPager->dbSizeValid ? (int) pPager->dbSize : -1;
37069   a[4] = pPager->state;
37070   a[5] = pPager->errCode;
37071   a[6] = pPager->nHit;
37072   a[7] = pPager->nMiss;
37073   a[8] = 0;  /* Used to be pPager->nOvfl */
37074   a[9] = pPager->nRead;
37075   a[10] = pPager->nWrite;
37076   return a;
37077 }
37078 #endif
37079
37080 /*
37081 ** Return true if this is an in-memory pager.
37082 */
37083 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
37084   return MEMDB;
37085 }
37086
37087 /*
37088 ** Check that there are at least nSavepoint savepoints open. If there are
37089 ** currently less than nSavepoints open, then open one or more savepoints
37090 ** to make up the difference. If the number of savepoints is already
37091 ** equal to nSavepoint, then this function is a no-op.
37092 **
37093 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
37094 ** occurs while opening the sub-journal file, then an IO error code is
37095 ** returned. Otherwise, SQLITE_OK.
37096 */
37097 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
37098   int rc = SQLITE_OK;                       /* Return code */
37099   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
37100
37101   if( nSavepoint>nCurrent && pPager->useJournal ){
37102     int ii;                                 /* Iterator variable */
37103     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
37104
37105     /* Either there is no active journal or the sub-journal is open or 
37106     ** the journal is always stored in memory */
37107     assert( pPager->nSavepoint==0 || isOpen(pPager->sjfd) ||
37108             pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
37109
37110     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
37111     ** if the allocation fails. Otherwise, zero the new portion in case a 
37112     ** malloc failure occurs while populating it in the for(...) loop below.
37113     */
37114     aNew = (PagerSavepoint *)sqlite3Realloc(
37115         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
37116     );
37117     if( !aNew ){
37118       return SQLITE_NOMEM;
37119     }
37120     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
37121     pPager->aSavepoint = aNew;
37122     pPager->nSavepoint = nSavepoint;
37123
37124     /* Populate the PagerSavepoint structures just allocated. */
37125     for(ii=nCurrent; ii<nSavepoint; ii++){
37126       assert( pPager->dbSizeValid );
37127       aNew[ii].nOrig = pPager->dbSize;
37128       if( isOpen(pPager->jfd) && ALWAYS(pPager->journalOff>0) ){
37129         aNew[ii].iOffset = pPager->journalOff;
37130       }else{
37131         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
37132       }
37133       aNew[ii].iSubRec = pPager->nSubRec;
37134       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
37135       if( !aNew[ii].pInSavepoint ){
37136         return SQLITE_NOMEM;
37137       }
37138     }
37139
37140     /* Open the sub-journal, if it is not already opened. */
37141     rc = openSubJournal(pPager);
37142     assertTruncateConstraint(pPager);
37143   }
37144
37145   return rc;
37146 }
37147
37148 /*
37149 ** This function is called to rollback or release (commit) a savepoint.
37150 ** The savepoint to release or rollback need not be the most recently 
37151 ** created savepoint.
37152 **
37153 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
37154 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
37155 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
37156 ** that have occurred since the specified savepoint was created.
37157 **
37158 ** The savepoint to rollback or release is identified by parameter 
37159 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
37160 ** (the first created). A value of (Pager.nSavepoint-1) means operate
37161 ** on the most recently created savepoint. If iSavepoint is greater than
37162 ** (Pager.nSavepoint-1), then this function is a no-op.
37163 **
37164 ** If a negative value is passed to this function, then the current
37165 ** transaction is rolled back. This is different to calling 
37166 ** sqlite3PagerRollback() because this function does not terminate
37167 ** the transaction or unlock the database, it just restores the 
37168 ** contents of the database to its original state. 
37169 **
37170 ** In any case, all savepoints with an index greater than iSavepoint 
37171 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
37172 ** then savepoint iSavepoint is also destroyed.
37173 **
37174 ** This function may return SQLITE_NOMEM if a memory allocation fails,
37175 ** or an IO error code if an IO error occurs while rolling back a 
37176 ** savepoint. If no errors occur, SQLITE_OK is returned.
37177 */ 
37178 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
37179   int rc = SQLITE_OK;
37180
37181   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
37182   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
37183
37184   if( iSavepoint<pPager->nSavepoint ){
37185     int ii;            /* Iterator variable */
37186     int nNew;          /* Number of remaining savepoints after this op. */
37187
37188     /* Figure out how many savepoints will still be active after this
37189     ** operation. Store this value in nNew. Then free resources associated 
37190     ** with any savepoints that are destroyed by this operation.
37191     */
37192     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
37193     for(ii=nNew; ii<pPager->nSavepoint; ii++){
37194       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
37195     }
37196     pPager->nSavepoint = nNew;
37197
37198     /* If this is a release of the outermost savepoint, truncate 
37199     ** the sub-journal to zero bytes in size. */
37200     if( op==SAVEPOINT_RELEASE ){
37201       if( nNew==0 && isOpen(pPager->sjfd) ){
37202         /* Only truncate if it is an in-memory sub-journal. */
37203         if( sqlite3IsMemJournal(pPager->sjfd) ){
37204           rc = sqlite3OsTruncate(pPager->sjfd, 0);
37205           assert( rc==SQLITE_OK );
37206         }
37207         pPager->nSubRec = 0;
37208       }
37209     }
37210     /* Else this is a rollback operation, playback the specified savepoint.
37211     ** If this is a temp-file, it is possible that the journal file has
37212     ** not yet been opened. In this case there have been no changes to
37213     ** the database file, so the playback operation can be skipped.
37214     */
37215     else if( isOpen(pPager->jfd) ){
37216       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
37217       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
37218       assert(rc!=SQLITE_DONE);
37219     }
37220   
37221   }
37222   return rc;
37223 }
37224
37225 /*
37226 ** Return the full pathname of the database file.
37227 */
37228 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager){
37229   return pPager->zFilename;
37230 }
37231
37232 /*
37233 ** Return the VFS structure for the pager.
37234 */
37235 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
37236   return pPager->pVfs;
37237 }
37238
37239 /*
37240 ** Return the file handle for the database file associated
37241 ** with the pager.  This might return NULL if the file has
37242 ** not yet been opened.
37243 */
37244 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
37245   return pPager->fd;
37246 }
37247
37248 /*
37249 ** Return the full pathname of the journal file.
37250 */
37251 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
37252   return pPager->zJournal;
37253 }
37254
37255 /*
37256 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
37257 ** if fsync()s are executed normally.
37258 */
37259 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
37260   return pPager->noSync;
37261 }
37262
37263 #ifdef SQLITE_HAS_CODEC
37264 /*
37265 ** Set or retrieve the codec for this pager
37266 */
37267 static void sqlite3PagerSetCodec(
37268   Pager *pPager,
37269   void *(*xCodec)(void*,void*,Pgno,int),
37270   void (*xCodecSizeChng)(void*,int,int),
37271   void (*xCodecFree)(void*),
37272   void *pCodec
37273 ){
37274   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
37275   pPager->xCodec = pPager->memDb ? 0 : xCodec;
37276   pPager->xCodecSizeChng = xCodecSizeChng;
37277   pPager->xCodecFree = xCodecFree;
37278   pPager->pCodec = pCodec;
37279   pagerReportSize(pPager);
37280 }
37281 static void *sqlite3PagerGetCodec(Pager *pPager){
37282   return pPager->pCodec;
37283 }
37284 #endif
37285
37286 #ifndef SQLITE_OMIT_AUTOVACUUM
37287 /*
37288 ** Move the page pPg to location pgno in the file.
37289 **
37290 ** There must be no references to the page previously located at
37291 ** pgno (which we call pPgOld) though that page is allowed to be
37292 ** in cache.  If the page previously located at pgno is not already
37293 ** in the rollback journal, it is not put there by by this routine.
37294 **
37295 ** References to the page pPg remain valid. Updating any
37296 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
37297 ** allocated along with the page) is the responsibility of the caller.
37298 **
37299 ** A transaction must be active when this routine is called. It used to be
37300 ** required that a statement transaction was not active, but this restriction
37301 ** has been removed (CREATE INDEX needs to move a page when a statement
37302 ** transaction is active).
37303 **
37304 ** If the fourth argument, isCommit, is non-zero, then this page is being
37305 ** moved as part of a database reorganization just before the transaction 
37306 ** is being committed. In this case, it is guaranteed that the database page 
37307 ** pPg refers to will not be written to again within this transaction.
37308 **
37309 ** This function may return SQLITE_NOMEM or an IO error code if an error
37310 ** occurs. Otherwise, it returns SQLITE_OK.
37311 */
37312 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
37313   PgHdr *pPgOld;               /* The page being overwritten. */
37314   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
37315   int rc;                      /* Return code */
37316   Pgno origPgno;               /* The original page number */
37317
37318   assert( pPg->nRef>0 );
37319
37320   /* In order to be able to rollback, an in-memory database must journal
37321   ** the page we are moving from.
37322   */
37323   if( MEMDB ){
37324     rc = sqlite3PagerWrite(pPg);
37325     if( rc ) return rc;
37326   }
37327
37328   /* If the page being moved is dirty and has not been saved by the latest
37329   ** savepoint, then save the current contents of the page into the 
37330   ** sub-journal now. This is required to handle the following scenario:
37331   **
37332   **   BEGIN;
37333   **     <journal page X, then modify it in memory>
37334   **     SAVEPOINT one;
37335   **       <Move page X to location Y>
37336   **     ROLLBACK TO one;
37337   **
37338   ** If page X were not written to the sub-journal here, it would not
37339   ** be possible to restore its contents when the "ROLLBACK TO one"
37340   ** statement were is processed.
37341   **
37342   ** subjournalPage() may need to allocate space to store pPg->pgno into
37343   ** one or more savepoint bitvecs. This is the reason this function
37344   ** may return SQLITE_NOMEM.
37345   */
37346   if( pPg->flags&PGHDR_DIRTY
37347    && subjRequiresPage(pPg)
37348    && SQLITE_OK!=(rc = subjournalPage(pPg))
37349   ){
37350     return rc;
37351   }
37352
37353   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
37354       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
37355   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
37356
37357   /* If the journal needs to be sync()ed before page pPg->pgno can
37358   ** be written to, store pPg->pgno in local variable needSyncPgno.
37359   **
37360   ** If the isCommit flag is set, there is no need to remember that
37361   ** the journal needs to be sync()ed before database page pPg->pgno 
37362   ** can be written to. The caller has already promised not to write to it.
37363   */
37364   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
37365     needSyncPgno = pPg->pgno;
37366     assert( pageInJournal(pPg) || pPg->pgno>pPager->dbOrigSize );
37367     assert( pPg->flags&PGHDR_DIRTY );
37368     assert( pPager->needSync );
37369   }
37370
37371   /* If the cache contains a page with page-number pgno, remove it
37372   ** from its hash chain. Also, if the PgHdr.needSync was set for 
37373   ** page pgno before the 'move' operation, it needs to be retained 
37374   ** for the page moved there.
37375   */
37376   pPg->flags &= ~PGHDR_NEED_SYNC;
37377   pPgOld = pager_lookup(pPager, pgno);
37378   assert( !pPgOld || pPgOld->nRef==1 );
37379   if( pPgOld ){
37380     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
37381     if( MEMDB ){
37382       /* Do not discard pages from an in-memory database since we might
37383       ** need to rollback later.  Just move the page out of the way. */
37384       assert( pPager->dbSizeValid );
37385       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
37386     }else{
37387       sqlite3PcacheDrop(pPgOld);
37388     }
37389   }
37390
37391   origPgno = pPg->pgno;
37392   sqlite3PcacheMove(pPg, pgno);
37393   sqlite3PcacheMakeDirty(pPg);
37394   pPager->dbModified = 1;
37395
37396   if( needSyncPgno ){
37397     /* If needSyncPgno is non-zero, then the journal file needs to be 
37398     ** sync()ed before any data is written to database file page needSyncPgno.
37399     ** Currently, no such page exists in the page-cache and the 
37400     ** "is journaled" bitvec flag has been set. This needs to be remedied by
37401     ** loading the page into the pager-cache and setting the PgHdr.needSync 
37402     ** flag.
37403     **
37404     ** If the attempt to load the page into the page-cache fails, (due
37405     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
37406     ** array. Otherwise, if the page is loaded and written again in
37407     ** this transaction, it may be written to the database file before
37408     ** it is synced into the journal file. This way, it may end up in
37409     ** the journal file twice, but that is not a problem.
37410     **
37411     ** The sqlite3PagerGet() call may cause the journal to sync. So make
37412     ** sure the Pager.needSync flag is set too.
37413     */
37414     PgHdr *pPgHdr;
37415     assert( pPager->needSync );
37416     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
37417     if( rc!=SQLITE_OK ){
37418       if( needSyncPgno<=pPager->dbOrigSize ){
37419         assert( pPager->pTmpSpace!=0 );
37420         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
37421       }
37422       return rc;
37423     }
37424     pPager->needSync = 1;
37425     assert( pPager->noSync==0 && !MEMDB );
37426     pPgHdr->flags |= PGHDR_NEED_SYNC;
37427     sqlite3PcacheMakeDirty(pPgHdr);
37428     sqlite3PagerUnref(pPgHdr);
37429   }
37430
37431   /*
37432   ** For an in-memory database, make sure the original page continues
37433   ** to exist, in case the transaction needs to roll back.  Use pPgOld
37434   ** as the original page since it has already been allocated.
37435   */
37436   if( MEMDB ){
37437     sqlite3PcacheMove(pPgOld, origPgno);
37438     sqlite3PagerUnref(pPgOld);
37439   }
37440
37441   return SQLITE_OK;
37442 }
37443 #endif
37444
37445 /*
37446 ** Return a pointer to the data for the specified page.
37447 */
37448 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
37449   assert( pPg->nRef>0 || pPg->pPager->memDb );
37450   return pPg->pData;
37451 }
37452
37453 /*
37454 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
37455 ** allocated along with the specified page.
37456 */
37457 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
37458   return pPg->pExtra;
37459 }
37460
37461 /*
37462 ** Get/set the locking-mode for this pager. Parameter eMode must be one
37463 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
37464 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
37465 ** the locking-mode is set to the value specified.
37466 **
37467 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
37468 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
37469 ** locking-mode.
37470 */
37471 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
37472   assert( eMode==PAGER_LOCKINGMODE_QUERY
37473             || eMode==PAGER_LOCKINGMODE_NORMAL
37474             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
37475   assert( PAGER_LOCKINGMODE_QUERY<0 );
37476   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
37477   if( eMode>=0 && !pPager->tempFile ){
37478     pPager->exclusiveMode = (u8)eMode;
37479   }
37480   return (int)pPager->exclusiveMode;
37481 }
37482
37483 /*
37484 ** Get/set the journal-mode for this pager. Parameter eMode must be one of:
37485 **
37486 **    PAGER_JOURNALMODE_QUERY
37487 **    PAGER_JOURNALMODE_DELETE
37488 **    PAGER_JOURNALMODE_TRUNCATE
37489 **    PAGER_JOURNALMODE_PERSIST
37490 **    PAGER_JOURNALMODE_OFF
37491 **    PAGER_JOURNALMODE_MEMORY
37492 **
37493 ** If the parameter is not _QUERY, then the journal_mode is set to the
37494 ** value specified if the change is allowed.  The change is disallowed
37495 ** for the following reasons:
37496 **
37497 **   *  An in-memory database can only have its journal_mode set to _OFF
37498 **      or _MEMORY.
37499 **
37500 **   *  The journal mode may not be changed while a transaction is active.
37501 **
37502 ** The returned indicate the current (possibly updated) journal-mode.
37503 */
37504 SQLITE_PRIVATE int sqlite3PagerJournalMode(Pager *pPager, int eMode){
37505   assert( eMode==PAGER_JOURNALMODE_QUERY
37506             || eMode==PAGER_JOURNALMODE_DELETE
37507             || eMode==PAGER_JOURNALMODE_TRUNCATE
37508             || eMode==PAGER_JOURNALMODE_PERSIST
37509             || eMode==PAGER_JOURNALMODE_OFF 
37510             || eMode==PAGER_JOURNALMODE_MEMORY );
37511   assert( PAGER_JOURNALMODE_QUERY<0 );
37512   if( eMode>=0
37513    && (!MEMDB || eMode==PAGER_JOURNALMODE_MEMORY 
37514               || eMode==PAGER_JOURNALMODE_OFF)
37515    && !pPager->dbModified
37516    && (!isOpen(pPager->jfd) || 0==pPager->journalOff)
37517   ){
37518     if( isOpen(pPager->jfd) ){
37519       sqlite3OsClose(pPager->jfd);
37520     }
37521     pPager->journalMode = (u8)eMode;
37522   }
37523   return (int)pPager->journalMode;
37524 }
37525
37526 /*
37527 ** Get/set the size-limit used for persistent journal files.
37528 **
37529 ** Setting the size limit to -1 means no limit is enforced.
37530 ** An attempt to set a limit smaller than -1 is a no-op.
37531 */
37532 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
37533   if( iLimit>=-1 ){
37534     pPager->journalSizeLimit = iLimit;
37535   }
37536   return pPager->journalSizeLimit;
37537 }
37538
37539 /*
37540 ** Return a pointer to the pPager->pBackup variable. The backup module
37541 ** in backup.c maintains the content of this variable. This module
37542 ** uses it opaquely as an argument to sqlite3BackupRestart() and
37543 ** sqlite3BackupUpdate() only.
37544 */
37545 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
37546   return &pPager->pBackup;
37547 }
37548
37549 #endif /* SQLITE_OMIT_DISKIO */
37550
37551 /************** End of pager.c ***********************************************/
37552 /************** Begin file btmutex.c *****************************************/
37553 /*
37554 ** 2007 August 27
37555 **
37556 ** The author disclaims copyright to this source code.  In place of
37557 ** a legal notice, here is a blessing:
37558 **
37559 **    May you do good and not evil.
37560 **    May you find forgiveness for yourself and forgive others.
37561 **    May you share freely, never taking more than you give.
37562 **
37563 *************************************************************************
37564 **
37565 ** This file contains code used to implement mutexes on Btree objects.
37566 ** This code really belongs in btree.c.  But btree.c is getting too
37567 ** big and we want to break it down some.  This packaged seemed like
37568 ** a good breakout.
37569 */
37570 /************** Include btreeInt.h in the middle of btmutex.c ****************/
37571 /************** Begin file btreeInt.h ****************************************/
37572 /*
37573 ** 2004 April 6
37574 **
37575 ** The author disclaims copyright to this source code.  In place of
37576 ** a legal notice, here is a blessing:
37577 **
37578 **    May you do good and not evil.
37579 **    May you find forgiveness for yourself and forgive others.
37580 **    May you share freely, never taking more than you give.
37581 **
37582 *************************************************************************
37583 ** This file implements a external (disk-based) database using BTrees.
37584 ** For a detailed discussion of BTrees, refer to
37585 **
37586 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
37587 **     "Sorting And Searching", pages 473-480. Addison-Wesley
37588 **     Publishing Company, Reading, Massachusetts.
37589 **
37590 ** The basic idea is that each page of the file contains N database
37591 ** entries and N+1 pointers to subpages.
37592 **
37593 **   ----------------------------------------------------------------
37594 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
37595 **   ----------------------------------------------------------------
37596 **
37597 ** All of the keys on the page that Ptr(0) points to have values less
37598 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
37599 ** values greater than Key(0) and less than Key(1).  All of the keys
37600 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
37601 ** so forth.
37602 **
37603 ** Finding a particular key requires reading O(log(M)) pages from the 
37604 ** disk where M is the number of entries in the tree.
37605 **
37606 ** In this implementation, a single file can hold one or more separate 
37607 ** BTrees.  Each BTree is identified by the index of its root page.  The
37608 ** key and data for any entry are combined to form the "payload".  A
37609 ** fixed amount of payload can be carried directly on the database
37610 ** page.  If the payload is larger than the preset amount then surplus
37611 ** bytes are stored on overflow pages.  The payload for an entry
37612 ** and the preceding pointer are combined to form a "Cell".  Each 
37613 ** page has a small header which contains the Ptr(N) pointer and other
37614 ** information such as the size of key and data.
37615 **
37616 ** FORMAT DETAILS
37617 **
37618 ** The file is divided into pages.  The first page is called page 1,
37619 ** the second is page 2, and so forth.  A page number of zero indicates
37620 ** "no such page".  The page size can be any power of 2 between 512 and 32768.
37621 ** Each page can be either a btree page, a freelist page, an overflow
37622 ** page, or a pointer-map page.
37623 **
37624 ** The first page is always a btree page.  The first 100 bytes of the first
37625 ** page contain a special header (the "file header") that describes the file.
37626 ** The format of the file header is as follows:
37627 **
37628 **   OFFSET   SIZE    DESCRIPTION
37629 **      0      16     Header string: "SQLite format 3\000"
37630 **     16       2     Page size in bytes.  
37631 **     18       1     File format write version
37632 **     19       1     File format read version
37633 **     20       1     Bytes of unused space at the end of each page
37634 **     21       1     Max embedded payload fraction
37635 **     22       1     Min embedded payload fraction
37636 **     23       1     Min leaf payload fraction
37637 **     24       4     File change counter
37638 **     28       4     Reserved for future use
37639 **     32       4     First freelist page
37640 **     36       4     Number of freelist pages in the file
37641 **     40      60     15 4-byte meta values passed to higher layers
37642 **
37643 **     40       4     Schema cookie
37644 **     44       4     File format of schema layer
37645 **     48       4     Size of page cache
37646 **     52       4     Largest root-page (auto/incr_vacuum)
37647 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
37648 **     60       4     User version
37649 **     64       4     Incremental vacuum mode
37650 **     68       4     unused
37651 **     72       4     unused
37652 **     76       4     unused
37653 **
37654 ** All of the integer values are big-endian (most significant byte first).
37655 **
37656 ** The file change counter is incremented when the database is changed
37657 ** This counter allows other processes to know when the file has changed
37658 ** and thus when they need to flush their cache.
37659 **
37660 ** The max embedded payload fraction is the amount of the total usable
37661 ** space in a page that can be consumed by a single cell for standard
37662 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
37663 ** is to limit the maximum cell size so that at least 4 cells will fit
37664 ** on one page.  Thus the default max embedded payload fraction is 64.
37665 **
37666 ** If the payload for a cell is larger than the max payload, then extra
37667 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
37668 ** as many bytes as possible are moved into the overflow pages without letting
37669 ** the cell size drop below the min embedded payload fraction.
37670 **
37671 ** The min leaf payload fraction is like the min embedded payload fraction
37672 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
37673 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
37674 ** not specified in the header.
37675 **
37676 ** Each btree pages is divided into three sections:  The header, the
37677 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
37678 ** file header that occurs before the page header.
37679 **
37680 **      |----------------|
37681 **      | file header    |   100 bytes.  Page 1 only.
37682 **      |----------------|
37683 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
37684 **      |----------------|
37685 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
37686 **      | array          |   |  Grows downward
37687 **      |                |   v
37688 **      |----------------|
37689 **      | unallocated    |
37690 **      | space          |
37691 **      |----------------|   ^  Grows upwards
37692 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
37693 **      | area           |   |  and free space fragments.
37694 **      |----------------|
37695 **
37696 ** The page headers looks like this:
37697 **
37698 **   OFFSET   SIZE     DESCRIPTION
37699 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
37700 **      1       2      byte offset to the first freeblock
37701 **      3       2      number of cells on this page
37702 **      5       2      first byte of the cell content area
37703 **      7       1      number of fragmented free bytes
37704 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
37705 **
37706 ** The flags define the format of this btree page.  The leaf flag means that
37707 ** this page has no children.  The zerodata flag means that this page carries
37708 ** only keys and no data.  The intkey flag means that the key is a integer
37709 ** which is stored in the key size entry of the cell header rather than in
37710 ** the payload area.
37711 **
37712 ** The cell pointer array begins on the first byte after the page header.
37713 ** The cell pointer array contains zero or more 2-byte numbers which are
37714 ** offsets from the beginning of the page to the cell content in the cell
37715 ** content area.  The cell pointers occur in sorted order.  The system strives
37716 ** to keep free space after the last cell pointer so that new cells can
37717 ** be easily added without having to defragment the page.
37718 **
37719 ** Cell content is stored at the very end of the page and grows toward the
37720 ** beginning of the page.
37721 **
37722 ** Unused space within the cell content area is collected into a linked list of
37723 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
37724 ** to the first freeblock is given in the header.  Freeblocks occur in
37725 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
37726 ** any group of 3 or fewer unused bytes in the cell content area cannot
37727 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
37728 ** a fragment.  The total number of bytes in all fragments is recorded.
37729 ** in the page header at offset 7.
37730 **
37731 **    SIZE    DESCRIPTION
37732 **      2     Byte offset of the next freeblock
37733 **      2     Bytes in this freeblock
37734 **
37735 ** Cells are of variable length.  Cells are stored in the cell content area at
37736 ** the end of the page.  Pointers to the cells are in the cell pointer array
37737 ** that immediately follows the page header.  Cells is not necessarily
37738 ** contiguous or in order, but cell pointers are contiguous and in order.
37739 **
37740 ** Cell content makes use of variable length integers.  A variable
37741 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
37742 ** byte are used.  The integer consists of all bytes that have bit 8 set and
37743 ** the first byte with bit 8 clear.  The most significant byte of the integer
37744 ** appears first.  A variable-length integer may not be more than 9 bytes long.
37745 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
37746 ** allows a 64-bit integer to be encoded in 9 bytes.
37747 **
37748 **    0x00                      becomes  0x00000000
37749 **    0x7f                      becomes  0x0000007f
37750 **    0x81 0x00                 becomes  0x00000080
37751 **    0x82 0x00                 becomes  0x00000100
37752 **    0x80 0x7f                 becomes  0x0000007f
37753 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
37754 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
37755 **
37756 ** Variable length integers are used for rowids and to hold the number of
37757 ** bytes of key and data in a btree cell.
37758 **
37759 ** The content of a cell looks like this:
37760 **
37761 **    SIZE    DESCRIPTION
37762 **      4     Page number of the left child. Omitted if leaf flag is set.
37763 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
37764 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
37765 **      *     Payload
37766 **      4     First page of the overflow chain.  Omitted if no overflow
37767 **
37768 ** Overflow pages form a linked list.  Each page except the last is completely
37769 ** filled with data (pagesize - 4 bytes).  The last page can have as little
37770 ** as 1 byte of data.
37771 **
37772 **    SIZE    DESCRIPTION
37773 **      4     Page number of next overflow page
37774 **      *     Data
37775 **
37776 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
37777 ** file header points to the first in a linked list of trunk page.  Each trunk
37778 ** page points to multiple leaf pages.  The content of a leaf page is
37779 ** unspecified.  A trunk page looks like this:
37780 **
37781 **    SIZE    DESCRIPTION
37782 **      4     Page number of next trunk page
37783 **      4     Number of leaf pointers on this page
37784 **      *     zero or more pages numbers of leaves
37785 */
37786
37787
37788 /* The following value is the maximum cell size assuming a maximum page
37789 ** size give above.
37790 */
37791 #define MX_CELL_SIZE(pBt)  (pBt->pageSize-8)
37792
37793 /* The maximum number of cells on a single page of the database.  This
37794 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
37795 ** plus 2 bytes for the index to the cell in the page header).  Such
37796 ** small cells will be rare, but they are possible.
37797 */
37798 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
37799
37800 /* Forward declarations */
37801 typedef struct MemPage MemPage;
37802 typedef struct BtLock BtLock;
37803
37804 /*
37805 ** This is a magic string that appears at the beginning of every
37806 ** SQLite database in order to identify the file as a real database.
37807 **
37808 ** You can change this value at compile-time by specifying a
37809 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
37810 ** header must be exactly 16 bytes including the zero-terminator so
37811 ** the string itself should be 15 characters long.  If you change
37812 ** the header, then your custom library will not be able to read 
37813 ** databases generated by the standard tools and the standard tools
37814 ** will not be able to read databases created by your custom library.
37815 */
37816 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
37817 #  define SQLITE_FILE_HEADER "SQLite format 3"
37818 #endif
37819
37820 /*
37821 ** Page type flags.  An ORed combination of these flags appear as the
37822 ** first byte of on-disk image of every BTree page.
37823 */
37824 #define PTF_INTKEY    0x01
37825 #define PTF_ZERODATA  0x02
37826 #define PTF_LEAFDATA  0x04
37827 #define PTF_LEAF      0x08
37828
37829 /*
37830 ** As each page of the file is loaded into memory, an instance of the following
37831 ** structure is appended and initialized to zero.  This structure stores
37832 ** information about the page that is decoded from the raw file page.
37833 **
37834 ** The pParent field points back to the parent page.  This allows us to
37835 ** walk up the BTree from any leaf to the root.  Care must be taken to
37836 ** unref() the parent page pointer when this page is no longer referenced.
37837 ** The pageDestructor() routine handles that chore.
37838 **
37839 ** Access to all fields of this structure is controlled by the mutex
37840 ** stored in MemPage.pBt->mutex.
37841 */
37842 struct MemPage {
37843   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
37844   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
37845   u8 intKey;           /* True if intkey flag is set */
37846   u8 leaf;             /* True if leaf flag is set */
37847   u8 hasData;          /* True if this page stores data */
37848   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
37849   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
37850   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
37851   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
37852   u16 cellOffset;      /* Index in aData of first cell pointer */
37853   u16 nFree;           /* Number of free bytes on the page */
37854   u16 nCell;           /* Number of cells on this page, local and ovfl */
37855   u16 maskPage;        /* Mask for page offset */
37856   struct _OvflCell {   /* Cells that will not fit on aData[] */
37857     u8 *pCell;          /* Pointers to the body of the overflow cell */
37858     u16 idx;            /* Insert this cell before idx-th non-overflow cell */
37859   } aOvfl[5];
37860   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
37861   u8 *aData;           /* Pointer to disk image of the page data */
37862   DbPage *pDbPage;     /* Pager page handle */
37863   Pgno pgno;           /* Page number for this page */
37864 };
37865
37866 /*
37867 ** The in-memory image of a disk page has the auxiliary information appended
37868 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
37869 ** that extra information.
37870 */
37871 #define EXTRA_SIZE sizeof(MemPage)
37872
37873 /*
37874 ** A linked list of the following structures is stored at BtShared.pLock.
37875 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
37876 ** is opened on the table with root page BtShared.iTable. Locks are removed
37877 ** from this list when a transaction is committed or rolled back, or when
37878 ** a btree handle is closed.
37879 */
37880 struct BtLock {
37881   Btree *pBtree;        /* Btree handle holding this lock */
37882   Pgno iTable;          /* Root page of table */
37883   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
37884   BtLock *pNext;        /* Next in BtShared.pLock list */
37885 };
37886
37887 /* Candidate values for BtLock.eLock */
37888 #define READ_LOCK     1
37889 #define WRITE_LOCK    2
37890
37891 /* A Btree handle
37892 **
37893 ** A database connection contains a pointer to an instance of
37894 ** this object for every database file that it has open.  This structure
37895 ** is opaque to the database connection.  The database connection cannot
37896 ** see the internals of this structure and only deals with pointers to
37897 ** this structure.
37898 **
37899 ** For some database files, the same underlying database cache might be 
37900 ** shared between multiple connections.  In that case, each connection
37901 ** has it own instance of this object.  But each instance of this object
37902 ** points to the same BtShared object.  The database cache and the
37903 ** schema associated with the database file are all contained within
37904 ** the BtShared object.
37905 **
37906 ** All fields in this structure are accessed under sqlite3.mutex.
37907 ** The pBt pointer itself may not be changed while there exists cursors 
37908 ** in the referenced BtShared that point back to this Btree since those
37909 ** cursors have to do go through this Btree to find their BtShared and
37910 ** they often do so without holding sqlite3.mutex.
37911 */
37912 struct Btree {
37913   sqlite3 *db;       /* The database connection holding this btree */
37914   BtShared *pBt;     /* Sharable content of this btree */
37915   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
37916   u8 sharable;       /* True if we can share pBt with another db */
37917   u8 locked;         /* True if db currently has pBt locked */
37918   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
37919   int nBackup;       /* Number of backup operations reading this btree */
37920   Btree *pNext;      /* List of other sharable Btrees from the same db */
37921   Btree *pPrev;      /* Back pointer of the same list */
37922 #ifndef SQLITE_OMIT_SHARED_CACHE
37923   BtLock lock;       /* Object used to lock page 1 */
37924 #endif
37925 };
37926
37927 /*
37928 ** Btree.inTrans may take one of the following values.
37929 **
37930 ** If the shared-data extension is enabled, there may be multiple users
37931 ** of the Btree structure. At most one of these may open a write transaction,
37932 ** but any number may have active read transactions.
37933 */
37934 #define TRANS_NONE  0
37935 #define TRANS_READ  1
37936 #define TRANS_WRITE 2
37937
37938 /*
37939 ** An instance of this object represents a single database file.
37940 ** 
37941 ** A single database file can be in use as the same time by two
37942 ** or more database connections.  When two or more connections are
37943 ** sharing the same database file, each connection has it own
37944 ** private Btree object for the file and each of those Btrees points
37945 ** to this one BtShared object.  BtShared.nRef is the number of
37946 ** connections currently sharing this database file.
37947 **
37948 ** Fields in this structure are accessed under the BtShared.mutex
37949 ** mutex, except for nRef and pNext which are accessed under the
37950 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
37951 ** may not be modified once it is initially set as long as nRef>0.
37952 ** The pSchema field may be set once under BtShared.mutex and
37953 ** thereafter is unchanged as long as nRef>0.
37954 **
37955 ** isPending:
37956 **
37957 **   If a BtShared client fails to obtain a write-lock on a database
37958 **   table (because there exists one or more read-locks on the table),
37959 **   the shared-cache enters 'pending-lock' state and isPending is
37960 **   set to true.
37961 **
37962 **   The shared-cache leaves the 'pending lock' state when either of
37963 **   the following occur:
37964 **
37965 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
37966 **     2) The number of locks held by other connections drops to zero.
37967 **
37968 **   while in the 'pending-lock' state, no connection may start a new
37969 **   transaction.
37970 **
37971 **   This feature is included to help prevent writer-starvation.
37972 */
37973 struct BtShared {
37974   Pager *pPager;        /* The page cache */
37975   sqlite3 *db;          /* Database connection currently using this Btree */
37976   BtCursor *pCursor;    /* A list of all open cursors */
37977   MemPage *pPage1;      /* First page of the database */
37978   u8 readOnly;          /* True if the underlying file is readonly */
37979   u8 pageSizeFixed;     /* True if the page size can no longer be changed */
37980   u8 secureDelete;      /* True if secure_delete is enabled */
37981 #ifndef SQLITE_OMIT_AUTOVACUUM
37982   u8 autoVacuum;        /* True if auto-vacuum is enabled */
37983   u8 incrVacuum;        /* True if incr-vacuum is enabled */
37984 #endif
37985   u16 pageSize;         /* Total number of bytes on a page */
37986   u16 usableSize;       /* Number of usable bytes on each page */
37987   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
37988   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
37989   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
37990   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
37991   u8 inTransaction;     /* Transaction state */
37992   int nTransaction;     /* Number of open transactions (read + write) */
37993   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
37994   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
37995   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this struct */
37996   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
37997 #ifndef SQLITE_OMIT_SHARED_CACHE
37998   int nRef;             /* Number of references to this structure */
37999   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
38000   BtLock *pLock;        /* List of locks held on this shared-btree struct */
38001   Btree *pWriter;       /* Btree with currently open write transaction */
38002   u8 isExclusive;       /* True if pWriter has an EXCLUSIVE lock on the db */
38003   u8 isPending;         /* If waiting for read-locks to clear */
38004 #endif
38005   u8 *pTmpSpace;        /* BtShared.pageSize bytes of space for tmp use */
38006 };
38007
38008 /*
38009 ** An instance of the following structure is used to hold information
38010 ** about a cell.  The parseCellPtr() function fills in this structure
38011 ** based on information extract from the raw disk page.
38012 */
38013 typedef struct CellInfo CellInfo;
38014 struct CellInfo {
38015   u8 *pCell;     /* Pointer to the start of cell content */
38016   i64 nKey;      /* The key for INTKEY tables, or number of bytes in key */
38017   u32 nData;     /* Number of bytes of data */
38018   u32 nPayload;  /* Total amount of payload */
38019   u16 nHeader;   /* Size of the cell content header in bytes */
38020   u16 nLocal;    /* Amount of payload held locally */
38021   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
38022   u16 nSize;     /* Size of the cell content on the main b-tree page */
38023 };
38024
38025 /*
38026 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
38027 ** this will be declared corrupt. This value is calculated based on a
38028 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
38029 ** root-node and 3 for all other internal nodes.
38030 **
38031 ** If a tree that appears to be taller than this is encountered, it is
38032 ** assumed that the database is corrupt.
38033 */
38034 #define BTCURSOR_MAX_DEPTH 20
38035
38036 /*
38037 ** A cursor is a pointer to a particular entry within a particular
38038 ** b-tree within a database file.
38039 **
38040 ** The entry is identified by its MemPage and the index in
38041 ** MemPage.aCell[] of the entry.
38042 **
38043 ** A single database file can shared by two more database connections,
38044 ** but cursors cannot be shared.  Each cursor is associated with a
38045 ** particular database connection identified BtCursor.pBtree.db.
38046 **
38047 ** Fields in this structure are accessed under the BtShared.mutex
38048 ** found at self->pBt->mutex. 
38049 */
38050 struct BtCursor {
38051   Btree *pBtree;            /* The Btree to which this cursor belongs */
38052   BtShared *pBt;            /* The BtShared this cursor points to */
38053   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
38054   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
38055   Pgno pgnoRoot;            /* The root page of this tree */
38056   sqlite3_int64 cachedRowid; /* Next rowid cache.  0 means not valid */
38057   CellInfo info;            /* A parse of the cell we are pointing at */
38058   u8 wrFlag;                /* True if writable */
38059   u8 atLast;                /* Cursor pointing to the last entry */
38060   u8 validNKey;             /* True if info.nKey is valid */
38061   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
38062   void *pKey;      /* Saved key that was cursor's last known position */
38063   i64 nKey;        /* Size of pKey, or last integer key */
38064   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive */
38065 #ifndef SQLITE_OMIT_INCRBLOB
38066   u8 isIncrblobHandle;      /* True if this cursor is an incr. io handle */
38067   Pgno *aOverflow;          /* Cache of overflow page locations */
38068 #endif
38069   i16 iPage;                            /* Index of current page in apPage */
38070   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
38071   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
38072 };
38073
38074 /*
38075 ** Potential values for BtCursor.eState.
38076 **
38077 ** CURSOR_VALID:
38078 **   Cursor points to a valid entry. getPayload() etc. may be called.
38079 **
38080 ** CURSOR_INVALID:
38081 **   Cursor does not point to a valid entry. This can happen (for example) 
38082 **   because the table is empty or because BtreeCursorFirst() has not been
38083 **   called.
38084 **
38085 ** CURSOR_REQUIRESEEK:
38086 **   The table that this cursor was opened on still exists, but has been 
38087 **   modified since the cursor was last used. The cursor position is saved
38088 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
38089 **   this state, restoreCursorPosition() can be called to attempt to
38090 **   seek the cursor to the saved position.
38091 **
38092 ** CURSOR_FAULT:
38093 **   A unrecoverable error (an I/O error or a malloc failure) has occurred
38094 **   on a different connection that shares the BtShared cache with this
38095 **   cursor.  The error has left the cache in an inconsistent state.
38096 **   Do nothing else with this cursor.  Any attempt to use the cursor
38097 **   should return the error code stored in BtCursor.skip
38098 */
38099 #define CURSOR_INVALID           0
38100 #define CURSOR_VALID             1
38101 #define CURSOR_REQUIRESEEK       2
38102 #define CURSOR_FAULT             3
38103
38104 /* 
38105 ** The database page the PENDING_BYTE occupies. This page is never used.
38106 */
38107 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
38108
38109 /*
38110 ** These macros define the location of the pointer-map entry for a 
38111 ** database page. The first argument to each is the number of usable
38112 ** bytes on each page of the database (often 1024). The second is the
38113 ** page number to look up in the pointer map.
38114 **
38115 ** PTRMAP_PAGENO returns the database page number of the pointer-map
38116 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
38117 ** the offset of the requested map entry.
38118 **
38119 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
38120 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
38121 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
38122 ** this test.
38123 */
38124 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
38125 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
38126 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
38127
38128 /*
38129 ** The pointer map is a lookup table that identifies the parent page for
38130 ** each child page in the database file.  The parent page is the page that
38131 ** contains a pointer to the child.  Every page in the database contains
38132 ** 0 or 1 parent pages.  (In this context 'database page' refers
38133 ** to any page that is not part of the pointer map itself.)  Each pointer map
38134 ** entry consists of a single byte 'type' and a 4 byte parent page number.
38135 ** The PTRMAP_XXX identifiers below are the valid types.
38136 **
38137 ** The purpose of the pointer map is to facility moving pages from one
38138 ** position in the file to another as part of autovacuum.  When a page
38139 ** is moved, the pointer in its parent must be updated to point to the
38140 ** new location.  The pointer map is used to locate the parent page quickly.
38141 **
38142 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
38143 **                  used in this case.
38144 **
38145 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
38146 **                  is not used in this case.
38147 **
38148 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
38149 **                   overflow pages. The page number identifies the page that
38150 **                   contains the cell with a pointer to this overflow page.
38151 **
38152 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
38153 **                   overflow pages. The page-number identifies the previous
38154 **                   page in the overflow page list.
38155 **
38156 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
38157 **               identifies the parent page in the btree.
38158 */
38159 #define PTRMAP_ROOTPAGE 1
38160 #define PTRMAP_FREEPAGE 2
38161 #define PTRMAP_OVERFLOW1 3
38162 #define PTRMAP_OVERFLOW2 4
38163 #define PTRMAP_BTREE 5
38164
38165 /* A bunch of assert() statements to check the transaction state variables
38166 ** of handle p (type Btree*) are internally consistent.
38167 */
38168 #define btreeIntegrity(p) \
38169   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
38170   assert( p->pBt->inTransaction>=p->inTrans ); 
38171
38172
38173 /*
38174 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
38175 ** if the database supports auto-vacuum or not. Because it is used
38176 ** within an expression that is an argument to another macro 
38177 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
38178 ** So, this macro is defined instead.
38179 */
38180 #ifndef SQLITE_OMIT_AUTOVACUUM
38181 #define ISAUTOVACUUM (pBt->autoVacuum)
38182 #else
38183 #define ISAUTOVACUUM 0
38184 #endif
38185
38186
38187 /*
38188 ** This structure is passed around through all the sanity checking routines
38189 ** in order to keep track of some global state information.
38190 */
38191 typedef struct IntegrityCk IntegrityCk;
38192 struct IntegrityCk {
38193   BtShared *pBt;    /* The tree being checked out */
38194   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
38195   Pgno nPage;       /* Number of pages in the database */
38196   int *anRef;       /* Number of times each page is referenced */
38197   int mxErr;        /* Stop accumulating errors when this reaches zero */
38198   int nErr;         /* Number of messages written to zErrMsg so far */
38199   int mallocFailed; /* A memory allocation error has occurred */
38200   StrAccum errMsg;  /* Accumulate the error message text here */
38201 };
38202
38203 /*
38204 ** Read or write a two- and four-byte big-endian integer values.
38205 */
38206 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
38207 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
38208 #define get4byte sqlite3Get4byte
38209 #define put4byte sqlite3Put4byte
38210
38211 /************** End of btreeInt.h ********************************************/
38212 /************** Continuing where we left off in btmutex.c ********************/
38213 #ifndef SQLITE_OMIT_SHARED_CACHE
38214 #if SQLITE_THREADSAFE
38215
38216 /*
38217 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
38218 ** set BtShared.db to the database handle associated with p and the
38219 ** p->locked boolean to true.
38220 */
38221 static void lockBtreeMutex(Btree *p){
38222   assert( p->locked==0 );
38223   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
38224   assert( sqlite3_mutex_held(p->db->mutex) );
38225
38226   sqlite3_mutex_enter(p->pBt->mutex);
38227   p->pBt->db = p->db;
38228   p->locked = 1;
38229 }
38230
38231 /*
38232 ** Release the BtShared mutex associated with B-Tree handle p and
38233 ** clear the p->locked boolean.
38234 */
38235 static void unlockBtreeMutex(Btree *p){
38236   assert( p->locked==1 );
38237   assert( sqlite3_mutex_held(p->pBt->mutex) );
38238   assert( sqlite3_mutex_held(p->db->mutex) );
38239   assert( p->db==p->pBt->db );
38240
38241   sqlite3_mutex_leave(p->pBt->mutex);
38242   p->locked = 0;
38243 }
38244
38245 /*
38246 ** Enter a mutex on the given BTree object.
38247 **
38248 ** If the object is not sharable, then no mutex is ever required
38249 ** and this routine is a no-op.  The underlying mutex is non-recursive.
38250 ** But we keep a reference count in Btree.wantToLock so the behavior
38251 ** of this interface is recursive.
38252 **
38253 ** To avoid deadlocks, multiple Btrees are locked in the same order
38254 ** by all database connections.  The p->pNext is a list of other
38255 ** Btrees belonging to the same database connection as the p Btree
38256 ** which need to be locked after p.  If we cannot get a lock on
38257 ** p, then first unlock all of the others on p->pNext, then wait
38258 ** for the lock to become available on p, then relock all of the
38259 ** subsequent Btrees that desire a lock.
38260 */
38261 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
38262   Btree *pLater;
38263
38264   /* Some basic sanity checking on the Btree.  The list of Btrees
38265   ** connected by pNext and pPrev should be in sorted order by
38266   ** Btree.pBt value. All elements of the list should belong to
38267   ** the same connection. Only shared Btrees are on the list. */
38268   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
38269   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
38270   assert( p->pNext==0 || p->pNext->db==p->db );
38271   assert( p->pPrev==0 || p->pPrev->db==p->db );
38272   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
38273
38274   /* Check for locking consistency */
38275   assert( !p->locked || p->wantToLock>0 );
38276   assert( p->sharable || p->wantToLock==0 );
38277
38278   /* We should already hold a lock on the database connection */
38279   assert( sqlite3_mutex_held(p->db->mutex) );
38280
38281   /* Unless the database is sharable and unlocked, then BtShared.db
38282   ** should already be set correctly. */
38283   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
38284
38285   if( !p->sharable ) return;
38286   p->wantToLock++;
38287   if( p->locked ) return;
38288
38289   /* In most cases, we should be able to acquire the lock we
38290   ** want without having to go throught the ascending lock
38291   ** procedure that follows.  Just be sure not to block.
38292   */
38293   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
38294     p->pBt->db = p->db;
38295     p->locked = 1;
38296     return;
38297   }
38298
38299   /* To avoid deadlock, first release all locks with a larger
38300   ** BtShared address.  Then acquire our lock.  Then reacquire
38301   ** the other BtShared locks that we used to hold in ascending
38302   ** order.
38303   */
38304   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
38305     assert( pLater->sharable );
38306     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
38307     assert( !pLater->locked || pLater->wantToLock>0 );
38308     if( pLater->locked ){
38309       unlockBtreeMutex(pLater);
38310     }
38311   }
38312   lockBtreeMutex(p);
38313   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
38314     if( pLater->wantToLock ){
38315       lockBtreeMutex(pLater);
38316     }
38317   }
38318 }
38319
38320 /*
38321 ** Exit the recursive mutex on a Btree.
38322 */
38323 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
38324   if( p->sharable ){
38325     assert( p->wantToLock>0 );
38326     p->wantToLock--;
38327     if( p->wantToLock==0 ){
38328       unlockBtreeMutex(p);
38329     }
38330   }
38331 }
38332
38333 #ifndef NDEBUG
38334 /*
38335 ** Return true if the BtShared mutex is held on the btree, or if the
38336 ** B-Tree is not marked as sharable.
38337 **
38338 ** This routine is used only from within assert() statements.
38339 */
38340 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
38341   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
38342   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
38343   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
38344   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
38345
38346   return (p->sharable==0 || p->locked);
38347 }
38348 #endif
38349
38350
38351 #ifndef SQLITE_OMIT_INCRBLOB
38352 /*
38353 ** Enter and leave a mutex on a Btree given a cursor owned by that
38354 ** Btree.  These entry points are used by incremental I/O and can be
38355 ** omitted if that module is not used.
38356 */
38357 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
38358   sqlite3BtreeEnter(pCur->pBtree);
38359 }
38360 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
38361   sqlite3BtreeLeave(pCur->pBtree);
38362 }
38363 #endif /* SQLITE_OMIT_INCRBLOB */
38364
38365
38366 /*
38367 ** Enter the mutex on every Btree associated with a database
38368 ** connection.  This is needed (for example) prior to parsing
38369 ** a statement since we will be comparing table and column names
38370 ** against all schemas and we do not want those schemas being
38371 ** reset out from under us.
38372 **
38373 ** There is a corresponding leave-all procedures.
38374 **
38375 ** Enter the mutexes in accending order by BtShared pointer address
38376 ** to avoid the possibility of deadlock when two threads with
38377 ** two or more btrees in common both try to lock all their btrees
38378 ** at the same instant.
38379 */
38380 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
38381   int i;
38382   Btree *p, *pLater;
38383   assert( sqlite3_mutex_held(db->mutex) );
38384   for(i=0; i<db->nDb; i++){
38385     p = db->aDb[i].pBt;
38386     assert( !p || (p->locked==0 && p->sharable) || p->pBt->db==p->db );
38387     if( p && p->sharable ){
38388       p->wantToLock++;
38389       if( !p->locked ){
38390         assert( p->wantToLock==1 );
38391         while( p->pPrev ) p = p->pPrev;
38392         /* Reason for ALWAYS:  There must be at least on unlocked Btree in
38393         ** the chain.  Otherwise the !p->locked test above would have failed */
38394         while( p->locked && ALWAYS(p->pNext) ) p = p->pNext;
38395         for(pLater = p->pNext; pLater; pLater=pLater->pNext){
38396           if( pLater->locked ){
38397             unlockBtreeMutex(pLater);
38398           }
38399         }
38400         while( p ){
38401           lockBtreeMutex(p);
38402           p = p->pNext;
38403         }
38404       }
38405     }
38406   }
38407 }
38408 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
38409   int i;
38410   Btree *p;
38411   assert( sqlite3_mutex_held(db->mutex) );
38412   for(i=0; i<db->nDb; i++){
38413     p = db->aDb[i].pBt;
38414     if( p && p->sharable ){
38415       assert( p->wantToLock>0 );
38416       p->wantToLock--;
38417       if( p->wantToLock==0 ){
38418         unlockBtreeMutex(p);
38419       }
38420     }
38421   }
38422 }
38423
38424 #ifndef NDEBUG
38425 /*
38426 ** Return true if the current thread holds the database connection
38427 ** mutex and all required BtShared mutexes.
38428 **
38429 ** This routine is used inside assert() statements only.
38430 */
38431 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
38432   int i;
38433   if( !sqlite3_mutex_held(db->mutex) ){
38434     return 0;
38435   }
38436   for(i=0; i<db->nDb; i++){
38437     Btree *p;
38438     p = db->aDb[i].pBt;
38439     if( p && p->sharable &&
38440          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
38441       return 0;
38442     }
38443   }
38444   return 1;
38445 }
38446 #endif /* NDEBUG */
38447
38448 /*
38449 ** Add a new Btree pointer to a BtreeMutexArray. 
38450 ** if the pointer can possibly be shared with
38451 ** another database connection.
38452 **
38453 ** The pointers are kept in sorted order by pBtree->pBt.  That
38454 ** way when we go to enter all the mutexes, we can enter them
38455 ** in order without every having to backup and retry and without
38456 ** worrying about deadlock.
38457 **
38458 ** The number of shared btrees will always be small (usually 0 or 1)
38459 ** so an insertion sort is an adequate algorithm here.
38460 */
38461 SQLITE_PRIVATE void sqlite3BtreeMutexArrayInsert(BtreeMutexArray *pArray, Btree *pBtree){
38462   int i, j;
38463   BtShared *pBt;
38464   if( pBtree==0 || pBtree->sharable==0 ) return;
38465 #ifndef NDEBUG
38466   {
38467     for(i=0; i<pArray->nMutex; i++){
38468       assert( pArray->aBtree[i]!=pBtree );
38469     }
38470   }
38471 #endif
38472   assert( pArray->nMutex>=0 );
38473   assert( pArray->nMutex<ArraySize(pArray->aBtree)-1 );
38474   pBt = pBtree->pBt;
38475   for(i=0; i<pArray->nMutex; i++){
38476     assert( pArray->aBtree[i]!=pBtree );
38477     if( pArray->aBtree[i]->pBt>pBt ){
38478       for(j=pArray->nMutex; j>i; j--){
38479         pArray->aBtree[j] = pArray->aBtree[j-1];
38480       }
38481       pArray->aBtree[i] = pBtree;
38482       pArray->nMutex++;
38483       return;
38484     }
38485   }
38486   pArray->aBtree[pArray->nMutex++] = pBtree;
38487 }
38488
38489 /*
38490 ** Enter the mutex of every btree in the array.  This routine is
38491 ** called at the beginning of sqlite3VdbeExec().  The mutexes are
38492 ** exited at the end of the same function.
38493 */
38494 SQLITE_PRIVATE void sqlite3BtreeMutexArrayEnter(BtreeMutexArray *pArray){
38495   int i;
38496   for(i=0; i<pArray->nMutex; i++){
38497     Btree *p = pArray->aBtree[i];
38498     /* Some basic sanity checking */
38499     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
38500     assert( !p->locked || p->wantToLock>0 );
38501
38502     /* We should already hold a lock on the database connection */
38503     assert( sqlite3_mutex_held(p->db->mutex) );
38504
38505     /* The Btree is sharable because only sharable Btrees are entered
38506     ** into the array in the first place. */
38507     assert( p->sharable );
38508
38509     p->wantToLock++;
38510     if( !p->locked ){
38511       lockBtreeMutex(p);
38512     }
38513   }
38514 }
38515
38516 /*
38517 ** Leave the mutex of every btree in the group.
38518 */
38519 SQLITE_PRIVATE void sqlite3BtreeMutexArrayLeave(BtreeMutexArray *pArray){
38520   int i;
38521   for(i=0; i<pArray->nMutex; i++){
38522     Btree *p = pArray->aBtree[i];
38523     /* Some basic sanity checking */
38524     assert( i==0 || pArray->aBtree[i-1]->pBt<p->pBt );
38525     assert( p->locked );
38526     assert( p->wantToLock>0 );
38527
38528     /* We should already hold a lock on the database connection */
38529     assert( sqlite3_mutex_held(p->db->mutex) );
38530
38531     p->wantToLock--;
38532     if( p->wantToLock==0 ){
38533       unlockBtreeMutex(p);
38534     }
38535   }
38536 }
38537
38538 #else
38539 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
38540   p->pBt->db = p->db;
38541 }
38542 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
38543   int i;
38544   for(i=0; i<db->nDb; i++){
38545     Btree *p = db->aDb[i].pBt;
38546     if( p ){
38547       p->pBt->db = p->db;
38548     }
38549   }
38550 }
38551 #endif /* if SQLITE_THREADSAFE */
38552 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
38553
38554 /************** End of btmutex.c *********************************************/
38555 /************** Begin file btree.c *******************************************/
38556 /*
38557 ** 2004 April 6
38558 **
38559 ** The author disclaims copyright to this source code.  In place of
38560 ** a legal notice, here is a blessing:
38561 **
38562 **    May you do good and not evil.
38563 **    May you find forgiveness for yourself and forgive others.
38564 **    May you share freely, never taking more than you give.
38565 **
38566 *************************************************************************
38567 ** This file implements a external (disk-based) database using BTrees.
38568 ** See the header comment on "btreeInt.h" for additional information.
38569 ** Including a description of file format and an overview of operation.
38570 */
38571
38572 /*
38573 ** The header string that appears at the beginning of every
38574 ** SQLite database.
38575 */
38576 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
38577
38578 /*
38579 ** Set this global variable to 1 to enable tracing using the TRACE
38580 ** macro.
38581 */
38582 #if 0
38583 int sqlite3BtreeTrace=1;  /* True to enable tracing */
38584 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
38585 #else
38586 # define TRACE(X)
38587 #endif
38588
38589
38590
38591 #ifndef SQLITE_OMIT_SHARED_CACHE
38592 /*
38593 ** A list of BtShared objects that are eligible for participation
38594 ** in shared cache.  This variable has file scope during normal builds,
38595 ** but the test harness needs to access it so we make it global for 
38596 ** test builds.
38597 **
38598 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
38599 */
38600 #ifdef SQLITE_TEST
38601 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
38602 #else
38603 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
38604 #endif
38605 #endif /* SQLITE_OMIT_SHARED_CACHE */
38606
38607 #ifndef SQLITE_OMIT_SHARED_CACHE
38608 /*
38609 ** Enable or disable the shared pager and schema features.
38610 **
38611 ** This routine has no effect on existing database connections.
38612 ** The shared cache setting effects only future calls to
38613 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
38614 */
38615 SQLITE_API int sqlite3_enable_shared_cache(int enable){
38616   sqlite3GlobalConfig.sharedCacheEnabled = enable;
38617   return SQLITE_OK;
38618 }
38619 #endif
38620
38621
38622
38623 #ifdef SQLITE_OMIT_SHARED_CACHE
38624   /*
38625   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
38626   ** and clearAllSharedCacheTableLocks()
38627   ** manipulate entries in the BtShared.pLock linked list used to store
38628   ** shared-cache table level locks. If the library is compiled with the
38629   ** shared-cache feature disabled, then there is only ever one user
38630   ** of each BtShared structure and so this locking is not necessary. 
38631   ** So define the lock related functions as no-ops.
38632   */
38633   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
38634   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
38635   #define clearAllSharedCacheTableLocks(a)
38636   #define downgradeAllSharedCacheTableLocks(a)
38637   #define hasSharedCacheTableLock(a,b,c,d) 1
38638   #define hasReadConflicts(a, b) 0
38639 #endif
38640
38641 #ifndef SQLITE_OMIT_SHARED_CACHE
38642
38643 #ifdef SQLITE_DEBUG
38644 /*
38645 **** This function is only used as part of an assert() statement. ***
38646 **
38647 ** Check to see if pBtree holds the required locks to read or write to the 
38648 ** table with root page iRoot.   Return 1 if it does and 0 if not.
38649 **
38650 ** For example, when writing to a table with root-page iRoot via 
38651 ** Btree connection pBtree:
38652 **
38653 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
38654 **
38655 ** When writing to an index that resides in a sharable database, the 
38656 ** caller should have first obtained a lock specifying the root page of
38657 ** the corresponding table. This makes things a bit more complicated,
38658 ** as this module treats each table as a separate structure. To determine
38659 ** the table corresponding to the index being written, this
38660 ** function has to search through the database schema.
38661 **
38662 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
38663 ** hold a write-lock on the schema table (root page 1). This is also
38664 ** acceptable.
38665 */
38666 static int hasSharedCacheTableLock(
38667   Btree *pBtree,         /* Handle that must hold lock */
38668   Pgno iRoot,            /* Root page of b-tree */
38669   int isIndex,           /* True if iRoot is the root of an index b-tree */
38670   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
38671 ){
38672   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
38673   Pgno iTab = 0;
38674   BtLock *pLock;
38675
38676   /* If this database is not shareable, or if the client is reading
38677   ** and has the read-uncommitted flag set, then no lock is required. 
38678   ** Return true immediately.
38679   */
38680   if( (pBtree->sharable==0)
38681    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
38682   ){
38683     return 1;
38684   }
38685
38686   /* If the client is reading  or writing an index and the schema is
38687   ** not loaded, then it is too difficult to actually check to see if
38688   ** the correct locks are held.  So do not bother - just return true.
38689   ** This case does not come up very often anyhow.
38690   */
38691   if( isIndex && (!pSchema || (pSchema->flags&DB_SchemaLoaded)==0) ){
38692     return 1;
38693   }
38694
38695   /* Figure out the root-page that the lock should be held on. For table
38696   ** b-trees, this is just the root page of the b-tree being read or
38697   ** written. For index b-trees, it is the root page of the associated
38698   ** table.  */
38699   if( isIndex ){
38700     HashElem *p;
38701     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
38702       Index *pIdx = (Index *)sqliteHashData(p);
38703       if( pIdx->tnum==(int)iRoot ){
38704         iTab = pIdx->pTable->tnum;
38705       }
38706     }
38707   }else{
38708     iTab = iRoot;
38709   }
38710
38711   /* Search for the required lock. Either a write-lock on root-page iTab, a 
38712   ** write-lock on the schema table, or (if the client is reading) a
38713   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
38714   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
38715     if( pLock->pBtree==pBtree 
38716      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
38717      && pLock->eLock>=eLockType 
38718     ){
38719       return 1;
38720     }
38721   }
38722
38723   /* Failed to find the required lock. */
38724   return 0;
38725 }
38726 #endif /* SQLITE_DEBUG */
38727
38728 #ifdef SQLITE_DEBUG
38729 /*
38730 **** This function may be used as part of assert() statements only. ****
38731 **
38732 ** Return true if it would be illegal for pBtree to write into the
38733 ** table or index rooted at iRoot because other shared connections are
38734 ** simultaneously reading that same table or index.
38735 **
38736 ** It is illegal for pBtree to write if some other Btree object that
38737 ** shares the same BtShared object is currently reading or writing
38738 ** the iRoot table.  Except, if the other Btree object has the
38739 ** read-uncommitted flag set, then it is OK for the other object to
38740 ** have a read cursor.
38741 **
38742 ** For example, before writing to any part of the table or index
38743 ** rooted at page iRoot, one should call:
38744 **
38745 **    assert( !hasReadConflicts(pBtree, iRoot) );
38746 */
38747 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
38748   BtCursor *p;
38749   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
38750     if( p->pgnoRoot==iRoot 
38751      && p->pBtree!=pBtree
38752      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
38753     ){
38754       return 1;
38755     }
38756   }
38757   return 0;
38758 }
38759 #endif    /* #ifdef SQLITE_DEBUG */
38760
38761 /*
38762 ** Query to see if Btree handle p may obtain a lock of type eLock 
38763 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
38764 ** SQLITE_OK if the lock may be obtained (by calling
38765 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
38766 */
38767 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
38768   BtShared *pBt = p->pBt;
38769   BtLock *pIter;
38770
38771   assert( sqlite3BtreeHoldsMutex(p) );
38772   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
38773   assert( p->db!=0 );
38774   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
38775   
38776   /* If requesting a write-lock, then the Btree must have an open write
38777   ** transaction on this file. And, obviously, for this to be so there 
38778   ** must be an open write transaction on the file itself.
38779   */
38780   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
38781   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
38782   
38783   /* This routine is a no-op if the shared-cache is not enabled */
38784   if( !p->sharable ){
38785     return SQLITE_OK;
38786   }
38787
38788   /* If some other connection is holding an exclusive lock, the
38789   ** requested lock may not be obtained.
38790   */
38791   if( pBt->pWriter!=p && pBt->isExclusive ){
38792     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
38793     return SQLITE_LOCKED_SHAREDCACHE;
38794   }
38795
38796   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
38797     /* The condition (pIter->eLock!=eLock) in the following if(...) 
38798     ** statement is a simplification of:
38799     **
38800     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
38801     **
38802     ** since we know that if eLock==WRITE_LOCK, then no other connection
38803     ** may hold a WRITE_LOCK on any table in this file (since there can
38804     ** only be a single writer).
38805     */
38806     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
38807     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
38808     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
38809       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
38810       if( eLock==WRITE_LOCK ){
38811         assert( p==pBt->pWriter );
38812         pBt->isPending = 1;
38813       }
38814       return SQLITE_LOCKED_SHAREDCACHE;
38815     }
38816   }
38817   return SQLITE_OK;
38818 }
38819 #endif /* !SQLITE_OMIT_SHARED_CACHE */
38820
38821 #ifndef SQLITE_OMIT_SHARED_CACHE
38822 /*
38823 ** Add a lock on the table with root-page iTable to the shared-btree used
38824 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
38825 ** WRITE_LOCK.
38826 **
38827 ** This function assumes the following:
38828 **
38829 **   (a) The specified Btree object p is connected to a sharable
38830 **       database (one with the BtShared.sharable flag set), and
38831 **
38832 **   (b) No other Btree objects hold a lock that conflicts
38833 **       with the requested lock (i.e. querySharedCacheTableLock() has
38834 **       already been called and returned SQLITE_OK).
38835 **
38836 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
38837 ** is returned if a malloc attempt fails.
38838 */
38839 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
38840   BtShared *pBt = p->pBt;
38841   BtLock *pLock = 0;
38842   BtLock *pIter;
38843
38844   assert( sqlite3BtreeHoldsMutex(p) );
38845   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
38846   assert( p->db!=0 );
38847
38848   /* A connection with the read-uncommitted flag set will never try to
38849   ** obtain a read-lock using this function. The only read-lock obtained
38850   ** by a connection in read-uncommitted mode is on the sqlite_master 
38851   ** table, and that lock is obtained in BtreeBeginTrans().  */
38852   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
38853
38854   /* This function should only be called on a sharable b-tree after it 
38855   ** has been determined that no other b-tree holds a conflicting lock.  */
38856   assert( p->sharable );
38857   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
38858
38859   /* First search the list for an existing lock on this table. */
38860   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
38861     if( pIter->iTable==iTable && pIter->pBtree==p ){
38862       pLock = pIter;
38863       break;
38864     }
38865   }
38866
38867   /* If the above search did not find a BtLock struct associating Btree p
38868   ** with table iTable, allocate one and link it into the list.
38869   */
38870   if( !pLock ){
38871     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
38872     if( !pLock ){
38873       return SQLITE_NOMEM;
38874     }
38875     pLock->iTable = iTable;
38876     pLock->pBtree = p;
38877     pLock->pNext = pBt->pLock;
38878     pBt->pLock = pLock;
38879   }
38880
38881   /* Set the BtLock.eLock variable to the maximum of the current lock
38882   ** and the requested lock. This means if a write-lock was already held
38883   ** and a read-lock requested, we don't incorrectly downgrade the lock.
38884   */
38885   assert( WRITE_LOCK>READ_LOCK );
38886   if( eLock>pLock->eLock ){
38887     pLock->eLock = eLock;
38888   }
38889
38890   return SQLITE_OK;
38891 }
38892 #endif /* !SQLITE_OMIT_SHARED_CACHE */
38893
38894 #ifndef SQLITE_OMIT_SHARED_CACHE
38895 /*
38896 ** Release all the table locks (locks obtained via calls to
38897 ** the setSharedCacheTableLock() procedure) held by Btree object p.
38898 **
38899 ** This function assumes that Btree p has an open read or write 
38900 ** transaction. If it does not, then the BtShared.isPending variable
38901 ** may be incorrectly cleared.
38902 */
38903 static void clearAllSharedCacheTableLocks(Btree *p){
38904   BtShared *pBt = p->pBt;
38905   BtLock **ppIter = &pBt->pLock;
38906
38907   assert( sqlite3BtreeHoldsMutex(p) );
38908   assert( p->sharable || 0==*ppIter );
38909   assert( p->inTrans>0 );
38910
38911   while( *ppIter ){
38912     BtLock *pLock = *ppIter;
38913     assert( pBt->isExclusive==0 || pBt->pWriter==pLock->pBtree );
38914     assert( pLock->pBtree->inTrans>=pLock->eLock );
38915     if( pLock->pBtree==p ){
38916       *ppIter = pLock->pNext;
38917       assert( pLock->iTable!=1 || pLock==&p->lock );
38918       if( pLock->iTable!=1 ){
38919         sqlite3_free(pLock);
38920       }
38921     }else{
38922       ppIter = &pLock->pNext;
38923     }
38924   }
38925
38926   assert( pBt->isPending==0 || pBt->pWriter );
38927   if( pBt->pWriter==p ){
38928     pBt->pWriter = 0;
38929     pBt->isExclusive = 0;
38930     pBt->isPending = 0;
38931   }else if( pBt->nTransaction==2 ){
38932     /* This function is called when Btree p is concluding its 
38933     ** transaction. If there currently exists a writer, and p is not
38934     ** that writer, then the number of locks held by connections other
38935     ** than the writer must be about to drop to zero. In this case
38936     ** set the isPending flag to 0.
38937     **
38938     ** If there is not currently a writer, then BtShared.isPending must
38939     ** be zero already. So this next line is harmless in that case.
38940     */
38941     pBt->isPending = 0;
38942   }
38943 }
38944
38945 /*
38946 ** This function changes all write-locks held by Btree p into read-locks.
38947 */
38948 static void downgradeAllSharedCacheTableLocks(Btree *p){
38949   BtShared *pBt = p->pBt;
38950   if( pBt->pWriter==p ){
38951     BtLock *pLock;
38952     pBt->pWriter = 0;
38953     pBt->isExclusive = 0;
38954     pBt->isPending = 0;
38955     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
38956       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
38957       pLock->eLock = READ_LOCK;
38958     }
38959   }
38960 }
38961
38962 #endif /* SQLITE_OMIT_SHARED_CACHE */
38963
38964 static void releasePage(MemPage *pPage);  /* Forward reference */
38965
38966 /*
38967 ***** This routine is used inside of assert() only ****
38968 **
38969 ** Verify that the cursor holds the mutex on its BtShared
38970 */
38971 #ifdef SQLITE_DEBUG
38972 static int cursorHoldsMutex(BtCursor *p){
38973   return sqlite3_mutex_held(p->pBt->mutex);
38974 }
38975 #endif
38976
38977
38978 #ifndef SQLITE_OMIT_INCRBLOB
38979 /*
38980 ** Invalidate the overflow page-list cache for cursor pCur, if any.
38981 */
38982 static void invalidateOverflowCache(BtCursor *pCur){
38983   assert( cursorHoldsMutex(pCur) );
38984   sqlite3_free(pCur->aOverflow);
38985   pCur->aOverflow = 0;
38986 }
38987
38988 /*
38989 ** Invalidate the overflow page-list cache for all cursors opened
38990 ** on the shared btree structure pBt.
38991 */
38992 static void invalidateAllOverflowCache(BtShared *pBt){
38993   BtCursor *p;
38994   assert( sqlite3_mutex_held(pBt->mutex) );
38995   for(p=pBt->pCursor; p; p=p->pNext){
38996     invalidateOverflowCache(p);
38997   }
38998 }
38999
39000 /*
39001 ** This function is called before modifying the contents of a table
39002 ** to invalidate any incrblob cursors that are open on the
39003 ** row or one of the rows being modified.
39004 **
39005 ** If argument isClearTable is true, then the entire contents of the
39006 ** table is about to be deleted. In this case invalidate all incrblob
39007 ** cursors open on any row within the table with root-page pgnoRoot.
39008 **
39009 ** Otherwise, if argument isClearTable is false, then the row with
39010 ** rowid iRow is being replaced or deleted. In this case invalidate
39011 ** only those incrblob cursors open on that specific row.
39012 */
39013 static void invalidateIncrblobCursors(
39014   Btree *pBtree,          /* The database file to check */
39015   i64 iRow,               /* The rowid that might be changing */
39016   int isClearTable        /* True if all rows are being deleted */
39017 ){
39018   BtCursor *p;
39019   BtShared *pBt = pBtree->pBt;
39020   assert( sqlite3BtreeHoldsMutex(pBtree) );
39021   for(p=pBt->pCursor; p; p=p->pNext){
39022     if( p->isIncrblobHandle && (isClearTable || p->info.nKey==iRow) ){
39023       p->eState = CURSOR_INVALID;
39024     }
39025   }
39026 }
39027
39028 #else
39029   /* Stub functions when INCRBLOB is omitted */
39030   #define invalidateOverflowCache(x)
39031   #define invalidateAllOverflowCache(x)
39032   #define invalidateIncrblobCursors(x,y,z)
39033 #endif /* SQLITE_OMIT_INCRBLOB */
39034
39035 /*
39036 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
39037 ** when a page that previously contained data becomes a free-list leaf 
39038 ** page.
39039 **
39040 ** The BtShared.pHasContent bitvec exists to work around an obscure
39041 ** bug caused by the interaction of two useful IO optimizations surrounding
39042 ** free-list leaf pages:
39043 **
39044 **   1) When all data is deleted from a page and the page becomes
39045 **      a free-list leaf page, the page is not written to the database
39046 **      (as free-list leaf pages contain no meaningful data). Sometimes
39047 **      such a page is not even journalled (as it will not be modified,
39048 **      why bother journalling it?).
39049 **
39050 **   2) When a free-list leaf page is reused, its content is not read
39051 **      from the database or written to the journal file (why should it
39052 **      be, if it is not at all meaningful?).
39053 **
39054 ** By themselves, these optimizations work fine and provide a handy
39055 ** performance boost to bulk delete or insert operations. However, if
39056 ** a page is moved to the free-list and then reused within the same
39057 ** transaction, a problem comes up. If the page is not journalled when
39058 ** it is moved to the free-list and it is also not journalled when it
39059 ** is extracted from the free-list and reused, then the original data
39060 ** may be lost. In the event of a rollback, it may not be possible
39061 ** to restore the database to its original configuration.
39062 **
39063 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
39064 ** moved to become a free-list leaf page, the corresponding bit is
39065 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
39066 ** optimization 2 above is omitted if the corresponding bit is already
39067 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
39068 ** at the end of every transaction.
39069 */
39070 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
39071   int rc = SQLITE_OK;
39072   if( !pBt->pHasContent ){
39073     int nPage = 100;
39074     sqlite3PagerPagecount(pBt->pPager, &nPage);
39075     /* If sqlite3PagerPagecount() fails there is no harm because the
39076     ** nPage variable is unchanged from its default value of 100 */
39077     pBt->pHasContent = sqlite3BitvecCreate((u32)nPage);
39078     if( !pBt->pHasContent ){
39079       rc = SQLITE_NOMEM;
39080     }
39081   }
39082   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
39083     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
39084   }
39085   return rc;
39086 }
39087
39088 /*
39089 ** Query the BtShared.pHasContent vector.
39090 **
39091 ** This function is called when a free-list leaf page is removed from the
39092 ** free-list for reuse. It returns false if it is safe to retrieve the
39093 ** page from the pager layer with the 'no-content' flag set. True otherwise.
39094 */
39095 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
39096   Bitvec *p = pBt->pHasContent;
39097   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
39098 }
39099
39100 /*
39101 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
39102 ** invoked at the conclusion of each write-transaction.
39103 */
39104 static void btreeClearHasContent(BtShared *pBt){
39105   sqlite3BitvecDestroy(pBt->pHasContent);
39106   pBt->pHasContent = 0;
39107 }
39108
39109 /*
39110 ** Save the current cursor position in the variables BtCursor.nKey 
39111 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
39112 **
39113 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
39114 ** prior to calling this routine.  
39115 */
39116 static int saveCursorPosition(BtCursor *pCur){
39117   int rc;
39118
39119   assert( CURSOR_VALID==pCur->eState );
39120   assert( 0==pCur->pKey );
39121   assert( cursorHoldsMutex(pCur) );
39122
39123   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
39124   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
39125
39126   /* If this is an intKey table, then the above call to BtreeKeySize()
39127   ** stores the integer key in pCur->nKey. In this case this value is
39128   ** all that is required. Otherwise, if pCur is not open on an intKey
39129   ** table, then malloc space for and store the pCur->nKey bytes of key 
39130   ** data.
39131   */
39132   if( 0==pCur->apPage[0]->intKey ){
39133     void *pKey = sqlite3Malloc( (int)pCur->nKey );
39134     if( pKey ){
39135       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
39136       if( rc==SQLITE_OK ){
39137         pCur->pKey = pKey;
39138       }else{
39139         sqlite3_free(pKey);
39140       }
39141     }else{
39142       rc = SQLITE_NOMEM;
39143     }
39144   }
39145   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
39146
39147   if( rc==SQLITE_OK ){
39148     int i;
39149     for(i=0; i<=pCur->iPage; i++){
39150       releasePage(pCur->apPage[i]);
39151       pCur->apPage[i] = 0;
39152     }
39153     pCur->iPage = -1;
39154     pCur->eState = CURSOR_REQUIRESEEK;
39155   }
39156
39157   invalidateOverflowCache(pCur);
39158   return rc;
39159 }
39160
39161 /*
39162 ** Save the positions of all cursors (except pExcept) that are open on
39163 ** the table  with root-page iRoot. Usually, this is called just before cursor
39164 ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
39165 */
39166 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
39167   BtCursor *p;
39168   assert( sqlite3_mutex_held(pBt->mutex) );
39169   assert( pExcept==0 || pExcept->pBt==pBt );
39170   for(p=pBt->pCursor; p; p=p->pNext){
39171     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) && 
39172         p->eState==CURSOR_VALID ){
39173       int rc = saveCursorPosition(p);
39174       if( SQLITE_OK!=rc ){
39175         return rc;
39176       }
39177     }
39178   }
39179   return SQLITE_OK;
39180 }
39181
39182 /*
39183 ** Clear the current cursor position.
39184 */
39185 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
39186   assert( cursorHoldsMutex(pCur) );
39187   sqlite3_free(pCur->pKey);
39188   pCur->pKey = 0;
39189   pCur->eState = CURSOR_INVALID;
39190 }
39191
39192 /*
39193 ** In this version of BtreeMoveto, pKey is a packed index record
39194 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
39195 ** record and then call BtreeMovetoUnpacked() to do the work.
39196 */
39197 static int btreeMoveto(
39198   BtCursor *pCur,     /* Cursor open on the btree to be searched */
39199   const void *pKey,   /* Packed key if the btree is an index */
39200   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
39201   int bias,           /* Bias search to the high end */
39202   int *pRes           /* Write search results here */
39203 ){
39204   int rc;                    /* Status code */
39205   UnpackedRecord *pIdxKey;   /* Unpacked index key */
39206   char aSpace[150];          /* Temp space for pIdxKey - to avoid a malloc */
39207
39208   if( pKey ){
39209     assert( nKey==(i64)(int)nKey );
39210     pIdxKey = sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey,
39211                                       aSpace, sizeof(aSpace));
39212     if( pIdxKey==0 ) return SQLITE_NOMEM;
39213   }else{
39214     pIdxKey = 0;
39215   }
39216   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
39217   if( pKey ){
39218     sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
39219   }
39220   return rc;
39221 }
39222
39223 /*
39224 ** Restore the cursor to the position it was in (or as close to as possible)
39225 ** when saveCursorPosition() was called. Note that this call deletes the 
39226 ** saved position info stored by saveCursorPosition(), so there can be
39227 ** at most one effective restoreCursorPosition() call after each 
39228 ** saveCursorPosition().
39229 */
39230 static int btreeRestoreCursorPosition(BtCursor *pCur){
39231   int rc;
39232   assert( cursorHoldsMutex(pCur) );
39233   assert( pCur->eState>=CURSOR_REQUIRESEEK );
39234   if( pCur->eState==CURSOR_FAULT ){
39235     return pCur->skipNext;
39236   }
39237   pCur->eState = CURSOR_INVALID;
39238   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
39239   if( rc==SQLITE_OK ){
39240     sqlite3_free(pCur->pKey);
39241     pCur->pKey = 0;
39242     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
39243   }
39244   return rc;
39245 }
39246
39247 #define restoreCursorPosition(p) \
39248   (p->eState>=CURSOR_REQUIRESEEK ? \
39249          btreeRestoreCursorPosition(p) : \
39250          SQLITE_OK)
39251
39252 /*
39253 ** Determine whether or not a cursor has moved from the position it
39254 ** was last placed at.  Cursors can move when the row they are pointing
39255 ** at is deleted out from under them.
39256 **
39257 ** This routine returns an error code if something goes wrong.  The
39258 ** integer *pHasMoved is set to one if the cursor has moved and 0 if not.
39259 */
39260 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur, int *pHasMoved){
39261   int rc;
39262
39263   rc = restoreCursorPosition(pCur);
39264   if( rc ){
39265     *pHasMoved = 1;
39266     return rc;
39267   }
39268   if( pCur->eState!=CURSOR_VALID || pCur->skipNext!=0 ){
39269     *pHasMoved = 1;
39270   }else{
39271     *pHasMoved = 0;
39272   }
39273   return SQLITE_OK;
39274 }
39275
39276 #ifndef SQLITE_OMIT_AUTOVACUUM
39277 /*
39278 ** Given a page number of a regular database page, return the page
39279 ** number for the pointer-map page that contains the entry for the
39280 ** input page number.
39281 */
39282 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
39283   int nPagesPerMapPage;
39284   Pgno iPtrMap, ret;
39285   assert( sqlite3_mutex_held(pBt->mutex) );
39286   nPagesPerMapPage = (pBt->usableSize/5)+1;
39287   iPtrMap = (pgno-2)/nPagesPerMapPage;
39288   ret = (iPtrMap*nPagesPerMapPage) + 2; 
39289   if( ret==PENDING_BYTE_PAGE(pBt) ){
39290     ret++;
39291   }
39292   return ret;
39293 }
39294
39295 /*
39296 ** Write an entry into the pointer map.
39297 **
39298 ** This routine updates the pointer map entry for page number 'key'
39299 ** so that it maps to type 'eType' and parent page number 'pgno'.
39300 **
39301 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
39302 ** a no-op.  If an error occurs, the appropriate error code is written
39303 ** into *pRC.
39304 */
39305 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
39306   DbPage *pDbPage;  /* The pointer map page */
39307   u8 *pPtrmap;      /* The pointer map data */
39308   Pgno iPtrmap;     /* The pointer map page number */
39309   int offset;       /* Offset in pointer map page */
39310   int rc;           /* Return code from subfunctions */
39311
39312   if( *pRC ) return;
39313
39314   assert( sqlite3_mutex_held(pBt->mutex) );
39315   /* The master-journal page number must never be used as a pointer map page */
39316   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
39317
39318   assert( pBt->autoVacuum );
39319   if( key==0 ){
39320     *pRC = SQLITE_CORRUPT_BKPT;
39321     return;
39322   }
39323   iPtrmap = PTRMAP_PAGENO(pBt, key);
39324   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
39325   if( rc!=SQLITE_OK ){
39326     *pRC = rc;
39327     return;
39328   }
39329   offset = PTRMAP_PTROFFSET(iPtrmap, key);
39330   if( offset<0 ){
39331     *pRC = SQLITE_CORRUPT_BKPT;
39332     goto ptrmap_exit;
39333   }
39334   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
39335
39336   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
39337     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
39338     *pRC= rc = sqlite3PagerWrite(pDbPage);
39339     if( rc==SQLITE_OK ){
39340       pPtrmap[offset] = eType;
39341       put4byte(&pPtrmap[offset+1], parent);
39342     }
39343   }
39344
39345 ptrmap_exit:
39346   sqlite3PagerUnref(pDbPage);
39347 }
39348
39349 /*
39350 ** Read an entry from the pointer map.
39351 **
39352 ** This routine retrieves the pointer map entry for page 'key', writing
39353 ** the type and parent page number to *pEType and *pPgno respectively.
39354 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
39355 */
39356 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
39357   DbPage *pDbPage;   /* The pointer map page */
39358   int iPtrmap;       /* Pointer map page index */
39359   u8 *pPtrmap;       /* Pointer map page data */
39360   int offset;        /* Offset of entry in pointer map */
39361   int rc;
39362
39363   assert( sqlite3_mutex_held(pBt->mutex) );
39364
39365   iPtrmap = PTRMAP_PAGENO(pBt, key);
39366   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
39367   if( rc!=0 ){
39368     return rc;
39369   }
39370   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
39371
39372   offset = PTRMAP_PTROFFSET(iPtrmap, key);
39373   assert( pEType!=0 );
39374   *pEType = pPtrmap[offset];
39375   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
39376
39377   sqlite3PagerUnref(pDbPage);
39378   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
39379   return SQLITE_OK;
39380 }
39381
39382 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
39383   #define ptrmapPut(w,x,y,z,rc)
39384   #define ptrmapGet(w,x,y,z) SQLITE_OK
39385   #define ptrmapPutOvflPtr(x, y, rc)
39386 #endif
39387
39388 /*
39389 ** Given a btree page and a cell index (0 means the first cell on
39390 ** the page, 1 means the second cell, and so forth) return a pointer
39391 ** to the cell content.
39392 **
39393 ** This routine works only for pages that do not contain overflow cells.
39394 */
39395 #define findCell(P,I) \
39396   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aData[(P)->cellOffset+2*(I)])))
39397
39398 /*
39399 ** This a more complex version of findCell() that works for
39400 ** pages that do contain overflow cells.
39401 */
39402 static u8 *findOverflowCell(MemPage *pPage, int iCell){
39403   int i;
39404   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39405   for(i=pPage->nOverflow-1; i>=0; i--){
39406     int k;
39407     struct _OvflCell *pOvfl;
39408     pOvfl = &pPage->aOvfl[i];
39409     k = pOvfl->idx;
39410     if( k<=iCell ){
39411       if( k==iCell ){
39412         return pOvfl->pCell;
39413       }
39414       iCell--;
39415     }
39416   }
39417   return findCell(pPage, iCell);
39418 }
39419
39420 /*
39421 ** Parse a cell content block and fill in the CellInfo structure.  There
39422 ** are two versions of this function.  btreeParseCell() takes a 
39423 ** cell index as the second argument and btreeParseCellPtr() 
39424 ** takes a pointer to the body of the cell as its second argument.
39425 **
39426 ** Within this file, the parseCell() macro can be called instead of
39427 ** btreeParseCellPtr(). Using some compilers, this will be faster.
39428 */
39429 static void btreeParseCellPtr(
39430   MemPage *pPage,         /* Page containing the cell */
39431   u8 *pCell,              /* Pointer to the cell text. */
39432   CellInfo *pInfo         /* Fill in this structure */
39433 ){
39434   u16 n;                  /* Number bytes in cell content header */
39435   u32 nPayload;           /* Number of bytes of cell payload */
39436
39437   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39438
39439   pInfo->pCell = pCell;
39440   assert( pPage->leaf==0 || pPage->leaf==1 );
39441   n = pPage->childPtrSize;
39442   assert( n==4-4*pPage->leaf );
39443   if( pPage->intKey ){
39444     if( pPage->hasData ){
39445       n += getVarint32(&pCell[n], nPayload);
39446     }else{
39447       nPayload = 0;
39448     }
39449     n += getVarint(&pCell[n], (u64*)&pInfo->nKey);
39450     pInfo->nData = nPayload;
39451   }else{
39452     pInfo->nData = 0;
39453     n += getVarint32(&pCell[n], nPayload);
39454     pInfo->nKey = nPayload;
39455   }
39456   pInfo->nPayload = nPayload;
39457   pInfo->nHeader = n;
39458   testcase( nPayload==pPage->maxLocal );
39459   testcase( nPayload==pPage->maxLocal+1 );
39460   if( likely(nPayload<=pPage->maxLocal) ){
39461     /* This is the (easy) common case where the entire payload fits
39462     ** on the local page.  No overflow is required.
39463     */
39464     int nSize;          /* Total size of cell content in bytes */
39465     nSize = nPayload + n;
39466     pInfo->nLocal = (u16)nPayload;
39467     pInfo->iOverflow = 0;
39468     if( (nSize & ~3)==0 ){
39469       nSize = 4;        /* Minimum cell size is 4 */
39470     }
39471     pInfo->nSize = (u16)nSize;
39472   }else{
39473     /* If the payload will not fit completely on the local page, we have
39474     ** to decide how much to store locally and how much to spill onto
39475     ** overflow pages.  The strategy is to minimize the amount of unused
39476     ** space on overflow pages while keeping the amount of local storage
39477     ** in between minLocal and maxLocal.
39478     **
39479     ** Warning:  changing the way overflow payload is distributed in any
39480     ** way will result in an incompatible file format.
39481     */
39482     int minLocal;  /* Minimum amount of payload held locally */
39483     int maxLocal;  /* Maximum amount of payload held locally */
39484     int surplus;   /* Overflow payload available for local storage */
39485
39486     minLocal = pPage->minLocal;
39487     maxLocal = pPage->maxLocal;
39488     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
39489     testcase( surplus==maxLocal );
39490     testcase( surplus==maxLocal+1 );
39491     if( surplus <= maxLocal ){
39492       pInfo->nLocal = (u16)surplus;
39493     }else{
39494       pInfo->nLocal = (u16)minLocal;
39495     }
39496     pInfo->iOverflow = (u16)(pInfo->nLocal + n);
39497     pInfo->nSize = pInfo->iOverflow + 4;
39498   }
39499 }
39500 #define parseCell(pPage, iCell, pInfo) \
39501   btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
39502 static void btreeParseCell(
39503   MemPage *pPage,         /* Page containing the cell */
39504   int iCell,              /* The cell index.  First cell is 0 */
39505   CellInfo *pInfo         /* Fill in this structure */
39506 ){
39507   parseCell(pPage, iCell, pInfo);
39508 }
39509
39510 /*
39511 ** Compute the total number of bytes that a Cell needs in the cell
39512 ** data area of the btree-page.  The return number includes the cell
39513 ** data header and the local payload, but not any overflow page or
39514 ** the space used by the cell pointer.
39515 */
39516 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
39517   u8 *pIter = &pCell[pPage->childPtrSize];
39518   u32 nSize;
39519
39520 #ifdef SQLITE_DEBUG
39521   /* The value returned by this function should always be the same as
39522   ** the (CellInfo.nSize) value found by doing a full parse of the
39523   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
39524   ** this function verifies that this invariant is not violated. */
39525   CellInfo debuginfo;
39526   btreeParseCellPtr(pPage, pCell, &debuginfo);
39527 #endif
39528
39529   if( pPage->intKey ){
39530     u8 *pEnd;
39531     if( pPage->hasData ){
39532       pIter += getVarint32(pIter, nSize);
39533     }else{
39534       nSize = 0;
39535     }
39536
39537     /* pIter now points at the 64-bit integer key value, a variable length 
39538     ** integer. The following block moves pIter to point at the first byte
39539     ** past the end of the key value. */
39540     pEnd = &pIter[9];
39541     while( (*pIter++)&0x80 && pIter<pEnd );
39542   }else{
39543     pIter += getVarint32(pIter, nSize);
39544   }
39545
39546   testcase( nSize==pPage->maxLocal );
39547   testcase( nSize==pPage->maxLocal+1 );
39548   if( nSize>pPage->maxLocal ){
39549     int minLocal = pPage->minLocal;
39550     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
39551     testcase( nSize==pPage->maxLocal );
39552     testcase( nSize==pPage->maxLocal+1 );
39553     if( nSize>pPage->maxLocal ){
39554       nSize = minLocal;
39555     }
39556     nSize += 4;
39557   }
39558   nSize += (u32)(pIter - pCell);
39559
39560   /* The minimum size of any cell is 4 bytes. */
39561   if( nSize<4 ){
39562     nSize = 4;
39563   }
39564
39565   assert( nSize==debuginfo.nSize );
39566   return (u16)nSize;
39567 }
39568
39569 #ifdef SQLITE_DEBUG
39570 /* This variation on cellSizePtr() is used inside of assert() statements
39571 ** only. */
39572 static u16 cellSize(MemPage *pPage, int iCell){
39573   return cellSizePtr(pPage, findCell(pPage, iCell));
39574 }
39575 #endif
39576
39577 #ifndef SQLITE_OMIT_AUTOVACUUM
39578 /*
39579 ** If the cell pCell, part of page pPage contains a pointer
39580 ** to an overflow page, insert an entry into the pointer-map
39581 ** for the overflow page.
39582 */
39583 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
39584   CellInfo info;
39585   if( *pRC ) return;
39586   assert( pCell!=0 );
39587   btreeParseCellPtr(pPage, pCell, &info);
39588   assert( (info.nData+(pPage->intKey?0:info.nKey))==info.nPayload );
39589   if( info.iOverflow ){
39590     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
39591     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
39592   }
39593 }
39594 #endif
39595
39596
39597 /*
39598 ** Defragment the page given.  All Cells are moved to the
39599 ** end of the page and all free space is collected into one
39600 ** big FreeBlk that occurs in between the header and cell
39601 ** pointer array and the cell content area.
39602 */
39603 static int defragmentPage(MemPage *pPage){
39604   int i;                     /* Loop counter */
39605   int pc;                    /* Address of a i-th cell */
39606   int hdr;                   /* Offset to the page header */
39607   int size;                  /* Size of a cell */
39608   int usableSize;            /* Number of usable bytes on a page */
39609   int cellOffset;            /* Offset to the cell pointer array */
39610   int cbrk;                  /* Offset to the cell content area */
39611   int nCell;                 /* Number of cells on the page */
39612   unsigned char *data;       /* The page data */
39613   unsigned char *temp;       /* Temp area for cell content */
39614   int iCellFirst;            /* First allowable cell index */
39615   int iCellLast;             /* Last possible cell index */
39616
39617
39618   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
39619   assert( pPage->pBt!=0 );
39620   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
39621   assert( pPage->nOverflow==0 );
39622   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39623   temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
39624   data = pPage->aData;
39625   hdr = pPage->hdrOffset;
39626   cellOffset = pPage->cellOffset;
39627   nCell = pPage->nCell;
39628   assert( nCell==get2byte(&data[hdr+3]) );
39629   usableSize = pPage->pBt->usableSize;
39630   cbrk = get2byte(&data[hdr+5]);
39631   memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
39632   cbrk = usableSize;
39633   iCellFirst = cellOffset + 2*nCell;
39634   iCellLast = usableSize - 4;
39635   for(i=0; i<nCell; i++){
39636     u8 *pAddr;     /* The i-th cell pointer */
39637     pAddr = &data[cellOffset + i*2];
39638     pc = get2byte(pAddr);
39639     testcase( pc==iCellFirst );
39640     testcase( pc==iCellLast );
39641 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
39642     /* These conditions have already been verified in btreeInitPage()
39643     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined 
39644     */
39645     if( pc<iCellFirst || pc>iCellLast ){
39646       return SQLITE_CORRUPT_BKPT;
39647     }
39648 #endif
39649     assert( pc>=iCellFirst && pc<=iCellLast );
39650     size = cellSizePtr(pPage, &temp[pc]);
39651     cbrk -= size;
39652 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
39653     if( cbrk<iCellFirst ){
39654       return SQLITE_CORRUPT_BKPT;
39655     }
39656 #else
39657     if( cbrk<iCellFirst || pc+size>usableSize ){
39658       return SQLITE_CORRUPT_BKPT;
39659     }
39660 #endif
39661     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
39662     testcase( cbrk+size==usableSize );
39663     testcase( pc+size==usableSize );
39664     memcpy(&data[cbrk], &temp[pc], size);
39665     put2byte(pAddr, cbrk);
39666   }
39667   assert( cbrk>=iCellFirst );
39668   put2byte(&data[hdr+5], cbrk);
39669   data[hdr+1] = 0;
39670   data[hdr+2] = 0;
39671   data[hdr+7] = 0;
39672   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
39673   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
39674   if( cbrk-iCellFirst!=pPage->nFree ){
39675     return SQLITE_CORRUPT_BKPT;
39676   }
39677   return SQLITE_OK;
39678 }
39679
39680 /*
39681 ** Allocate nByte bytes of space from within the B-Tree page passed
39682 ** as the first argument. Write into *pIdx the index into pPage->aData[]
39683 ** of the first byte of allocated space. Return either SQLITE_OK or
39684 ** an error code (usually SQLITE_CORRUPT).
39685 **
39686 ** The caller guarantees that there is sufficient space to make the
39687 ** allocation.  This routine might need to defragment in order to bring
39688 ** all the space together, however.  This routine will avoid using
39689 ** the first two bytes past the cell pointer area since presumably this
39690 ** allocation is being made in order to insert a new cell, so we will
39691 ** also end up needing a new cell pointer.
39692 */
39693 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
39694   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
39695   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
39696   int nFrag;                           /* Number of fragmented bytes on pPage */
39697   int top;                             /* First byte of cell content area */
39698   int gap;        /* First byte of gap between cell pointers and cell content */
39699   int rc;         /* Integer return code */
39700   int usableSize; /* Usable size of the page */
39701   
39702   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
39703   assert( pPage->pBt );
39704   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39705   assert( nByte>=0 );  /* Minimum cell size is 4 */
39706   assert( pPage->nFree>=nByte );
39707   assert( pPage->nOverflow==0 );
39708   usableSize = pPage->pBt->usableSize;
39709   assert( nByte < usableSize-8 );
39710
39711   nFrag = data[hdr+7];
39712   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
39713   gap = pPage->cellOffset + 2*pPage->nCell;
39714   top = get2byte(&data[hdr+5]);
39715   if( gap>top ) return SQLITE_CORRUPT_BKPT;
39716   testcase( gap+2==top );
39717   testcase( gap+1==top );
39718   testcase( gap==top );
39719
39720   if( nFrag>=60 ){
39721     /* Always defragment highly fragmented pages */
39722     rc = defragmentPage(pPage);
39723     if( rc ) return rc;
39724     top = get2byte(&data[hdr+5]);
39725   }else if( gap+2<=top ){
39726     /* Search the freelist looking for a free slot big enough to satisfy 
39727     ** the request. The allocation is made from the first free slot in 
39728     ** the list that is large enough to accomadate it.
39729     */
39730     int pc, addr;
39731     for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
39732       int size;            /* Size of the free slot */
39733       if( pc>usableSize-4 || pc<addr+4 ){
39734         return SQLITE_CORRUPT_BKPT;
39735       }
39736       size = get2byte(&data[pc+2]);
39737       if( size>=nByte ){
39738         int x = size - nByte;
39739         testcase( x==4 );
39740         testcase( x==3 );
39741         if( x<4 ){
39742           /* Remove the slot from the free-list. Update the number of
39743           ** fragmented bytes within the page. */
39744           memcpy(&data[addr], &data[pc], 2);
39745           data[hdr+7] = (u8)(nFrag + x);
39746         }else if( size+pc > usableSize ){
39747           return SQLITE_CORRUPT_BKPT;
39748         }else{
39749           /* The slot remains on the free-list. Reduce its size to account
39750           ** for the portion used by the new allocation. */
39751           put2byte(&data[pc+2], x);
39752         }
39753         *pIdx = pc + x;
39754         return SQLITE_OK;
39755       }
39756     }
39757   }
39758
39759   /* Check to make sure there is enough space in the gap to satisfy
39760   ** the allocation.  If not, defragment.
39761   */
39762   testcase( gap+2+nByte==top );
39763   if( gap+2+nByte>top ){
39764     rc = defragmentPage(pPage);
39765     if( rc ) return rc;
39766     top = get2byte(&data[hdr+5]);
39767     assert( gap+nByte<=top );
39768   }
39769
39770
39771   /* Allocate memory from the gap in between the cell pointer array
39772   ** and the cell content area.  The btreeInitPage() call has already
39773   ** validated the freelist.  Given that the freelist is valid, there
39774   ** is no way that the allocation can extend off the end of the page.
39775   ** The assert() below verifies the previous sentence.
39776   */
39777   top -= nByte;
39778   put2byte(&data[hdr+5], top);
39779   assert( top+nByte <= pPage->pBt->usableSize );
39780   *pIdx = top;
39781   return SQLITE_OK;
39782 }
39783
39784 /*
39785 ** Return a section of the pPage->aData to the freelist.
39786 ** The first byte of the new free block is pPage->aDisk[start]
39787 ** and the size of the block is "size" bytes.
39788 **
39789 ** Most of the effort here is involved in coalesing adjacent
39790 ** free blocks into a single big free block.
39791 */
39792 static int freeSpace(MemPage *pPage, int start, int size){
39793   int addr, pbegin, hdr;
39794   int iLast;                        /* Largest possible freeblock offset */
39795   unsigned char *data = pPage->aData;
39796
39797   assert( pPage->pBt!=0 );
39798   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
39799   assert( start>=pPage->hdrOffset+6+pPage->childPtrSize );
39800   assert( (start + size)<=pPage->pBt->usableSize );
39801   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39802   assert( size>=0 );   /* Minimum cell size is 4 */
39803
39804   if( pPage->pBt->secureDelete ){
39805     /* Overwrite deleted information with zeros when the secure_delete
39806     ** option is enabled */
39807     memset(&data[start], 0, size);
39808   }
39809
39810   /* Add the space back into the linked list of freeblocks.  Note that
39811   ** even though the freeblock list was checked by btreeInitPage(),
39812   ** btreeInitPage() did not detect overlapping cells or
39813   ** freeblocks that overlapped cells.   Nor does it detect when the
39814   ** cell content area exceeds the value in the page header.  If these
39815   ** situations arise, then subsequent insert operations might corrupt
39816   ** the freelist.  So we do need to check for corruption while scanning
39817   ** the freelist.
39818   */
39819   hdr = pPage->hdrOffset;
39820   addr = hdr + 1;
39821   iLast = pPage->pBt->usableSize - 4;
39822   assert( start<=iLast );
39823   while( (pbegin = get2byte(&data[addr]))<start && pbegin>0 ){
39824     if( pbegin<addr+4 ){
39825       return SQLITE_CORRUPT_BKPT;
39826     }
39827     addr = pbegin;
39828   }
39829   if( pbegin>iLast ){
39830     return SQLITE_CORRUPT_BKPT;
39831   }
39832   assert( pbegin>addr || pbegin==0 );
39833   put2byte(&data[addr], start);
39834   put2byte(&data[start], pbegin);
39835   put2byte(&data[start+2], size);
39836   pPage->nFree = pPage->nFree + (u16)size;
39837
39838   /* Coalesce adjacent free blocks */
39839   addr = hdr + 1;
39840   while( (pbegin = get2byte(&data[addr]))>0 ){
39841     int pnext, psize, x;
39842     assert( pbegin>addr );
39843     assert( pbegin<=pPage->pBt->usableSize-4 );
39844     pnext = get2byte(&data[pbegin]);
39845     psize = get2byte(&data[pbegin+2]);
39846     if( pbegin + psize + 3 >= pnext && pnext>0 ){
39847       int frag = pnext - (pbegin+psize);
39848       if( (frag<0) || (frag>(int)data[hdr+7]) ){
39849         return SQLITE_CORRUPT_BKPT;
39850       }
39851       data[hdr+7] -= (u8)frag;
39852       x = get2byte(&data[pnext]);
39853       put2byte(&data[pbegin], x);
39854       x = pnext + get2byte(&data[pnext+2]) - pbegin;
39855       put2byte(&data[pbegin+2], x);
39856     }else{
39857       addr = pbegin;
39858     }
39859   }
39860
39861   /* If the cell content area begins with a freeblock, remove it. */
39862   if( data[hdr+1]==data[hdr+5] && data[hdr+2]==data[hdr+6] ){
39863     int top;
39864     pbegin = get2byte(&data[hdr+1]);
39865     memcpy(&data[hdr+1], &data[pbegin], 2);
39866     top = get2byte(&data[hdr+5]) + get2byte(&data[pbegin+2]);
39867     put2byte(&data[hdr+5], top);
39868   }
39869   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
39870   return SQLITE_OK;
39871 }
39872
39873 /*
39874 ** Decode the flags byte (the first byte of the header) for a page
39875 ** and initialize fields of the MemPage structure accordingly.
39876 **
39877 ** Only the following combinations are supported.  Anything different
39878 ** indicates a corrupt database files:
39879 **
39880 **         PTF_ZERODATA
39881 **         PTF_ZERODATA | PTF_LEAF
39882 **         PTF_LEAFDATA | PTF_INTKEY
39883 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
39884 */
39885 static int decodeFlags(MemPage *pPage, int flagByte){
39886   BtShared *pBt;     /* A copy of pPage->pBt */
39887
39888   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
39889   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39890   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
39891   flagByte &= ~PTF_LEAF;
39892   pPage->childPtrSize = 4-4*pPage->leaf;
39893   pBt = pPage->pBt;
39894   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
39895     pPage->intKey = 1;
39896     pPage->hasData = pPage->leaf;
39897     pPage->maxLocal = pBt->maxLeaf;
39898     pPage->minLocal = pBt->minLeaf;
39899   }else if( flagByte==PTF_ZERODATA ){
39900     pPage->intKey = 0;
39901     pPage->hasData = 0;
39902     pPage->maxLocal = pBt->maxLocal;
39903     pPage->minLocal = pBt->minLocal;
39904   }else{
39905     return SQLITE_CORRUPT_BKPT;
39906   }
39907   return SQLITE_OK;
39908 }
39909
39910 /*
39911 ** Initialize the auxiliary information for a disk block.
39912 **
39913 ** Return SQLITE_OK on success.  If we see that the page does
39914 ** not contain a well-formed database page, then return 
39915 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
39916 ** guarantee that the page is well-formed.  It only shows that
39917 ** we failed to detect any corruption.
39918 */
39919 static int btreeInitPage(MemPage *pPage){
39920
39921   assert( pPage->pBt!=0 );
39922   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
39923   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
39924   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
39925   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
39926
39927   if( !pPage->isInit ){
39928     u16 pc;            /* Address of a freeblock within pPage->aData[] */
39929     u8 hdr;            /* Offset to beginning of page header */
39930     u8 *data;          /* Equal to pPage->aData */
39931     BtShared *pBt;        /* The main btree structure */
39932     u16 usableSize;    /* Amount of usable space on each page */
39933     u16 cellOffset;    /* Offset from start of page to first cell pointer */
39934     u16 nFree;         /* Number of unused bytes on the page */
39935     u16 top;           /* First byte of the cell content area */
39936     int iCellFirst;    /* First allowable cell or freeblock offset */
39937     int iCellLast;     /* Last possible cell or freeblock offset */
39938
39939     pBt = pPage->pBt;
39940
39941     hdr = pPage->hdrOffset;
39942     data = pPage->aData;
39943     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
39944     assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
39945     pPage->maskPage = pBt->pageSize - 1;
39946     pPage->nOverflow = 0;
39947     usableSize = pBt->usableSize;
39948     pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
39949     top = get2byte(&data[hdr+5]);
39950     pPage->nCell = get2byte(&data[hdr+3]);
39951     if( pPage->nCell>MX_CELL(pBt) ){
39952       /* To many cells for a single page.  The page must be corrupt */
39953       return SQLITE_CORRUPT_BKPT;
39954     }
39955     testcase( pPage->nCell==MX_CELL(pBt) );
39956
39957     /* A malformed database page might cause us to read past the end
39958     ** of page when parsing a cell.  
39959     **
39960     ** The following block of code checks early to see if a cell extends
39961     ** past the end of a page boundary and causes SQLITE_CORRUPT to be 
39962     ** returned if it does.
39963     */
39964     iCellFirst = cellOffset + 2*pPage->nCell;
39965     iCellLast = usableSize - 4;
39966 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
39967     {
39968       int i;            /* Index into the cell pointer array */
39969       int sz;           /* Size of a cell */
39970
39971       if( !pPage->leaf ) iCellLast--;
39972       for(i=0; i<pPage->nCell; i++){
39973         pc = get2byte(&data[cellOffset+i*2]);
39974         testcase( pc==iCellFirst );
39975         testcase( pc==iCellLast );
39976         if( pc<iCellFirst || pc>iCellLast ){
39977           return SQLITE_CORRUPT_BKPT;
39978         }
39979         sz = cellSizePtr(pPage, &data[pc]);
39980         testcase( pc+sz==usableSize );
39981         if( pc+sz>usableSize ){
39982           return SQLITE_CORRUPT_BKPT;
39983         }
39984       }
39985       if( !pPage->leaf ) iCellLast++;
39986     }  
39987 #endif
39988
39989     /* Compute the total free space on the page */
39990     pc = get2byte(&data[hdr+1]);
39991     nFree = data[hdr+7] + top;
39992     while( pc>0 ){
39993       u16 next, size;
39994       if( pc<iCellFirst || pc>iCellLast ){
39995         /* Start of free block is off the page */
39996         return SQLITE_CORRUPT_BKPT; 
39997       }
39998       next = get2byte(&data[pc]);
39999       size = get2byte(&data[pc+2]);
40000       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
40001         /* Free blocks must be in ascending order. And the last byte of
40002         ** the free-block must lie on the database page.  */
40003         return SQLITE_CORRUPT_BKPT; 
40004       }
40005       nFree = nFree + size;
40006       pc = next;
40007     }
40008
40009     /* At this point, nFree contains the sum of the offset to the start
40010     ** of the cell-content area plus the number of free bytes within
40011     ** the cell-content area. If this is greater than the usable-size
40012     ** of the page, then the page must be corrupted. This check also
40013     ** serves to verify that the offset to the start of the cell-content
40014     ** area, according to the page header, lies within the page.
40015     */
40016     if( nFree>usableSize ){
40017       return SQLITE_CORRUPT_BKPT; 
40018     }
40019     pPage->nFree = (u16)(nFree - iCellFirst);
40020     pPage->isInit = 1;
40021   }
40022   return SQLITE_OK;
40023 }
40024
40025 /*
40026 ** Set up a raw page so that it looks like a database page holding
40027 ** no entries.
40028 */
40029 static void zeroPage(MemPage *pPage, int flags){
40030   unsigned char *data = pPage->aData;
40031   BtShared *pBt = pPage->pBt;
40032   u8 hdr = pPage->hdrOffset;
40033   u16 first;
40034
40035   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
40036   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
40037   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
40038   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
40039   assert( sqlite3_mutex_held(pBt->mutex) );
40040   if( pBt->secureDelete ){
40041     memset(&data[hdr], 0, pBt->usableSize - hdr);
40042   }
40043   data[hdr] = (char)flags;
40044   first = hdr + 8 + 4*((flags&PTF_LEAF)==0 ?1:0);
40045   memset(&data[hdr+1], 0, 4);
40046   data[hdr+7] = 0;
40047   put2byte(&data[hdr+5], pBt->usableSize);
40048   pPage->nFree = pBt->usableSize - first;
40049   decodeFlags(pPage, flags);
40050   pPage->hdrOffset = hdr;
40051   pPage->cellOffset = first;
40052   pPage->nOverflow = 0;
40053   assert( pBt->pageSize>=512 && pBt->pageSize<=32768 );
40054   pPage->maskPage = pBt->pageSize - 1;
40055   pPage->nCell = 0;
40056   pPage->isInit = 1;
40057 }
40058
40059
40060 /*
40061 ** Convert a DbPage obtained from the pager into a MemPage used by
40062 ** the btree layer.
40063 */
40064 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
40065   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
40066   pPage->aData = sqlite3PagerGetData(pDbPage);
40067   pPage->pDbPage = pDbPage;
40068   pPage->pBt = pBt;
40069   pPage->pgno = pgno;
40070   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
40071   return pPage; 
40072 }
40073
40074 /*
40075 ** Get a page from the pager.  Initialize the MemPage.pBt and
40076 ** MemPage.aData elements if needed.
40077 **
40078 ** If the noContent flag is set, it means that we do not care about
40079 ** the content of the page at this time.  So do not go to the disk
40080 ** to fetch the content.  Just fill in the content with zeros for now.
40081 ** If in the future we call sqlite3PagerWrite() on this page, that
40082 ** means we have started to be concerned about content and the disk
40083 ** read should occur at that point.
40084 */
40085 static int btreeGetPage(
40086   BtShared *pBt,       /* The btree */
40087   Pgno pgno,           /* Number of the page to fetch */
40088   MemPage **ppPage,    /* Return the page in this parameter */
40089   int noContent        /* Do not load page content if true */
40090 ){
40091   int rc;
40092   DbPage *pDbPage;
40093
40094   assert( sqlite3_mutex_held(pBt->mutex) );
40095   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, noContent);
40096   if( rc ) return rc;
40097   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
40098   return SQLITE_OK;
40099 }
40100
40101 /*
40102 ** Retrieve a page from the pager cache. If the requested page is not
40103 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
40104 ** MemPage.aData elements if needed.
40105 */
40106 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
40107   DbPage *pDbPage;
40108   assert( sqlite3_mutex_held(pBt->mutex) );
40109   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
40110   if( pDbPage ){
40111     return btreePageFromDbPage(pDbPage, pgno, pBt);
40112   }
40113   return 0;
40114 }
40115
40116 /*
40117 ** Return the size of the database file in pages. If there is any kind of
40118 ** error, return ((unsigned int)-1).
40119 */
40120 static Pgno pagerPagecount(BtShared *pBt){
40121   int nPage = -1;
40122   int rc;
40123   assert( pBt->pPage1 );
40124   rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
40125   assert( rc==SQLITE_OK || nPage==-1 );
40126   return (Pgno)nPage;
40127 }
40128
40129 /*
40130 ** Get a page from the pager and initialize it.  This routine is just a
40131 ** convenience wrapper around separate calls to btreeGetPage() and 
40132 ** btreeInitPage().
40133 **
40134 ** If an error occurs, then the value *ppPage is set to is undefined. It
40135 ** may remain unchanged, or it may be set to an invalid value.
40136 */
40137 static int getAndInitPage(
40138   BtShared *pBt,          /* The database file */
40139   Pgno pgno,           /* Number of the page to get */
40140   MemPage **ppPage     /* Write the page pointer here */
40141 ){
40142   int rc;
40143   TESTONLY( Pgno iLastPg = pagerPagecount(pBt); )
40144   assert( sqlite3_mutex_held(pBt->mutex) );
40145
40146   rc = btreeGetPage(pBt, pgno, ppPage, 0);
40147   if( rc==SQLITE_OK ){
40148     rc = btreeInitPage(*ppPage);
40149     if( rc!=SQLITE_OK ){
40150       releasePage(*ppPage);
40151     }
40152   }
40153
40154   /* If the requested page number was either 0 or greater than the page
40155   ** number of the last page in the database, this function should return
40156   ** SQLITE_CORRUPT or some other error (i.e. SQLITE_FULL). Check that this
40157   ** is the case.  */
40158   assert( (pgno>0 && pgno<=iLastPg) || rc!=SQLITE_OK );
40159   testcase( pgno==0 );
40160   testcase( pgno==iLastPg );
40161
40162   return rc;
40163 }
40164
40165 /*
40166 ** Release a MemPage.  This should be called once for each prior
40167 ** call to btreeGetPage.
40168 */
40169 static void releasePage(MemPage *pPage){
40170   if( pPage ){
40171     assert( pPage->aData );
40172     assert( pPage->pBt );
40173     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
40174     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
40175     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
40176     sqlite3PagerUnref(pPage->pDbPage);
40177   }
40178 }
40179
40180 /*
40181 ** During a rollback, when the pager reloads information into the cache
40182 ** so that the cache is restored to its original state at the start of
40183 ** the transaction, for each page restored this routine is called.
40184 **
40185 ** This routine needs to reset the extra data section at the end of the
40186 ** page to agree with the restored data.
40187 */
40188 static void pageReinit(DbPage *pData){
40189   MemPage *pPage;
40190   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
40191   assert( sqlite3PagerPageRefcount(pData)>0 );
40192   if( pPage->isInit ){
40193     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
40194     pPage->isInit = 0;
40195     if( sqlite3PagerPageRefcount(pData)>1 ){
40196       /* pPage might not be a btree page;  it might be an overflow page
40197       ** or ptrmap page or a free page.  In those cases, the following
40198       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
40199       ** But no harm is done by this.  And it is very important that
40200       ** btreeInitPage() be called on every btree page so we make
40201       ** the call for every page that comes in for re-initing. */
40202       btreeInitPage(pPage);
40203     }
40204   }
40205 }
40206
40207 /*
40208 ** Invoke the busy handler for a btree.
40209 */
40210 static int btreeInvokeBusyHandler(void *pArg){
40211   BtShared *pBt = (BtShared*)pArg;
40212   assert( pBt->db );
40213   assert( sqlite3_mutex_held(pBt->db->mutex) );
40214   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
40215 }
40216
40217 /*
40218 ** Open a database file.
40219 ** 
40220 ** zFilename is the name of the database file.  If zFilename is NULL
40221 ** a new database with a random name is created.  This randomly named
40222 ** database file will be deleted when sqlite3BtreeClose() is called.
40223 ** If zFilename is ":memory:" then an in-memory database is created
40224 ** that is automatically destroyed when it is closed.
40225 **
40226 ** If the database is already opened in the same database connection
40227 ** and we are in shared cache mode, then the open will fail with an
40228 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
40229 ** objects in the same database connection since doing so will lead
40230 ** to problems with locking.
40231 */
40232 SQLITE_PRIVATE int sqlite3BtreeOpen(
40233   const char *zFilename,  /* Name of the file containing the BTree database */
40234   sqlite3 *db,            /* Associated database handle */
40235   Btree **ppBtree,        /* Pointer to new Btree object written here */
40236   int flags,              /* Options */
40237   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
40238 ){
40239   sqlite3_vfs *pVfs;             /* The VFS to use for this btree */
40240   BtShared *pBt = 0;             /* Shared part of btree structure */
40241   Btree *p;                      /* Handle to return */
40242   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
40243   int rc = SQLITE_OK;            /* Result code from this function */
40244   u8 nReserve;                   /* Byte of unused space on each page */
40245   unsigned char zDbHeader[100];  /* Database header content */
40246
40247   /* Set the variable isMemdb to true for an in-memory database, or 
40248   ** false for a file-based database. This symbol is only required if
40249   ** either of the shared-data or autovacuum features are compiled 
40250   ** into the library.
40251   */
40252 #if !defined(SQLITE_OMIT_SHARED_CACHE) || !defined(SQLITE_OMIT_AUTOVACUUM)
40253   #ifdef SQLITE_OMIT_MEMORYDB
40254     const int isMemdb = 0;
40255   #else
40256     const int isMemdb = zFilename && !strcmp(zFilename, ":memory:");
40257   #endif
40258 #endif
40259
40260   assert( db!=0 );
40261   assert( sqlite3_mutex_held(db->mutex) );
40262
40263   pVfs = db->pVfs;
40264   p = sqlite3MallocZero(sizeof(Btree));
40265   if( !p ){
40266     return SQLITE_NOMEM;
40267   }
40268   p->inTrans = TRANS_NONE;
40269   p->db = db;
40270 #ifndef SQLITE_OMIT_SHARED_CACHE
40271   p->lock.pBtree = p;
40272   p->lock.iTable = 1;
40273 #endif
40274
40275 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
40276   /*
40277   ** If this Btree is a candidate for shared cache, try to find an
40278   ** existing BtShared object that we can share with
40279   */
40280   if( isMemdb==0 && zFilename && zFilename[0] ){
40281     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
40282       int nFullPathname = pVfs->mxPathname+1;
40283       char *zFullPathname = sqlite3Malloc(nFullPathname);
40284       sqlite3_mutex *mutexShared;
40285       p->sharable = 1;
40286       if( !zFullPathname ){
40287         sqlite3_free(p);
40288         return SQLITE_NOMEM;
40289       }
40290       sqlite3OsFullPathname(pVfs, zFilename, nFullPathname, zFullPathname);
40291       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
40292       sqlite3_mutex_enter(mutexOpen);
40293       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
40294       sqlite3_mutex_enter(mutexShared);
40295       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
40296         assert( pBt->nRef>0 );
40297         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager))
40298                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
40299           int iDb;
40300           for(iDb=db->nDb-1; iDb>=0; iDb--){
40301             Btree *pExisting = db->aDb[iDb].pBt;
40302             if( pExisting && pExisting->pBt==pBt ){
40303               sqlite3_mutex_leave(mutexShared);
40304               sqlite3_mutex_leave(mutexOpen);
40305               sqlite3_free(zFullPathname);
40306               sqlite3_free(p);
40307               return SQLITE_CONSTRAINT;
40308             }
40309           }
40310           p->pBt = pBt;
40311           pBt->nRef++;
40312           break;
40313         }
40314       }
40315       sqlite3_mutex_leave(mutexShared);
40316       sqlite3_free(zFullPathname);
40317     }
40318 #ifdef SQLITE_DEBUG
40319     else{
40320       /* In debug mode, we mark all persistent databases as sharable
40321       ** even when they are not.  This exercises the locking code and
40322       ** gives more opportunity for asserts(sqlite3_mutex_held())
40323       ** statements to find locking problems.
40324       */
40325       p->sharable = 1;
40326     }
40327 #endif
40328   }
40329 #endif
40330   if( pBt==0 ){
40331     /*
40332     ** The following asserts make sure that structures used by the btree are
40333     ** the right size.  This is to guard against size changes that result
40334     ** when compiling on a different architecture.
40335     */
40336     assert( sizeof(i64)==8 || sizeof(i64)==4 );
40337     assert( sizeof(u64)==8 || sizeof(u64)==4 );
40338     assert( sizeof(u32)==4 );
40339     assert( sizeof(u16)==2 );
40340     assert( sizeof(Pgno)==4 );
40341   
40342     pBt = sqlite3MallocZero( sizeof(*pBt) );
40343     if( pBt==0 ){
40344       rc = SQLITE_NOMEM;
40345       goto btree_open_out;
40346     }
40347     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
40348                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
40349     if( rc==SQLITE_OK ){
40350       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
40351     }
40352     if( rc!=SQLITE_OK ){
40353       goto btree_open_out;
40354     }
40355     pBt->db = db;
40356     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
40357     p->pBt = pBt;
40358   
40359     pBt->pCursor = 0;
40360     pBt->pPage1 = 0;
40361     pBt->readOnly = sqlite3PagerIsreadonly(pBt->pPager);
40362 #ifdef SQLITE_SECURE_DELETE
40363     pBt->secureDelete = 1;
40364 #endif
40365     pBt->pageSize = get2byte(&zDbHeader[16]);
40366     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
40367          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
40368       pBt->pageSize = 0;
40369 #ifndef SQLITE_OMIT_AUTOVACUUM
40370       /* If the magic name ":memory:" will create an in-memory database, then
40371       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
40372       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
40373       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
40374       ** regular file-name. In this case the auto-vacuum applies as per normal.
40375       */
40376       if( zFilename && !isMemdb ){
40377         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
40378         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
40379       }
40380 #endif
40381       nReserve = 0;
40382     }else{
40383       nReserve = zDbHeader[20];
40384       pBt->pageSizeFixed = 1;
40385 #ifndef SQLITE_OMIT_AUTOVACUUM
40386       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
40387       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
40388 #endif
40389     }
40390     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
40391     if( rc ) goto btree_open_out;
40392     pBt->usableSize = pBt->pageSize - nReserve;
40393     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
40394    
40395 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
40396     /* Add the new BtShared object to the linked list sharable BtShareds.
40397     */
40398     if( p->sharable ){
40399       sqlite3_mutex *mutexShared;
40400       pBt->nRef = 1;
40401       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
40402       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
40403         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
40404         if( pBt->mutex==0 ){
40405           rc = SQLITE_NOMEM;
40406           db->mallocFailed = 0;
40407           goto btree_open_out;
40408         }
40409       }
40410       sqlite3_mutex_enter(mutexShared);
40411       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
40412       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
40413       sqlite3_mutex_leave(mutexShared);
40414     }
40415 #endif
40416   }
40417
40418 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
40419   /* If the new Btree uses a sharable pBtShared, then link the new
40420   ** Btree into the list of all sharable Btrees for the same connection.
40421   ** The list is kept in ascending order by pBt address.
40422   */
40423   if( p->sharable ){
40424     int i;
40425     Btree *pSib;
40426     for(i=0; i<db->nDb; i++){
40427       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
40428         while( pSib->pPrev ){ pSib = pSib->pPrev; }
40429         if( p->pBt<pSib->pBt ){
40430           p->pNext = pSib;
40431           p->pPrev = 0;
40432           pSib->pPrev = p;
40433         }else{
40434           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
40435             pSib = pSib->pNext;
40436           }
40437           p->pNext = pSib->pNext;
40438           p->pPrev = pSib;
40439           if( p->pNext ){
40440             p->pNext->pPrev = p;
40441           }
40442           pSib->pNext = p;
40443         }
40444         break;
40445       }
40446     }
40447   }
40448 #endif
40449   *ppBtree = p;
40450
40451 btree_open_out:
40452   if( rc!=SQLITE_OK ){
40453     if( pBt && pBt->pPager ){
40454       sqlite3PagerClose(pBt->pPager);
40455     }
40456     sqlite3_free(pBt);
40457     sqlite3_free(p);
40458     *ppBtree = 0;
40459   }
40460   if( mutexOpen ){
40461     assert( sqlite3_mutex_held(mutexOpen) );
40462     sqlite3_mutex_leave(mutexOpen);
40463   }
40464   return rc;
40465 }
40466
40467 /*
40468 ** Decrement the BtShared.nRef counter.  When it reaches zero,
40469 ** remove the BtShared structure from the sharing list.  Return
40470 ** true if the BtShared.nRef counter reaches zero and return
40471 ** false if it is still positive.
40472 */
40473 static int removeFromSharingList(BtShared *pBt){
40474 #ifndef SQLITE_OMIT_SHARED_CACHE
40475   sqlite3_mutex *pMaster;
40476   BtShared *pList;
40477   int removed = 0;
40478
40479   assert( sqlite3_mutex_notheld(pBt->mutex) );
40480   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
40481   sqlite3_mutex_enter(pMaster);
40482   pBt->nRef--;
40483   if( pBt->nRef<=0 ){
40484     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
40485       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
40486     }else{
40487       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
40488       while( ALWAYS(pList) && pList->pNext!=pBt ){
40489         pList=pList->pNext;
40490       }
40491       if( ALWAYS(pList) ){
40492         pList->pNext = pBt->pNext;
40493       }
40494     }
40495     if( SQLITE_THREADSAFE ){
40496       sqlite3_mutex_free(pBt->mutex);
40497     }
40498     removed = 1;
40499   }
40500   sqlite3_mutex_leave(pMaster);
40501   return removed;
40502 #else
40503   return 1;
40504 #endif
40505 }
40506
40507 /*
40508 ** Make sure pBt->pTmpSpace points to an allocation of 
40509 ** MX_CELL_SIZE(pBt) bytes.
40510 */
40511 static void allocateTempSpace(BtShared *pBt){
40512   if( !pBt->pTmpSpace ){
40513     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
40514   }
40515 }
40516
40517 /*
40518 ** Free the pBt->pTmpSpace allocation
40519 */
40520 static void freeTempSpace(BtShared *pBt){
40521   sqlite3PageFree( pBt->pTmpSpace);
40522   pBt->pTmpSpace = 0;
40523 }
40524
40525 /*
40526 ** Close an open database and invalidate all cursors.
40527 */
40528 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
40529   BtShared *pBt = p->pBt;
40530   BtCursor *pCur;
40531
40532   /* Close all cursors opened via this handle.  */
40533   assert( sqlite3_mutex_held(p->db->mutex) );
40534   sqlite3BtreeEnter(p);
40535   pCur = pBt->pCursor;
40536   while( pCur ){
40537     BtCursor *pTmp = pCur;
40538     pCur = pCur->pNext;
40539     if( pTmp->pBtree==p ){
40540       sqlite3BtreeCloseCursor(pTmp);
40541     }
40542   }
40543
40544   /* Rollback any active transaction and free the handle structure.
40545   ** The call to sqlite3BtreeRollback() drops any table-locks held by
40546   ** this handle.
40547   */
40548   sqlite3BtreeRollback(p);
40549   sqlite3BtreeLeave(p);
40550
40551   /* If there are still other outstanding references to the shared-btree
40552   ** structure, return now. The remainder of this procedure cleans 
40553   ** up the shared-btree.
40554   */
40555   assert( p->wantToLock==0 && p->locked==0 );
40556   if( !p->sharable || removeFromSharingList(pBt) ){
40557     /* The pBt is no longer on the sharing list, so we can access
40558     ** it without having to hold the mutex.
40559     **
40560     ** Clean out and delete the BtShared object.
40561     */
40562     assert( !pBt->pCursor );
40563     sqlite3PagerClose(pBt->pPager);
40564     if( pBt->xFreeSchema && pBt->pSchema ){
40565       pBt->xFreeSchema(pBt->pSchema);
40566     }
40567     sqlite3_free(pBt->pSchema);
40568     freeTempSpace(pBt);
40569     sqlite3_free(pBt);
40570   }
40571
40572 #ifndef SQLITE_OMIT_SHARED_CACHE
40573   assert( p->wantToLock==0 );
40574   assert( p->locked==0 );
40575   if( p->pPrev ) p->pPrev->pNext = p->pNext;
40576   if( p->pNext ) p->pNext->pPrev = p->pPrev;
40577 #endif
40578
40579   sqlite3_free(p);
40580   return SQLITE_OK;
40581 }
40582
40583 /*
40584 ** Change the limit on the number of pages allowed in the cache.
40585 **
40586 ** The maximum number of cache pages is set to the absolute
40587 ** value of mxPage.  If mxPage is negative, the pager will
40588 ** operate asynchronously - it will not stop to do fsync()s
40589 ** to insure data is written to the disk surface before
40590 ** continuing.  Transactions still work if synchronous is off,
40591 ** and the database cannot be corrupted if this program
40592 ** crashes.  But if the operating system crashes or there is
40593 ** an abrupt power failure when synchronous is off, the database
40594 ** could be left in an inconsistent and unrecoverable state.
40595 ** Synchronous is on by default so database corruption is not
40596 ** normally a worry.
40597 */
40598 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
40599   BtShared *pBt = p->pBt;
40600   assert( sqlite3_mutex_held(p->db->mutex) );
40601   sqlite3BtreeEnter(p);
40602   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
40603   sqlite3BtreeLeave(p);
40604   return SQLITE_OK;
40605 }
40606
40607 /*
40608 ** Change the way data is synced to disk in order to increase or decrease
40609 ** how well the database resists damage due to OS crashes and power
40610 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
40611 ** there is a high probability of damage)  Level 2 is the default.  There
40612 ** is a very low but non-zero probability of damage.  Level 3 reduces the
40613 ** probability of damage to near zero but with a write performance reduction.
40614 */
40615 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
40616 SQLITE_PRIVATE int sqlite3BtreeSetSafetyLevel(Btree *p, int level, int fullSync){
40617   BtShared *pBt = p->pBt;
40618   assert( sqlite3_mutex_held(p->db->mutex) );
40619   sqlite3BtreeEnter(p);
40620   sqlite3PagerSetSafetyLevel(pBt->pPager, level, fullSync);
40621   sqlite3BtreeLeave(p);
40622   return SQLITE_OK;
40623 }
40624 #endif
40625
40626 /*
40627 ** Return TRUE if the given btree is set to safety level 1.  In other
40628 ** words, return TRUE if no sync() occurs on the disk files.
40629 */
40630 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
40631   BtShared *pBt = p->pBt;
40632   int rc;
40633   assert( sqlite3_mutex_held(p->db->mutex) );  
40634   sqlite3BtreeEnter(p);
40635   assert( pBt && pBt->pPager );
40636   rc = sqlite3PagerNosync(pBt->pPager);
40637   sqlite3BtreeLeave(p);
40638   return rc;
40639 }
40640
40641 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
40642 /*
40643 ** Change the default pages size and the number of reserved bytes per page.
40644 ** Or, if the page size has already been fixed, return SQLITE_READONLY 
40645 ** without changing anything.
40646 **
40647 ** The page size must be a power of 2 between 512 and 65536.  If the page
40648 ** size supplied does not meet this constraint then the page size is not
40649 ** changed.
40650 **
40651 ** Page sizes are constrained to be a power of two so that the region
40652 ** of the database file used for locking (beginning at PENDING_BYTE,
40653 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
40654 ** at the beginning of a page.
40655 **
40656 ** If parameter nReserve is less than zero, then the number of reserved
40657 ** bytes per page is left unchanged.
40658 **
40659 ** If the iFix!=0 then the pageSizeFixed flag is set so that the page size
40660 ** and autovacuum mode can no longer be changed.
40661 */
40662 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
40663   int rc = SQLITE_OK;
40664   BtShared *pBt = p->pBt;
40665   assert( nReserve>=-1 && nReserve<=255 );
40666   sqlite3BtreeEnter(p);
40667   if( pBt->pageSizeFixed ){
40668     sqlite3BtreeLeave(p);
40669     return SQLITE_READONLY;
40670   }
40671   if( nReserve<0 ){
40672     nReserve = pBt->pageSize - pBt->usableSize;
40673   }
40674   assert( nReserve>=0 && nReserve<=255 );
40675   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
40676         ((pageSize-1)&pageSize)==0 ){
40677     assert( (pageSize & 7)==0 );
40678     assert( !pBt->pPage1 && !pBt->pCursor );
40679     pBt->pageSize = (u16)pageSize;
40680     freeTempSpace(pBt);
40681   }
40682   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
40683   pBt->usableSize = pBt->pageSize - (u16)nReserve;
40684   if( iFix ) pBt->pageSizeFixed = 1;
40685   sqlite3BtreeLeave(p);
40686   return rc;
40687 }
40688
40689 /*
40690 ** Return the currently defined page size
40691 */
40692 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
40693   return p->pBt->pageSize;
40694 }
40695
40696 /*
40697 ** Return the number of bytes of space at the end of every page that
40698 ** are intentually left unused.  This is the "reserved" space that is
40699 ** sometimes used by extensions.
40700 */
40701 SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
40702   int n;
40703   sqlite3BtreeEnter(p);
40704   n = p->pBt->pageSize - p->pBt->usableSize;
40705   sqlite3BtreeLeave(p);
40706   return n;
40707 }
40708
40709 /*
40710 ** Set the maximum page count for a database if mxPage is positive.
40711 ** No changes are made if mxPage is 0 or negative.
40712 ** Regardless of the value of mxPage, return the maximum page count.
40713 */
40714 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
40715   int n;
40716   sqlite3BtreeEnter(p);
40717   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
40718   sqlite3BtreeLeave(p);
40719   return n;
40720 }
40721
40722 /*
40723 ** Set the secureDelete flag if newFlag is 0 or 1.  If newFlag is -1,
40724 ** then make no changes.  Always return the value of the secureDelete
40725 ** setting after the change.
40726 */
40727 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
40728   int b;
40729   if( p==0 ) return 0;
40730   sqlite3BtreeEnter(p);
40731   if( newFlag>=0 ){
40732     p->pBt->secureDelete = (newFlag!=0) ? 1 : 0;
40733   } 
40734   b = p->pBt->secureDelete;
40735   sqlite3BtreeLeave(p);
40736   return b;
40737 }
40738 #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
40739
40740 /*
40741 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
40742 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
40743 ** is disabled. The default value for the auto-vacuum property is 
40744 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
40745 */
40746 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
40747 #ifdef SQLITE_OMIT_AUTOVACUUM
40748   return SQLITE_READONLY;
40749 #else
40750   BtShared *pBt = p->pBt;
40751   int rc = SQLITE_OK;
40752   u8 av = (u8)autoVacuum;
40753
40754   sqlite3BtreeEnter(p);
40755   if( pBt->pageSizeFixed && (av ?1:0)!=pBt->autoVacuum ){
40756     rc = SQLITE_READONLY;
40757   }else{
40758     pBt->autoVacuum = av ?1:0;
40759     pBt->incrVacuum = av==2 ?1:0;
40760   }
40761   sqlite3BtreeLeave(p);
40762   return rc;
40763 #endif
40764 }
40765
40766 /*
40767 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
40768 ** enabled 1 is returned. Otherwise 0.
40769 */
40770 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
40771 #ifdef SQLITE_OMIT_AUTOVACUUM
40772   return BTREE_AUTOVACUUM_NONE;
40773 #else
40774   int rc;
40775   sqlite3BtreeEnter(p);
40776   rc = (
40777     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
40778     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
40779     BTREE_AUTOVACUUM_INCR
40780   );
40781   sqlite3BtreeLeave(p);
40782   return rc;
40783 #endif
40784 }
40785
40786
40787 /*
40788 ** Get a reference to pPage1 of the database file.  This will
40789 ** also acquire a readlock on that file.
40790 **
40791 ** SQLITE_OK is returned on success.  If the file is not a
40792 ** well-formed database file, then SQLITE_CORRUPT is returned.
40793 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
40794 ** is returned if we run out of memory. 
40795 */
40796 static int lockBtree(BtShared *pBt){
40797   int rc;
40798   MemPage *pPage1;
40799   int nPage;
40800
40801   assert( sqlite3_mutex_held(pBt->mutex) );
40802   assert( pBt->pPage1==0 );
40803   rc = sqlite3PagerSharedLock(pBt->pPager);
40804   if( rc!=SQLITE_OK ) return rc;
40805   rc = btreeGetPage(pBt, 1, &pPage1, 0);
40806   if( rc!=SQLITE_OK ) return rc;
40807
40808   /* Do some checking to help insure the file we opened really is
40809   ** a valid database file. 
40810   */
40811   rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
40812   if( rc!=SQLITE_OK ){
40813     goto page1_init_failed;
40814   }else if( nPage>0 ){
40815     int pageSize;
40816     int usableSize;
40817     u8 *page1 = pPage1->aData;
40818     rc = SQLITE_NOTADB;
40819     if( memcmp(page1, zMagicHeader, 16)!=0 ){
40820       goto page1_init_failed;
40821     }
40822     if( page1[18]>1 ){
40823       pBt->readOnly = 1;
40824     }
40825     if( page1[19]>1 ){
40826       goto page1_init_failed;
40827     }
40828
40829     /* The maximum embedded fraction must be exactly 25%.  And the minimum
40830     ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
40831     ** The original design allowed these amounts to vary, but as of
40832     ** version 3.6.0, we require them to be fixed.
40833     */
40834     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
40835       goto page1_init_failed;
40836     }
40837     pageSize = get2byte(&page1[16]);
40838     if( ((pageSize-1)&pageSize)!=0 || pageSize<512 ||
40839         (SQLITE_MAX_PAGE_SIZE<32768 && pageSize>SQLITE_MAX_PAGE_SIZE)
40840     ){
40841       goto page1_init_failed;
40842     }
40843     assert( (pageSize & 7)==0 );
40844     usableSize = pageSize - page1[20];
40845     if( pageSize!=pBt->pageSize ){
40846       /* After reading the first page of the database assuming a page size
40847       ** of BtShared.pageSize, we have discovered that the page-size is
40848       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
40849       ** zero and return SQLITE_OK. The caller will call this function
40850       ** again with the correct page-size.
40851       */
40852       releasePage(pPage1);
40853       pBt->usableSize = (u16)usableSize;
40854       pBt->pageSize = (u16)pageSize;
40855       freeTempSpace(pBt);
40856       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
40857                                    pageSize-usableSize);
40858       return rc;
40859     }
40860     if( usableSize<480 ){
40861       goto page1_init_failed;
40862     }
40863     pBt->pageSize = (u16)pageSize;
40864     pBt->usableSize = (u16)usableSize;
40865 #ifndef SQLITE_OMIT_AUTOVACUUM
40866     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
40867     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
40868 #endif
40869   }
40870
40871   /* maxLocal is the maximum amount of payload to store locally for
40872   ** a cell.  Make sure it is small enough so that at least minFanout
40873   ** cells can will fit on one page.  We assume a 10-byte page header.
40874   ** Besides the payload, the cell must store:
40875   **     2-byte pointer to the cell
40876   **     4-byte child pointer
40877   **     9-byte nKey value
40878   **     4-byte nData value
40879   **     4-byte overflow page pointer
40880   ** So a cell consists of a 2-byte poiner, a header which is as much as
40881   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
40882   ** page pointer.
40883   */
40884   pBt->maxLocal = (pBt->usableSize-12)*64/255 - 23;
40885   pBt->minLocal = (pBt->usableSize-12)*32/255 - 23;
40886   pBt->maxLeaf = pBt->usableSize - 35;
40887   pBt->minLeaf = (pBt->usableSize-12)*32/255 - 23;
40888   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
40889   pBt->pPage1 = pPage1;
40890   return SQLITE_OK;
40891
40892 page1_init_failed:
40893   releasePage(pPage1);
40894   pBt->pPage1 = 0;
40895   return rc;
40896 }
40897
40898 /*
40899 ** If there are no outstanding cursors and we are not in the middle
40900 ** of a transaction but there is a read lock on the database, then
40901 ** this routine unrefs the first page of the database file which 
40902 ** has the effect of releasing the read lock.
40903 **
40904 ** If there is a transaction in progress, this routine is a no-op.
40905 */
40906 static void unlockBtreeIfUnused(BtShared *pBt){
40907   assert( sqlite3_mutex_held(pBt->mutex) );
40908   assert( pBt->pCursor==0 || pBt->inTransaction>TRANS_NONE );
40909   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
40910     assert( pBt->pPage1->aData );
40911     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
40912     assert( pBt->pPage1->aData );
40913     releasePage(pBt->pPage1);
40914     pBt->pPage1 = 0;
40915   }
40916 }
40917
40918 /*
40919 ** If pBt points to an empty file then convert that empty file
40920 ** into a new empty database by initializing the first page of
40921 ** the database.
40922 */
40923 static int newDatabase(BtShared *pBt){
40924   MemPage *pP1;
40925   unsigned char *data;
40926   int rc;
40927   int nPage;
40928
40929   assert( sqlite3_mutex_held(pBt->mutex) );
40930   rc = sqlite3PagerPagecount(pBt->pPager, &nPage);
40931   if( rc!=SQLITE_OK || nPage>0 ){
40932     return rc;
40933   }
40934   pP1 = pBt->pPage1;
40935   assert( pP1!=0 );
40936   data = pP1->aData;
40937   rc = sqlite3PagerWrite(pP1->pDbPage);
40938   if( rc ) return rc;
40939   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
40940   assert( sizeof(zMagicHeader)==16 );
40941   put2byte(&data[16], pBt->pageSize);
40942   data[18] = 1;
40943   data[19] = 1;
40944   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
40945   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
40946   data[21] = 64;
40947   data[22] = 32;
40948   data[23] = 32;
40949   memset(&data[24], 0, 100-24);
40950   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
40951   pBt->pageSizeFixed = 1;
40952 #ifndef SQLITE_OMIT_AUTOVACUUM
40953   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
40954   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
40955   put4byte(&data[36 + 4*4], pBt->autoVacuum);
40956   put4byte(&data[36 + 7*4], pBt->incrVacuum);
40957 #endif
40958   return SQLITE_OK;
40959 }
40960
40961 /*
40962 ** Attempt to start a new transaction. A write-transaction
40963 ** is started if the second argument is nonzero, otherwise a read-
40964 ** transaction.  If the second argument is 2 or more and exclusive
40965 ** transaction is started, meaning that no other process is allowed
40966 ** to access the database.  A preexisting transaction may not be
40967 ** upgraded to exclusive by calling this routine a second time - the
40968 ** exclusivity flag only works for a new transaction.
40969 **
40970 ** A write-transaction must be started before attempting any 
40971 ** changes to the database.  None of the following routines 
40972 ** will work unless a transaction is started first:
40973 **
40974 **      sqlite3BtreeCreateTable()
40975 **      sqlite3BtreeCreateIndex()
40976 **      sqlite3BtreeClearTable()
40977 **      sqlite3BtreeDropTable()
40978 **      sqlite3BtreeInsert()
40979 **      sqlite3BtreeDelete()
40980 **      sqlite3BtreeUpdateMeta()
40981 **
40982 ** If an initial attempt to acquire the lock fails because of lock contention
40983 ** and the database was previously unlocked, then invoke the busy handler
40984 ** if there is one.  But if there was previously a read-lock, do not
40985 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
40986 ** returned when there is already a read-lock in order to avoid a deadlock.
40987 **
40988 ** Suppose there are two processes A and B.  A has a read lock and B has
40989 ** a reserved lock.  B tries to promote to exclusive but is blocked because
40990 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
40991 ** One or the other of the two processes must give way or there can be
40992 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
40993 ** when A already has a read lock, we encourage A to give up and let B
40994 ** proceed.
40995 */
40996 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
40997   sqlite3 *pBlock = 0;
40998   BtShared *pBt = p->pBt;
40999   int rc = SQLITE_OK;
41000
41001   sqlite3BtreeEnter(p);
41002   btreeIntegrity(p);
41003
41004   /* If the btree is already in a write-transaction, or it
41005   ** is already in a read-transaction and a read-transaction
41006   ** is requested, this is a no-op.
41007   */
41008   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
41009     goto trans_begun;
41010   }
41011
41012   /* Write transactions are not possible on a read-only database */
41013   if( pBt->readOnly && wrflag ){
41014     rc = SQLITE_READONLY;
41015     goto trans_begun;
41016   }
41017
41018 #ifndef SQLITE_OMIT_SHARED_CACHE
41019   /* If another database handle has already opened a write transaction 
41020   ** on this shared-btree structure and a second write transaction is
41021   ** requested, return SQLITE_LOCKED.
41022   */
41023   if( (wrflag && pBt->inTransaction==TRANS_WRITE) || pBt->isPending ){
41024     pBlock = pBt->pWriter->db;
41025   }else if( wrflag>1 ){
41026     BtLock *pIter;
41027     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
41028       if( pIter->pBtree!=p ){
41029         pBlock = pIter->pBtree->db;
41030         break;
41031       }
41032     }
41033   }
41034   if( pBlock ){
41035     sqlite3ConnectionBlocked(p->db, pBlock);
41036     rc = SQLITE_LOCKED_SHAREDCACHE;
41037     goto trans_begun;
41038   }
41039 #endif
41040
41041   /* Any read-only or read-write transaction implies a read-lock on 
41042   ** page 1. So if some other shared-cache client already has a write-lock 
41043   ** on page 1, the transaction cannot be opened. */
41044   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
41045   if( SQLITE_OK!=rc ) goto trans_begun;
41046
41047   do {
41048     /* Call lockBtree() until either pBt->pPage1 is populated or
41049     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
41050     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
41051     ** reading page 1 it discovers that the page-size of the database 
41052     ** file is not pBt->pageSize. In this case lockBtree() will update
41053     ** pBt->pageSize to the page-size of the file on disk.
41054     */
41055     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
41056
41057     if( rc==SQLITE_OK && wrflag ){
41058       if( pBt->readOnly ){
41059         rc = SQLITE_READONLY;
41060       }else{
41061         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
41062         if( rc==SQLITE_OK ){
41063           rc = newDatabase(pBt);
41064         }
41065       }
41066     }
41067   
41068     if( rc!=SQLITE_OK ){
41069       unlockBtreeIfUnused(pBt);
41070     }
41071   }while( rc==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
41072           btreeInvokeBusyHandler(pBt) );
41073
41074   if( rc==SQLITE_OK ){
41075     if( p->inTrans==TRANS_NONE ){
41076       pBt->nTransaction++;
41077 #ifndef SQLITE_OMIT_SHARED_CACHE
41078       if( p->sharable ){
41079         assert( p->lock.pBtree==p && p->lock.iTable==1 );
41080         p->lock.eLock = READ_LOCK;
41081         p->lock.pNext = pBt->pLock;
41082         pBt->pLock = &p->lock;
41083       }
41084 #endif
41085     }
41086     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
41087     if( p->inTrans>pBt->inTransaction ){
41088       pBt->inTransaction = p->inTrans;
41089     }
41090 #ifndef SQLITE_OMIT_SHARED_CACHE
41091     if( wrflag ){
41092       assert( !pBt->pWriter );
41093       pBt->pWriter = p;
41094       pBt->isExclusive = (u8)(wrflag>1);
41095     }
41096 #endif
41097   }
41098
41099
41100 trans_begun:
41101   if( rc==SQLITE_OK && wrflag ){
41102     /* This call makes sure that the pager has the correct number of
41103     ** open savepoints. If the second parameter is greater than 0 and
41104     ** the sub-journal is not already open, then it will be opened here.
41105     */
41106     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
41107   }
41108
41109   btreeIntegrity(p);
41110   sqlite3BtreeLeave(p);
41111   return rc;
41112 }
41113
41114 #ifndef SQLITE_OMIT_AUTOVACUUM
41115
41116 /*
41117 ** Set the pointer-map entries for all children of page pPage. Also, if
41118 ** pPage contains cells that point to overflow pages, set the pointer
41119 ** map entries for the overflow pages as well.
41120 */
41121 static int setChildPtrmaps(MemPage *pPage){
41122   int i;                             /* Counter variable */
41123   int nCell;                         /* Number of cells in page pPage */
41124   int rc;                            /* Return code */
41125   BtShared *pBt = pPage->pBt;
41126   u8 isInitOrig = pPage->isInit;
41127   Pgno pgno = pPage->pgno;
41128
41129   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
41130   rc = btreeInitPage(pPage);
41131   if( rc!=SQLITE_OK ){
41132     goto set_child_ptrmaps_out;
41133   }
41134   nCell = pPage->nCell;
41135
41136   for(i=0; i<nCell; i++){
41137     u8 *pCell = findCell(pPage, i);
41138
41139     ptrmapPutOvflPtr(pPage, pCell, &rc);
41140
41141     if( !pPage->leaf ){
41142       Pgno childPgno = get4byte(pCell);
41143       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
41144     }
41145   }
41146
41147   if( !pPage->leaf ){
41148     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
41149     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
41150   }
41151
41152 set_child_ptrmaps_out:
41153   pPage->isInit = isInitOrig;
41154   return rc;
41155 }
41156
41157 /*
41158 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
41159 ** that it points to iTo. Parameter eType describes the type of pointer to
41160 ** be modified, as  follows:
41161 **
41162 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
41163 **                   page of pPage.
41164 **
41165 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
41166 **                   page pointed to by one of the cells on pPage.
41167 **
41168 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
41169 **                   overflow page in the list.
41170 */
41171 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
41172   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
41173   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
41174   if( eType==PTRMAP_OVERFLOW2 ){
41175     /* The pointer is always the first 4 bytes of the page in this case.  */
41176     if( get4byte(pPage->aData)!=iFrom ){
41177       return SQLITE_CORRUPT_BKPT;
41178     }
41179     put4byte(pPage->aData, iTo);
41180   }else{
41181     u8 isInitOrig = pPage->isInit;
41182     int i;
41183     int nCell;
41184
41185     btreeInitPage(pPage);
41186     nCell = pPage->nCell;
41187
41188     for(i=0; i<nCell; i++){
41189       u8 *pCell = findCell(pPage, i);
41190       if( eType==PTRMAP_OVERFLOW1 ){
41191         CellInfo info;
41192         btreeParseCellPtr(pPage, pCell, &info);
41193         if( info.iOverflow ){
41194           if( iFrom==get4byte(&pCell[info.iOverflow]) ){
41195             put4byte(&pCell[info.iOverflow], iTo);
41196             break;
41197           }
41198         }
41199       }else{
41200         if( get4byte(pCell)==iFrom ){
41201           put4byte(pCell, iTo);
41202           break;
41203         }
41204       }
41205     }
41206   
41207     if( i==nCell ){
41208       if( eType!=PTRMAP_BTREE || 
41209           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
41210         return SQLITE_CORRUPT_BKPT;
41211       }
41212       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
41213     }
41214
41215     pPage->isInit = isInitOrig;
41216   }
41217   return SQLITE_OK;
41218 }
41219
41220
41221 /*
41222 ** Move the open database page pDbPage to location iFreePage in the 
41223 ** database. The pDbPage reference remains valid.
41224 **
41225 ** The isCommit flag indicates that there is no need to remember that
41226 ** the journal needs to be sync()ed before database page pDbPage->pgno 
41227 ** can be written to. The caller has already promised not to write to that
41228 ** page.
41229 */
41230 static int relocatePage(
41231   BtShared *pBt,           /* Btree */
41232   MemPage *pDbPage,        /* Open page to move */
41233   u8 eType,                /* Pointer map 'type' entry for pDbPage */
41234   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
41235   Pgno iFreePage,          /* The location to move pDbPage to */
41236   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
41237 ){
41238   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
41239   Pgno iDbPage = pDbPage->pgno;
41240   Pager *pPager = pBt->pPager;
41241   int rc;
41242
41243   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
41244       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
41245   assert( sqlite3_mutex_held(pBt->mutex) );
41246   assert( pDbPage->pBt==pBt );
41247
41248   /* Move page iDbPage from its current location to page number iFreePage */
41249   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
41250       iDbPage, iFreePage, iPtrPage, eType));
41251   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
41252   if( rc!=SQLITE_OK ){
41253     return rc;
41254   }
41255   pDbPage->pgno = iFreePage;
41256
41257   /* If pDbPage was a btree-page, then it may have child pages and/or cells
41258   ** that point to overflow pages. The pointer map entries for all these
41259   ** pages need to be changed.
41260   **
41261   ** If pDbPage is an overflow page, then the first 4 bytes may store a
41262   ** pointer to a subsequent overflow page. If this is the case, then
41263   ** the pointer map needs to be updated for the subsequent overflow page.
41264   */
41265   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
41266     rc = setChildPtrmaps(pDbPage);
41267     if( rc!=SQLITE_OK ){
41268       return rc;
41269     }
41270   }else{
41271     Pgno nextOvfl = get4byte(pDbPage->aData);
41272     if( nextOvfl!=0 ){
41273       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
41274       if( rc!=SQLITE_OK ){
41275         return rc;
41276       }
41277     }
41278   }
41279
41280   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
41281   ** that it points at iFreePage. Also fix the pointer map entry for
41282   ** iPtrPage.
41283   */
41284   if( eType!=PTRMAP_ROOTPAGE ){
41285     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
41286     if( rc!=SQLITE_OK ){
41287       return rc;
41288     }
41289     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
41290     if( rc!=SQLITE_OK ){
41291       releasePage(pPtrPage);
41292       return rc;
41293     }
41294     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
41295     releasePage(pPtrPage);
41296     if( rc==SQLITE_OK ){
41297       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
41298     }
41299   }
41300   return rc;
41301 }
41302
41303 /* Forward declaration required by incrVacuumStep(). */
41304 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
41305
41306 /*
41307 ** Perform a single step of an incremental-vacuum. If successful,
41308 ** return SQLITE_OK. If there is no work to do (and therefore no
41309 ** point in calling this function again), return SQLITE_DONE.
41310 **
41311 ** More specificly, this function attempts to re-organize the 
41312 ** database so that the last page of the file currently in use
41313 ** is no longer in use.
41314 **
41315 ** If the nFin parameter is non-zero, this function assumes
41316 ** that the caller will keep calling incrVacuumStep() until
41317 ** it returns SQLITE_DONE or an error, and that nFin is the
41318 ** number of pages the database file will contain after this 
41319 ** process is complete.  If nFin is zero, it is assumed that
41320 ** incrVacuumStep() will be called a finite amount of times
41321 ** which may or may not empty the freelist.  A full autovacuum
41322 ** has nFin>0.  A "PRAGMA incremental_vacuum" has nFin==0.
41323 */
41324 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg){
41325   Pgno nFreeList;           /* Number of pages still on the free-list */
41326
41327   assert( sqlite3_mutex_held(pBt->mutex) );
41328   assert( iLastPg>nFin );
41329
41330   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
41331     int rc;
41332     u8 eType;
41333     Pgno iPtrPage;
41334
41335     nFreeList = get4byte(&pBt->pPage1->aData[36]);
41336     if( nFreeList==0 ){
41337       return SQLITE_DONE;
41338     }
41339
41340     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
41341     if( rc!=SQLITE_OK ){
41342       return rc;
41343     }
41344     if( eType==PTRMAP_ROOTPAGE ){
41345       return SQLITE_CORRUPT_BKPT;
41346     }
41347
41348     if( eType==PTRMAP_FREEPAGE ){
41349       if( nFin==0 ){
41350         /* Remove the page from the files free-list. This is not required
41351         ** if nFin is non-zero. In that case, the free-list will be
41352         ** truncated to zero after this function returns, so it doesn't 
41353         ** matter if it still contains some garbage entries.
41354         */
41355         Pgno iFreePg;
41356         MemPage *pFreePg;
41357         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, 1);
41358         if( rc!=SQLITE_OK ){
41359           return rc;
41360         }
41361         assert( iFreePg==iLastPg );
41362         releasePage(pFreePg);
41363       }
41364     } else {
41365       Pgno iFreePg;             /* Index of free page to move pLastPg to */
41366       MemPage *pLastPg;
41367
41368       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
41369       if( rc!=SQLITE_OK ){
41370         return rc;
41371       }
41372
41373       /* If nFin is zero, this loop runs exactly once and page pLastPg
41374       ** is swapped with the first free page pulled off the free list.
41375       **
41376       ** On the other hand, if nFin is greater than zero, then keep
41377       ** looping until a free-page located within the first nFin pages
41378       ** of the file is found.
41379       */
41380       do {
41381         MemPage *pFreePg;
41382         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, 0, 0);
41383         if( rc!=SQLITE_OK ){
41384           releasePage(pLastPg);
41385           return rc;
41386         }
41387         releasePage(pFreePg);
41388       }while( nFin!=0 && iFreePg>nFin );
41389       assert( iFreePg<iLastPg );
41390       
41391       rc = sqlite3PagerWrite(pLastPg->pDbPage);
41392       if( rc==SQLITE_OK ){
41393         rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, nFin!=0);
41394       }
41395       releasePage(pLastPg);
41396       if( rc!=SQLITE_OK ){
41397         return rc;
41398       }
41399     }
41400   }
41401
41402   if( nFin==0 ){
41403     iLastPg--;
41404     while( iLastPg==PENDING_BYTE_PAGE(pBt)||PTRMAP_ISPAGE(pBt, iLastPg) ){
41405       if( PTRMAP_ISPAGE(pBt, iLastPg) ){
41406         MemPage *pPg;
41407         int rc = btreeGetPage(pBt, iLastPg, &pPg, 0);
41408         if( rc!=SQLITE_OK ){
41409           return rc;
41410         }
41411         rc = sqlite3PagerWrite(pPg->pDbPage);
41412         releasePage(pPg);
41413         if( rc!=SQLITE_OK ){
41414           return rc;
41415         }
41416       }
41417       iLastPg--;
41418     }
41419     sqlite3PagerTruncateImage(pBt->pPager, iLastPg);
41420   }
41421   return SQLITE_OK;
41422 }
41423
41424 /*
41425 ** A write-transaction must be opened before calling this function.
41426 ** It performs a single unit of work towards an incremental vacuum.
41427 **
41428 ** If the incremental vacuum is finished after this function has run,
41429 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
41430 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
41431 */
41432 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
41433   int rc;
41434   BtShared *pBt = p->pBt;
41435
41436   sqlite3BtreeEnter(p);
41437   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
41438   if( !pBt->autoVacuum ){
41439     rc = SQLITE_DONE;
41440   }else{
41441     invalidateAllOverflowCache(pBt);
41442     rc = incrVacuumStep(pBt, 0, pagerPagecount(pBt));
41443   }
41444   sqlite3BtreeLeave(p);
41445   return rc;
41446 }
41447
41448 /*
41449 ** This routine is called prior to sqlite3PagerCommit when a transaction
41450 ** is commited for an auto-vacuum database.
41451 **
41452 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
41453 ** the database file should be truncated to during the commit process. 
41454 ** i.e. the database has been reorganized so that only the first *pnTrunc
41455 ** pages are in use.
41456 */
41457 static int autoVacuumCommit(BtShared *pBt){
41458   int rc = SQLITE_OK;
41459   Pager *pPager = pBt->pPager;
41460   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
41461
41462   assert( sqlite3_mutex_held(pBt->mutex) );
41463   invalidateAllOverflowCache(pBt);
41464   assert(pBt->autoVacuum);
41465   if( !pBt->incrVacuum ){
41466     Pgno nFin;         /* Number of pages in database after autovacuuming */
41467     Pgno nFree;        /* Number of pages on the freelist initially */
41468     Pgno nPtrmap;      /* Number of PtrMap pages to be freed */
41469     Pgno iFree;        /* The next page to be freed */
41470     int nEntry;        /* Number of entries on one ptrmap page */
41471     Pgno nOrig;        /* Database size before freeing */
41472
41473     nOrig = pagerPagecount(pBt);
41474     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
41475       /* It is not possible to create a database for which the final page
41476       ** is either a pointer-map page or the pending-byte page. If one
41477       ** is encountered, this indicates corruption.
41478       */
41479       return SQLITE_CORRUPT_BKPT;
41480     }
41481
41482     nFree = get4byte(&pBt->pPage1->aData[36]);
41483     nEntry = pBt->usableSize/5;
41484     nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
41485     nFin = nOrig - nFree - nPtrmap;
41486     if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
41487       nFin--;
41488     }
41489     while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
41490       nFin--;
41491     }
41492     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
41493
41494     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
41495       rc = incrVacuumStep(pBt, nFin, iFree);
41496     }
41497     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
41498       rc = SQLITE_OK;
41499       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
41500       put4byte(&pBt->pPage1->aData[32], 0);
41501       put4byte(&pBt->pPage1->aData[36], 0);
41502       sqlite3PagerTruncateImage(pBt->pPager, nFin);
41503     }
41504     if( rc!=SQLITE_OK ){
41505       sqlite3PagerRollback(pPager);
41506     }
41507   }
41508
41509   assert( nRef==sqlite3PagerRefcount(pPager) );
41510   return rc;
41511 }
41512
41513 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
41514 # define setChildPtrmaps(x) SQLITE_OK
41515 #endif
41516
41517 /*
41518 ** This routine does the first phase of a two-phase commit.  This routine
41519 ** causes a rollback journal to be created (if it does not already exist)
41520 ** and populated with enough information so that if a power loss occurs
41521 ** the database can be restored to its original state by playing back
41522 ** the journal.  Then the contents of the journal are flushed out to
41523 ** the disk.  After the journal is safely on oxide, the changes to the
41524 ** database are written into the database file and flushed to oxide.
41525 ** At the end of this call, the rollback journal still exists on the
41526 ** disk and we are still holding all locks, so the transaction has not
41527 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
41528 ** commit process.
41529 **
41530 ** This call is a no-op if no write-transaction is currently active on pBt.
41531 **
41532 ** Otherwise, sync the database file for the btree pBt. zMaster points to
41533 ** the name of a master journal file that should be written into the
41534 ** individual journal file, or is NULL, indicating no master journal file 
41535 ** (single database transaction).
41536 **
41537 ** When this is called, the master journal should already have been
41538 ** created, populated with this journal pointer and synced to disk.
41539 **
41540 ** Once this is routine has returned, the only thing required to commit
41541 ** the write-transaction for this database file is to delete the journal.
41542 */
41543 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
41544   int rc = SQLITE_OK;
41545   if( p->inTrans==TRANS_WRITE ){
41546     BtShared *pBt = p->pBt;
41547     sqlite3BtreeEnter(p);
41548 #ifndef SQLITE_OMIT_AUTOVACUUM
41549     if( pBt->autoVacuum ){
41550       rc = autoVacuumCommit(pBt);
41551       if( rc!=SQLITE_OK ){
41552         sqlite3BtreeLeave(p);
41553         return rc;
41554       }
41555     }
41556 #endif
41557     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
41558     sqlite3BtreeLeave(p);
41559   }
41560   return rc;
41561 }
41562
41563 /*
41564 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
41565 ** at the conclusion of a transaction.
41566 */
41567 static void btreeEndTransaction(Btree *p){
41568   BtShared *pBt = p->pBt;
41569   assert( sqlite3BtreeHoldsMutex(p) );
41570
41571   btreeClearHasContent(pBt);
41572   if( p->inTrans>TRANS_NONE && p->db->activeVdbeCnt>1 ){
41573     /* If there are other active statements that belong to this database
41574     ** handle, downgrade to a read-only transaction. The other statements
41575     ** may still be reading from the database.  */
41576     downgradeAllSharedCacheTableLocks(p);
41577     p->inTrans = TRANS_READ;
41578   }else{
41579     /* If the handle had any kind of transaction open, decrement the 
41580     ** transaction count of the shared btree. If the transaction count 
41581     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
41582     ** call below will unlock the pager.  */
41583     if( p->inTrans!=TRANS_NONE ){
41584       clearAllSharedCacheTableLocks(p);
41585       pBt->nTransaction--;
41586       if( 0==pBt->nTransaction ){
41587         pBt->inTransaction = TRANS_NONE;
41588       }
41589     }
41590
41591     /* Set the current transaction state to TRANS_NONE and unlock the 
41592     ** pager if this call closed the only read or write transaction.  */
41593     p->inTrans = TRANS_NONE;
41594     unlockBtreeIfUnused(pBt);
41595   }
41596
41597   btreeIntegrity(p);
41598 }
41599
41600 /*
41601 ** Commit the transaction currently in progress.
41602 **
41603 ** This routine implements the second phase of a 2-phase commit.  The
41604 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
41605 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
41606 ** routine did all the work of writing information out to disk and flushing the
41607 ** contents so that they are written onto the disk platter.  All this
41608 ** routine has to do is delete or truncate or zero the header in the
41609 ** the rollback journal (which causes the transaction to commit) and
41610 ** drop locks.
41611 **
41612 ** This will release the write lock on the database file.  If there
41613 ** are no active cursors, it also releases the read lock.
41614 */
41615 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p){
41616   BtShared *pBt = p->pBt;
41617
41618   sqlite3BtreeEnter(p);
41619   btreeIntegrity(p);
41620
41621   /* If the handle has a write-transaction open, commit the shared-btrees 
41622   ** transaction and set the shared state to TRANS_READ.
41623   */
41624   if( p->inTrans==TRANS_WRITE ){
41625     int rc;
41626     assert( pBt->inTransaction==TRANS_WRITE );
41627     assert( pBt->nTransaction>0 );
41628     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
41629     if( rc!=SQLITE_OK ){
41630       sqlite3BtreeLeave(p);
41631       return rc;
41632     }
41633     pBt->inTransaction = TRANS_READ;
41634   }
41635
41636   btreeEndTransaction(p);
41637   sqlite3BtreeLeave(p);
41638   return SQLITE_OK;
41639 }
41640
41641 /*
41642 ** Do both phases of a commit.
41643 */
41644 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
41645   int rc;
41646   sqlite3BtreeEnter(p);
41647   rc = sqlite3BtreeCommitPhaseOne(p, 0);
41648   if( rc==SQLITE_OK ){
41649     rc = sqlite3BtreeCommitPhaseTwo(p);
41650   }
41651   sqlite3BtreeLeave(p);
41652   return rc;
41653 }
41654
41655 #ifndef NDEBUG
41656 /*
41657 ** Return the number of write-cursors open on this handle. This is for use
41658 ** in assert() expressions, so it is only compiled if NDEBUG is not
41659 ** defined.
41660 **
41661 ** For the purposes of this routine, a write-cursor is any cursor that
41662 ** is capable of writing to the databse.  That means the cursor was
41663 ** originally opened for writing and the cursor has not be disabled
41664 ** by having its state changed to CURSOR_FAULT.
41665 */
41666 static int countWriteCursors(BtShared *pBt){
41667   BtCursor *pCur;
41668   int r = 0;
41669   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
41670     if( pCur->wrFlag && pCur->eState!=CURSOR_FAULT ) r++; 
41671   }
41672   return r;
41673 }
41674 #endif
41675
41676 /*
41677 ** This routine sets the state to CURSOR_FAULT and the error
41678 ** code to errCode for every cursor on BtShared that pBtree
41679 ** references.
41680 **
41681 ** Every cursor is tripped, including cursors that belong
41682 ** to other database connections that happen to be sharing
41683 ** the cache with pBtree.
41684 **
41685 ** This routine gets called when a rollback occurs.
41686 ** All cursors using the same cache must be tripped
41687 ** to prevent them from trying to use the btree after
41688 ** the rollback.  The rollback may have deleted tables
41689 ** or moved root pages, so it is not sufficient to
41690 ** save the state of the cursor.  The cursor must be
41691 ** invalidated.
41692 */
41693 SQLITE_PRIVATE void sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode){
41694   BtCursor *p;
41695   sqlite3BtreeEnter(pBtree);
41696   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
41697     int i;
41698     sqlite3BtreeClearCursor(p);
41699     p->eState = CURSOR_FAULT;
41700     p->skipNext = errCode;
41701     for(i=0; i<=p->iPage; i++){
41702       releasePage(p->apPage[i]);
41703       p->apPage[i] = 0;
41704     }
41705   }
41706   sqlite3BtreeLeave(pBtree);
41707 }
41708
41709 /*
41710 ** Rollback the transaction in progress.  All cursors will be
41711 ** invalided by this operation.  Any attempt to use a cursor
41712 ** that was open at the beginning of this operation will result
41713 ** in an error.
41714 **
41715 ** This will release the write lock on the database file.  If there
41716 ** are no active cursors, it also releases the read lock.
41717 */
41718 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p){
41719   int rc;
41720   BtShared *pBt = p->pBt;
41721   MemPage *pPage1;
41722
41723   sqlite3BtreeEnter(p);
41724   rc = saveAllCursors(pBt, 0, 0);
41725 #ifndef SQLITE_OMIT_SHARED_CACHE
41726   if( rc!=SQLITE_OK ){
41727     /* This is a horrible situation. An IO or malloc() error occurred whilst
41728     ** trying to save cursor positions. If this is an automatic rollback (as
41729     ** the result of a constraint, malloc() failure or IO error) then 
41730     ** the cache may be internally inconsistent (not contain valid trees) so
41731     ** we cannot simply return the error to the caller. Instead, abort 
41732     ** all queries that may be using any of the cursors that failed to save.
41733     */
41734     sqlite3BtreeTripAllCursors(p, rc);
41735   }
41736 #endif
41737   btreeIntegrity(p);
41738
41739   if( p->inTrans==TRANS_WRITE ){
41740     int rc2;
41741
41742     assert( TRANS_WRITE==pBt->inTransaction );
41743     rc2 = sqlite3PagerRollback(pBt->pPager);
41744     if( rc2!=SQLITE_OK ){
41745       rc = rc2;
41746     }
41747
41748     /* The rollback may have destroyed the pPage1->aData value.  So
41749     ** call btreeGetPage() on page 1 again to make
41750     ** sure pPage1->aData is set correctly. */
41751     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
41752       releasePage(pPage1);
41753     }
41754     assert( countWriteCursors(pBt)==0 );
41755     pBt->inTransaction = TRANS_READ;
41756   }
41757
41758   btreeEndTransaction(p);
41759   sqlite3BtreeLeave(p);
41760   return rc;
41761 }
41762
41763 /*
41764 ** Start a statement subtransaction. The subtransaction can can be rolled
41765 ** back independently of the main transaction. You must start a transaction 
41766 ** before starting a subtransaction. The subtransaction is ended automatically 
41767 ** if the main transaction commits or rolls back.
41768 **
41769 ** Statement subtransactions are used around individual SQL statements
41770 ** that are contained within a BEGIN...COMMIT block.  If a constraint
41771 ** error occurs within the statement, the effect of that one statement
41772 ** can be rolled back without having to rollback the entire transaction.
41773 **
41774 ** A statement sub-transaction is implemented as an anonymous savepoint. The
41775 ** value passed as the second parameter is the total number of savepoints,
41776 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
41777 ** are no active savepoints and no other statement-transactions open,
41778 ** iStatement is 1. This anonymous savepoint can be released or rolled back
41779 ** using the sqlite3BtreeSavepoint() function.
41780 */
41781 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
41782   int rc;
41783   BtShared *pBt = p->pBt;
41784   sqlite3BtreeEnter(p);
41785   assert( p->inTrans==TRANS_WRITE );
41786   assert( pBt->readOnly==0 );
41787   assert( iStatement>0 );
41788   assert( iStatement>p->db->nSavepoint );
41789   if( NEVER(p->inTrans!=TRANS_WRITE || pBt->readOnly) ){
41790     rc = SQLITE_INTERNAL;
41791   }else{
41792     assert( pBt->inTransaction==TRANS_WRITE );
41793     /* At the pager level, a statement transaction is a savepoint with
41794     ** an index greater than all savepoints created explicitly using
41795     ** SQL statements. It is illegal to open, release or rollback any
41796     ** such savepoints while the statement transaction savepoint is active.
41797     */
41798     rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
41799   }
41800   sqlite3BtreeLeave(p);
41801   return rc;
41802 }
41803
41804 /*
41805 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
41806 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
41807 ** savepoint identified by parameter iSavepoint, depending on the value 
41808 ** of op.
41809 **
41810 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
41811 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
41812 ** contents of the entire transaction are rolled back. This is different
41813 ** from a normal transaction rollback, as no locks are released and the
41814 ** transaction remains open.
41815 */
41816 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
41817   int rc = SQLITE_OK;
41818   if( p && p->inTrans==TRANS_WRITE ){
41819     BtShared *pBt = p->pBt;
41820     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
41821     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
41822     sqlite3BtreeEnter(p);
41823     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
41824     if( rc==SQLITE_OK ){
41825       rc = newDatabase(pBt);
41826     }
41827     sqlite3BtreeLeave(p);
41828   }
41829   return rc;
41830 }
41831
41832 /*
41833 ** Create a new cursor for the BTree whose root is on the page
41834 ** iTable. If a read-only cursor is requested, it is assumed that
41835 ** the caller already has at least a read-only transaction open
41836 ** on the database already. If a write-cursor is requested, then
41837 ** the caller is assumed to have an open write transaction.
41838 **
41839 ** If wrFlag==0, then the cursor can only be used for reading.
41840 ** If wrFlag==1, then the cursor can be used for reading or for
41841 ** writing if other conditions for writing are also met.  These
41842 ** are the conditions that must be met in order for writing to
41843 ** be allowed:
41844 **
41845 ** 1:  The cursor must have been opened with wrFlag==1
41846 **
41847 ** 2:  Other database connections that share the same pager cache
41848 **     but which are not in the READ_UNCOMMITTED state may not have
41849 **     cursors open with wrFlag==0 on the same table.  Otherwise
41850 **     the changes made by this write cursor would be visible to
41851 **     the read cursors in the other database connection.
41852 **
41853 ** 3:  The database must be writable (not on read-only media)
41854 **
41855 ** 4:  There must be an active transaction.
41856 **
41857 ** No checking is done to make sure that page iTable really is the
41858 ** root page of a b-tree.  If it is not, then the cursor acquired
41859 ** will not work correctly.
41860 **
41861 ** It is assumed that the sqlite3BtreeCursorZero() has been called
41862 ** on pCur to initialize the memory space prior to invoking this routine.
41863 */
41864 static int btreeCursor(
41865   Btree *p,                              /* The btree */
41866   int iTable,                            /* Root page of table to open */
41867   int wrFlag,                            /* 1 to write. 0 read-only */
41868   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
41869   BtCursor *pCur                         /* Space for new cursor */
41870 ){
41871   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
41872
41873   assert( sqlite3BtreeHoldsMutex(p) );
41874   assert( wrFlag==0 || wrFlag==1 );
41875
41876   /* The following assert statements verify that if this is a sharable 
41877   ** b-tree database, the connection is holding the required table locks, 
41878   ** and that no other connection has any open cursor that conflicts with 
41879   ** this lock.  */
41880   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
41881   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
41882
41883   /* Assert that the caller has opened the required transaction. */
41884   assert( p->inTrans>TRANS_NONE );
41885   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
41886   assert( pBt->pPage1 && pBt->pPage1->aData );
41887
41888   if( NEVER(wrFlag && pBt->readOnly) ){
41889     return SQLITE_READONLY;
41890   }
41891   if( iTable==1 && pagerPagecount(pBt)==0 ){
41892     return SQLITE_EMPTY;
41893   }
41894
41895   /* Now that no other errors can occur, finish filling in the BtCursor
41896   ** variables and link the cursor into the BtShared list.  */
41897   pCur->pgnoRoot = (Pgno)iTable;
41898   pCur->iPage = -1;
41899   pCur->pKeyInfo = pKeyInfo;
41900   pCur->pBtree = p;
41901   pCur->pBt = pBt;
41902   pCur->wrFlag = (u8)wrFlag;
41903   pCur->pNext = pBt->pCursor;
41904   if( pCur->pNext ){
41905     pCur->pNext->pPrev = pCur;
41906   }
41907   pBt->pCursor = pCur;
41908   pCur->eState = CURSOR_INVALID;
41909   pCur->cachedRowid = 0;
41910   return SQLITE_OK;
41911 }
41912 SQLITE_PRIVATE int sqlite3BtreeCursor(
41913   Btree *p,                                   /* The btree */
41914   int iTable,                                 /* Root page of table to open */
41915   int wrFlag,                                 /* 1 to write. 0 read-only */
41916   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
41917   BtCursor *pCur                              /* Write new cursor here */
41918 ){
41919   int rc;
41920   sqlite3BtreeEnter(p);
41921   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
41922   sqlite3BtreeLeave(p);
41923   return rc;
41924 }
41925
41926 /*
41927 ** Return the size of a BtCursor object in bytes.
41928 **
41929 ** This interfaces is needed so that users of cursors can preallocate
41930 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
41931 ** to users so they cannot do the sizeof() themselves - they must call
41932 ** this routine.
41933 */
41934 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
41935   return ROUND8(sizeof(BtCursor));
41936 }
41937
41938 /*
41939 ** Initialize memory that will be converted into a BtCursor object.
41940 **
41941 ** The simple approach here would be to memset() the entire object
41942 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
41943 ** do not need to be zeroed and they are large, so we can save a lot
41944 ** of run-time by skipping the initialization of those elements.
41945 */
41946 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
41947   memset(p, 0, offsetof(BtCursor, iPage));
41948 }
41949
41950 /*
41951 ** Set the cached rowid value of every cursor in the same database file
41952 ** as pCur and having the same root page number as pCur.  The value is
41953 ** set to iRowid.
41954 **
41955 ** Only positive rowid values are considered valid for this cache.
41956 ** The cache is initialized to zero, indicating an invalid cache.
41957 ** A btree will work fine with zero or negative rowids.  We just cannot
41958 ** cache zero or negative rowids, which means tables that use zero or
41959 ** negative rowids might run a little slower.  But in practice, zero
41960 ** or negative rowids are very uncommon so this should not be a problem.
41961 */
41962 SQLITE_PRIVATE void sqlite3BtreeSetCachedRowid(BtCursor *pCur, sqlite3_int64 iRowid){
41963   BtCursor *p;
41964   for(p=pCur->pBt->pCursor; p; p=p->pNext){
41965     if( p->pgnoRoot==pCur->pgnoRoot ) p->cachedRowid = iRowid;
41966   }
41967   assert( pCur->cachedRowid==iRowid );
41968 }
41969
41970 /*
41971 ** Return the cached rowid for the given cursor.  A negative or zero
41972 ** return value indicates that the rowid cache is invalid and should be
41973 ** ignored.  If the rowid cache has never before been set, then a
41974 ** zero is returned.
41975 */
41976 SQLITE_PRIVATE sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor *pCur){
41977   return pCur->cachedRowid;
41978 }
41979
41980 /*
41981 ** Close a cursor.  The read lock on the database file is released
41982 ** when the last cursor is closed.
41983 */
41984 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
41985   Btree *pBtree = pCur->pBtree;
41986   if( pBtree ){
41987     int i;
41988     BtShared *pBt = pCur->pBt;
41989     sqlite3BtreeEnter(pBtree);
41990     sqlite3BtreeClearCursor(pCur);
41991     if( pCur->pPrev ){
41992       pCur->pPrev->pNext = pCur->pNext;
41993     }else{
41994       pBt->pCursor = pCur->pNext;
41995     }
41996     if( pCur->pNext ){
41997       pCur->pNext->pPrev = pCur->pPrev;
41998     }
41999     for(i=0; i<=pCur->iPage; i++){
42000       releasePage(pCur->apPage[i]);
42001     }
42002     unlockBtreeIfUnused(pBt);
42003     invalidateOverflowCache(pCur);
42004     /* sqlite3_free(pCur); */
42005     sqlite3BtreeLeave(pBtree);
42006   }
42007   return SQLITE_OK;
42008 }
42009
42010 /*
42011 ** Make sure the BtCursor* given in the argument has a valid
42012 ** BtCursor.info structure.  If it is not already valid, call
42013 ** btreeParseCell() to fill it in.
42014 **
42015 ** BtCursor.info is a cache of the information in the current cell.
42016 ** Using this cache reduces the number of calls to btreeParseCell().
42017 **
42018 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
42019 ** compiler to crash when getCellInfo() is implemented as a macro.
42020 ** But there is a measureable speed advantage to using the macro on gcc
42021 ** (when less compiler optimizations like -Os or -O0 are used and the
42022 ** compiler is not doing agressive inlining.)  So we use a real function
42023 ** for MSVC and a macro for everything else.  Ticket #2457.
42024 */
42025 #ifndef NDEBUG
42026   static void assertCellInfo(BtCursor *pCur){
42027     CellInfo info;
42028     int iPage = pCur->iPage;
42029     memset(&info, 0, sizeof(info));
42030     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
42031     assert( memcmp(&info, &pCur->info, sizeof(info))==0 );
42032   }
42033 #else
42034   #define assertCellInfo(x)
42035 #endif
42036 #ifdef _MSC_VER
42037   /* Use a real function in MSVC to work around bugs in that compiler. */
42038   static void getCellInfo(BtCursor *pCur){
42039     if( pCur->info.nSize==0 ){
42040       int iPage = pCur->iPage;
42041       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
42042       pCur->validNKey = 1;
42043     }else{
42044       assertCellInfo(pCur);
42045     }
42046   }
42047 #else /* if not _MSC_VER */
42048   /* Use a macro in all other compilers so that the function is inlined */
42049 #define getCellInfo(pCur)                                                      \
42050   if( pCur->info.nSize==0 ){                                                   \
42051     int iPage = pCur->iPage;                                                   \
42052     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
42053     pCur->validNKey = 1;                                                       \
42054   }else{                                                                       \
42055     assertCellInfo(pCur);                                                      \
42056   }
42057 #endif /* _MSC_VER */
42058
42059 #ifndef NDEBUG  /* The next routine used only within assert() statements */
42060 /*
42061 ** Return true if the given BtCursor is valid.  A valid cursor is one
42062 ** that is currently pointing to a row in a (non-empty) table.
42063 ** This is a verification routine is used only within assert() statements.
42064 */
42065 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
42066   return pCur && pCur->eState==CURSOR_VALID;
42067 }
42068 #endif /* NDEBUG */
42069
42070 /*
42071 ** Set *pSize to the size of the buffer needed to hold the value of
42072 ** the key for the current entry.  If the cursor is not pointing
42073 ** to a valid entry, *pSize is set to 0. 
42074 **
42075 ** For a table with the INTKEY flag set, this routine returns the key
42076 ** itself, not the number of bytes in the key.
42077 **
42078 ** The caller must position the cursor prior to invoking this routine.
42079 ** 
42080 ** This routine cannot fail.  It always returns SQLITE_OK.  
42081 */
42082 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
42083   assert( cursorHoldsMutex(pCur) );
42084   assert( pCur->eState==CURSOR_INVALID || pCur->eState==CURSOR_VALID );
42085   if( pCur->eState!=CURSOR_VALID ){
42086     *pSize = 0;
42087   }else{
42088     getCellInfo(pCur);
42089     *pSize = pCur->info.nKey;
42090   }
42091   return SQLITE_OK;
42092 }
42093
42094 /*
42095 ** Set *pSize to the number of bytes of data in the entry the
42096 ** cursor currently points to.
42097 **
42098 ** The caller must guarantee that the cursor is pointing to a non-NULL
42099 ** valid entry.  In other words, the calling procedure must guarantee
42100 ** that the cursor has Cursor.eState==CURSOR_VALID.
42101 **
42102 ** Failure is not possible.  This function always returns SQLITE_OK.
42103 ** It might just as well be a procedure (returning void) but we continue
42104 ** to return an integer result code for historical reasons.
42105 */
42106 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
42107   assert( cursorHoldsMutex(pCur) );
42108   assert( pCur->eState==CURSOR_VALID );
42109   getCellInfo(pCur);
42110   *pSize = pCur->info.nData;
42111   return SQLITE_OK;
42112 }
42113
42114 /*
42115 ** Given the page number of an overflow page in the database (parameter
42116 ** ovfl), this function finds the page number of the next page in the 
42117 ** linked list of overflow pages. If possible, it uses the auto-vacuum
42118 ** pointer-map data instead of reading the content of page ovfl to do so. 
42119 **
42120 ** If an error occurs an SQLite error code is returned. Otherwise:
42121 **
42122 ** The page number of the next overflow page in the linked list is 
42123 ** written to *pPgnoNext. If page ovfl is the last page in its linked 
42124 ** list, *pPgnoNext is set to zero. 
42125 **
42126 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
42127 ** to page number pOvfl was obtained, then *ppPage is set to point to that
42128 ** reference. It is the responsibility of the caller to call releasePage()
42129 ** on *ppPage to free the reference. In no reference was obtained (because
42130 ** the pointer-map was used to obtain the value for *pPgnoNext), then
42131 ** *ppPage is set to zero.
42132 */
42133 static int getOverflowPage(
42134   BtShared *pBt,               /* The database file */
42135   Pgno ovfl,                   /* Current overflow page number */
42136   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
42137   Pgno *pPgnoNext              /* OUT: Next overflow page number */
42138 ){
42139   Pgno next = 0;
42140   MemPage *pPage = 0;
42141   int rc = SQLITE_OK;
42142
42143   assert( sqlite3_mutex_held(pBt->mutex) );
42144   assert(pPgnoNext);
42145
42146 #ifndef SQLITE_OMIT_AUTOVACUUM
42147   /* Try to find the next page in the overflow list using the
42148   ** autovacuum pointer-map pages. Guess that the next page in 
42149   ** the overflow list is page number (ovfl+1). If that guess turns 
42150   ** out to be wrong, fall back to loading the data of page 
42151   ** number ovfl to determine the next page number.
42152   */
42153   if( pBt->autoVacuum ){
42154     Pgno pgno;
42155     Pgno iGuess = ovfl+1;
42156     u8 eType;
42157
42158     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
42159       iGuess++;
42160     }
42161
42162     if( iGuess<=pagerPagecount(pBt) ){
42163       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
42164       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
42165         next = iGuess;
42166         rc = SQLITE_DONE;
42167       }
42168     }
42169   }
42170 #endif
42171
42172   assert( next==0 || rc==SQLITE_DONE );
42173   if( rc==SQLITE_OK ){
42174     rc = btreeGetPage(pBt, ovfl, &pPage, 0);
42175     assert( rc==SQLITE_OK || pPage==0 );
42176     if( rc==SQLITE_OK ){
42177       next = get4byte(pPage->aData);
42178     }
42179   }
42180
42181   *pPgnoNext = next;
42182   if( ppPage ){
42183     *ppPage = pPage;
42184   }else{
42185     releasePage(pPage);
42186   }
42187   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
42188 }
42189
42190 /*
42191 ** Copy data from a buffer to a page, or from a page to a buffer.
42192 **
42193 ** pPayload is a pointer to data stored on database page pDbPage.
42194 ** If argument eOp is false, then nByte bytes of data are copied
42195 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
42196 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
42197 ** of data are copied from the buffer pBuf to pPayload.
42198 **
42199 ** SQLITE_OK is returned on success, otherwise an error code.
42200 */
42201 static int copyPayload(
42202   void *pPayload,           /* Pointer to page data */
42203   void *pBuf,               /* Pointer to buffer */
42204   int nByte,                /* Number of bytes to copy */
42205   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
42206   DbPage *pDbPage           /* Page containing pPayload */
42207 ){
42208   if( eOp ){
42209     /* Copy data from buffer to page (a write operation) */
42210     int rc = sqlite3PagerWrite(pDbPage);
42211     if( rc!=SQLITE_OK ){
42212       return rc;
42213     }
42214     memcpy(pPayload, pBuf, nByte);
42215   }else{
42216     /* Copy data from page to buffer (a read operation) */
42217     memcpy(pBuf, pPayload, nByte);
42218   }
42219   return SQLITE_OK;
42220 }
42221
42222 /*
42223 ** This function is used to read or overwrite payload information
42224 ** for the entry that the pCur cursor is pointing to. If the eOp
42225 ** parameter is 0, this is a read operation (data copied into
42226 ** buffer pBuf). If it is non-zero, a write (data copied from
42227 ** buffer pBuf).
42228 **
42229 ** A total of "amt" bytes are read or written beginning at "offset".
42230 ** Data is read to or from the buffer pBuf.
42231 **
42232 ** The content being read or written might appear on the main page
42233 ** or be scattered out on multiple overflow pages.
42234 **
42235 ** If the BtCursor.isIncrblobHandle flag is set, and the current
42236 ** cursor entry uses one or more overflow pages, this function
42237 ** allocates space for and lazily popluates the overflow page-list 
42238 ** cache array (BtCursor.aOverflow). Subsequent calls use this
42239 ** cache to make seeking to the supplied offset more efficient.
42240 **
42241 ** Once an overflow page-list cache has been allocated, it may be
42242 ** invalidated if some other cursor writes to the same table, or if
42243 ** the cursor is moved to a different row. Additionally, in auto-vacuum
42244 ** mode, the following events may invalidate an overflow page-list cache.
42245 **
42246 **   * An incremental vacuum,
42247 **   * A commit in auto_vacuum="full" mode,
42248 **   * Creating a table (may require moving an overflow page).
42249 */
42250 static int accessPayload(
42251   BtCursor *pCur,      /* Cursor pointing to entry to read from */
42252   u32 offset,          /* Begin reading this far into payload */
42253   u32 amt,             /* Read this many bytes */
42254   unsigned char *pBuf, /* Write the bytes into this buffer */ 
42255   int eOp              /* zero to read. non-zero to write. */
42256 ){
42257   unsigned char *aPayload;
42258   int rc = SQLITE_OK;
42259   u32 nKey;
42260   int iIdx = 0;
42261   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
42262   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
42263
42264   assert( pPage );
42265   assert( pCur->eState==CURSOR_VALID );
42266   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
42267   assert( cursorHoldsMutex(pCur) );
42268
42269   getCellInfo(pCur);
42270   aPayload = pCur->info.pCell + pCur->info.nHeader;
42271   nKey = (pPage->intKey ? 0 : (int)pCur->info.nKey);
42272
42273   if( NEVER(offset+amt > nKey+pCur->info.nData) 
42274    || &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize]
42275   ){
42276     /* Trying to read or write past the end of the data is an error */
42277     return SQLITE_CORRUPT_BKPT;
42278   }
42279
42280   /* Check if data must be read/written to/from the btree page itself. */
42281   if( offset<pCur->info.nLocal ){
42282     int a = amt;
42283     if( a+offset>pCur->info.nLocal ){
42284       a = pCur->info.nLocal - offset;
42285     }
42286     rc = copyPayload(&aPayload[offset], pBuf, a, eOp, pPage->pDbPage);
42287     offset = 0;
42288     pBuf += a;
42289     amt -= a;
42290   }else{
42291     offset -= pCur->info.nLocal;
42292   }
42293
42294   if( rc==SQLITE_OK && amt>0 ){
42295     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
42296     Pgno nextPage;
42297
42298     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
42299
42300 #ifndef SQLITE_OMIT_INCRBLOB
42301     /* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
42302     ** has not been allocated, allocate it now. The array is sized at
42303     ** one entry for each overflow page in the overflow chain. The
42304     ** page number of the first overflow page is stored in aOverflow[0],
42305     ** etc. A value of 0 in the aOverflow[] array means "not yet known"
42306     ** (the cache is lazily populated).
42307     */
42308     if( pCur->isIncrblobHandle && !pCur->aOverflow ){
42309       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
42310       pCur->aOverflow = (Pgno *)sqlite3MallocZero(sizeof(Pgno)*nOvfl);
42311       /* nOvfl is always positive.  If it were zero, fetchPayload would have
42312       ** been used instead of this routine. */
42313       if( ALWAYS(nOvfl) && !pCur->aOverflow ){
42314         rc = SQLITE_NOMEM;
42315       }
42316     }
42317
42318     /* If the overflow page-list cache has been allocated and the
42319     ** entry for the first required overflow page is valid, skip
42320     ** directly to it.
42321     */
42322     if( pCur->aOverflow && pCur->aOverflow[offset/ovflSize] ){
42323       iIdx = (offset/ovflSize);
42324       nextPage = pCur->aOverflow[iIdx];
42325       offset = (offset%ovflSize);
42326     }
42327 #endif
42328
42329     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
42330
42331 #ifndef SQLITE_OMIT_INCRBLOB
42332       /* If required, populate the overflow page-list cache. */
42333       if( pCur->aOverflow ){
42334         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
42335         pCur->aOverflow[iIdx] = nextPage;
42336       }
42337 #endif
42338
42339       if( offset>=ovflSize ){
42340         /* The only reason to read this page is to obtain the page
42341         ** number for the next page in the overflow chain. The page
42342         ** data is not required. So first try to lookup the overflow
42343         ** page-list cache, if any, then fall back to the getOverflowPage()
42344         ** function.
42345         */
42346 #ifndef SQLITE_OMIT_INCRBLOB
42347         if( pCur->aOverflow && pCur->aOverflow[iIdx+1] ){
42348           nextPage = pCur->aOverflow[iIdx+1];
42349         } else 
42350 #endif
42351           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
42352         offset -= ovflSize;
42353       }else{
42354         /* Need to read this page properly. It contains some of the
42355         ** range of data that is being read (eOp==0) or written (eOp!=0).
42356         */
42357         DbPage *pDbPage;
42358         int a = amt;
42359         rc = sqlite3PagerGet(pBt->pPager, nextPage, &pDbPage);
42360         if( rc==SQLITE_OK ){
42361           aPayload = sqlite3PagerGetData(pDbPage);
42362           nextPage = get4byte(aPayload);
42363           if( a + offset > ovflSize ){
42364             a = ovflSize - offset;
42365           }
42366           rc = copyPayload(&aPayload[offset+4], pBuf, a, eOp, pDbPage);
42367           sqlite3PagerUnref(pDbPage);
42368           offset = 0;
42369           amt -= a;
42370           pBuf += a;
42371         }
42372       }
42373     }
42374   }
42375
42376   if( rc==SQLITE_OK && amt>0 ){
42377     return SQLITE_CORRUPT_BKPT;
42378   }
42379   return rc;
42380 }
42381
42382 /*
42383 ** Read part of the key associated with cursor pCur.  Exactly
42384 ** "amt" bytes will be transfered into pBuf[].  The transfer
42385 ** begins at "offset".
42386 **
42387 ** The caller must ensure that pCur is pointing to a valid row
42388 ** in the table.
42389 **
42390 ** Return SQLITE_OK on success or an error code if anything goes
42391 ** wrong.  An error is returned if "offset+amt" is larger than
42392 ** the available payload.
42393 */
42394 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
42395   assert( cursorHoldsMutex(pCur) );
42396   assert( pCur->eState==CURSOR_VALID );
42397   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
42398   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
42399   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
42400 }
42401
42402 /*
42403 ** Read part of the data associated with cursor pCur.  Exactly
42404 ** "amt" bytes will be transfered into pBuf[].  The transfer
42405 ** begins at "offset".
42406 **
42407 ** Return SQLITE_OK on success or an error code if anything goes
42408 ** wrong.  An error is returned if "offset+amt" is larger than
42409 ** the available payload.
42410 */
42411 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
42412   int rc;
42413
42414 #ifndef SQLITE_OMIT_INCRBLOB
42415   if ( pCur->eState==CURSOR_INVALID ){
42416     return SQLITE_ABORT;
42417   }
42418 #endif
42419
42420   assert( cursorHoldsMutex(pCur) );
42421   rc = restoreCursorPosition(pCur);
42422   if( rc==SQLITE_OK ){
42423     assert( pCur->eState==CURSOR_VALID );
42424     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
42425     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
42426     rc = accessPayload(pCur, offset, amt, pBuf, 0);
42427   }
42428   return rc;
42429 }
42430
42431 /*
42432 ** Return a pointer to payload information from the entry that the 
42433 ** pCur cursor is pointing to.  The pointer is to the beginning of
42434 ** the key if skipKey==0 and it points to the beginning of data if
42435 ** skipKey==1.  The number of bytes of available key/data is written
42436 ** into *pAmt.  If *pAmt==0, then the value returned will not be
42437 ** a valid pointer.
42438 **
42439 ** This routine is an optimization.  It is common for the entire key
42440 ** and data to fit on the local page and for there to be no overflow
42441 ** pages.  When that is so, this routine can be used to access the
42442 ** key and data without making a copy.  If the key and/or data spills
42443 ** onto overflow pages, then accessPayload() must be used to reassemble
42444 ** the key/data and copy it into a preallocated buffer.
42445 **
42446 ** The pointer returned by this routine looks directly into the cached
42447 ** page of the database.  The data might change or move the next time
42448 ** any btree routine is called.
42449 */
42450 static const unsigned char *fetchPayload(
42451   BtCursor *pCur,      /* Cursor pointing to entry to read from */
42452   int *pAmt,           /* Write the number of available bytes here */
42453   int skipKey          /* read beginning at data if this is true */
42454 ){
42455   unsigned char *aPayload;
42456   MemPage *pPage;
42457   u32 nKey;
42458   u32 nLocal;
42459
42460   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
42461   assert( pCur->eState==CURSOR_VALID );
42462   assert( cursorHoldsMutex(pCur) );
42463   pPage = pCur->apPage[pCur->iPage];
42464   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
42465   if( NEVER(pCur->info.nSize==0) ){
42466     btreeParseCell(pCur->apPage[pCur->iPage], pCur->aiIdx[pCur->iPage],
42467                    &pCur->info);
42468   }
42469   aPayload = pCur->info.pCell;
42470   aPayload += pCur->info.nHeader;
42471   if( pPage->intKey ){
42472     nKey = 0;
42473   }else{
42474     nKey = (int)pCur->info.nKey;
42475   }
42476   if( skipKey ){
42477     aPayload += nKey;
42478     nLocal = pCur->info.nLocal - nKey;
42479   }else{
42480     nLocal = pCur->info.nLocal;
42481     assert( nLocal<=nKey );
42482   }
42483   *pAmt = nLocal;
42484   return aPayload;
42485 }
42486
42487
42488 /*
42489 ** For the entry that cursor pCur is point to, return as
42490 ** many bytes of the key or data as are available on the local
42491 ** b-tree page.  Write the number of available bytes into *pAmt.
42492 **
42493 ** The pointer returned is ephemeral.  The key/data may move
42494 ** or be destroyed on the next call to any Btree routine,
42495 ** including calls from other threads against the same cache.
42496 ** Hence, a mutex on the BtShared should be held prior to calling
42497 ** this routine.
42498 **
42499 ** These routines is used to get quick access to key and data
42500 ** in the common case where no overflow pages are used.
42501 */
42502 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, int *pAmt){
42503   const void *p = 0;
42504   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
42505   assert( cursorHoldsMutex(pCur) );
42506   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
42507     p = (const void*)fetchPayload(pCur, pAmt, 0);
42508   }
42509   return p;
42510 }
42511 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, int *pAmt){
42512   const void *p = 0;
42513   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
42514   assert( cursorHoldsMutex(pCur) );
42515   if( ALWAYS(pCur->eState==CURSOR_VALID) ){
42516     p = (const void*)fetchPayload(pCur, pAmt, 1);
42517   }
42518   return p;
42519 }
42520
42521
42522 /*
42523 ** Move the cursor down to a new child page.  The newPgno argument is the
42524 ** page number of the child page to move to.
42525 **
42526 ** This function returns SQLITE_CORRUPT if the page-header flags field of
42527 ** the new child page does not match the flags field of the parent (i.e.
42528 ** if an intkey page appears to be the parent of a non-intkey page, or
42529 ** vice-versa).
42530 */
42531 static int moveToChild(BtCursor *pCur, u32 newPgno){
42532   int rc;
42533   int i = pCur->iPage;
42534   MemPage *pNewPage;
42535   BtShared *pBt = pCur->pBt;
42536
42537   assert( cursorHoldsMutex(pCur) );
42538   assert( pCur->eState==CURSOR_VALID );
42539   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
42540   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
42541     return SQLITE_CORRUPT_BKPT;
42542   }
42543   rc = getAndInitPage(pBt, newPgno, &pNewPage);
42544   if( rc ) return rc;
42545   pCur->apPage[i+1] = pNewPage;
42546   pCur->aiIdx[i+1] = 0;
42547   pCur->iPage++;
42548
42549   pCur->info.nSize = 0;
42550   pCur->validNKey = 0;
42551   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
42552     return SQLITE_CORRUPT_BKPT;
42553   }
42554   return SQLITE_OK;
42555 }
42556
42557 #ifndef NDEBUG
42558 /*
42559 ** Page pParent is an internal (non-leaf) tree page. This function 
42560 ** asserts that page number iChild is the left-child if the iIdx'th
42561 ** cell in page pParent. Or, if iIdx is equal to the total number of
42562 ** cells in pParent, that page number iChild is the right-child of
42563 ** the page.
42564 */
42565 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
42566   assert( iIdx<=pParent->nCell );
42567   if( iIdx==pParent->nCell ){
42568     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
42569   }else{
42570     assert( get4byte(findCell(pParent, iIdx))==iChild );
42571   }
42572 }
42573 #else
42574 #  define assertParentIndex(x,y,z) 
42575 #endif
42576
42577 /*
42578 ** Move the cursor up to the parent page.
42579 **
42580 ** pCur->idx is set to the cell index that contains the pointer
42581 ** to the page we are coming from.  If we are coming from the
42582 ** right-most child page then pCur->idx is set to one more than
42583 ** the largest cell index.
42584 */
42585 static void moveToParent(BtCursor *pCur){
42586   assert( cursorHoldsMutex(pCur) );
42587   assert( pCur->eState==CURSOR_VALID );
42588   assert( pCur->iPage>0 );
42589   assert( pCur->apPage[pCur->iPage] );
42590   assertParentIndex(
42591     pCur->apPage[pCur->iPage-1], 
42592     pCur->aiIdx[pCur->iPage-1], 
42593     pCur->apPage[pCur->iPage]->pgno
42594   );
42595   releasePage(pCur->apPage[pCur->iPage]);
42596   pCur->iPage--;
42597   pCur->info.nSize = 0;
42598   pCur->validNKey = 0;
42599 }
42600
42601 /*
42602 ** Move the cursor to point to the root page of its b-tree structure.
42603 **
42604 ** If the table has a virtual root page, then the cursor is moved to point
42605 ** to the virtual root page instead of the actual root page. A table has a
42606 ** virtual root page when the actual root page contains no cells and a 
42607 ** single child page. This can only happen with the table rooted at page 1.
42608 **
42609 ** If the b-tree structure is empty, the cursor state is set to 
42610 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
42611 ** cell located on the root (or virtual root) page and the cursor state
42612 ** is set to CURSOR_VALID.
42613 **
42614 ** If this function returns successfully, it may be assumed that the
42615 ** page-header flags indicate that the [virtual] root-page is the expected 
42616 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
42617 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
42618 ** indicating a table b-tree, or if the caller did specify a KeyInfo 
42619 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
42620 ** b-tree).
42621 */
42622 static int moveToRoot(BtCursor *pCur){
42623   MemPage *pRoot;
42624   int rc = SQLITE_OK;
42625   Btree *p = pCur->pBtree;
42626   BtShared *pBt = p->pBt;
42627
42628   assert( cursorHoldsMutex(pCur) );
42629   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
42630   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
42631   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
42632   if( pCur->eState>=CURSOR_REQUIRESEEK ){
42633     if( pCur->eState==CURSOR_FAULT ){
42634       assert( pCur->skipNext!=SQLITE_OK );
42635       return pCur->skipNext;
42636     }
42637     sqlite3BtreeClearCursor(pCur);
42638   }
42639
42640   if( pCur->iPage>=0 ){
42641     int i;
42642     for(i=1; i<=pCur->iPage; i++){
42643       releasePage(pCur->apPage[i]);
42644     }
42645     pCur->iPage = 0;
42646   }else{
42647     rc = getAndInitPage(pBt, pCur->pgnoRoot, &pCur->apPage[0]);
42648     if( rc!=SQLITE_OK ){
42649       pCur->eState = CURSOR_INVALID;
42650       return rc;
42651     }
42652     pCur->iPage = 0;
42653
42654     /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
42655     ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
42656     ** NULL, the caller expects a table b-tree. If this is not the case,
42657     ** return an SQLITE_CORRUPT error.  */
42658     assert( pCur->apPage[0]->intKey==1 || pCur->apPage[0]->intKey==0 );
42659     if( (pCur->pKeyInfo==0)!=pCur->apPage[0]->intKey ){
42660       return SQLITE_CORRUPT_BKPT;
42661     }
42662   }
42663
42664   /* Assert that the root page is of the correct type. This must be the
42665   ** case as the call to this function that loaded the root-page (either
42666   ** this call or a previous invocation) would have detected corruption 
42667   ** if the assumption were not true, and it is not possible for the flags 
42668   ** byte to have been modified while this cursor is holding a reference
42669   ** to the page.  */
42670   pRoot = pCur->apPage[0];
42671   assert( pRoot->pgno==pCur->pgnoRoot );
42672   assert( pRoot->isInit && (pCur->pKeyInfo==0)==pRoot->intKey );
42673
42674   pCur->aiIdx[0] = 0;
42675   pCur->info.nSize = 0;
42676   pCur->atLast = 0;
42677   pCur->validNKey = 0;
42678
42679   if( pRoot->nCell==0 && !pRoot->leaf ){
42680     Pgno subpage;
42681     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
42682     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
42683     pCur->eState = CURSOR_VALID;
42684     rc = moveToChild(pCur, subpage);
42685   }else{
42686     pCur->eState = ((pRoot->nCell>0)?CURSOR_VALID:CURSOR_INVALID);
42687   }
42688   return rc;
42689 }
42690
42691 /*
42692 ** Move the cursor down to the left-most leaf entry beneath the
42693 ** entry to which it is currently pointing.
42694 **
42695 ** The left-most leaf is the one with the smallest key - the first
42696 ** in ascending order.
42697 */
42698 static int moveToLeftmost(BtCursor *pCur){
42699   Pgno pgno;
42700   int rc = SQLITE_OK;
42701   MemPage *pPage;
42702
42703   assert( cursorHoldsMutex(pCur) );
42704   assert( pCur->eState==CURSOR_VALID );
42705   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
42706     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
42707     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
42708     rc = moveToChild(pCur, pgno);
42709   }
42710   return rc;
42711 }
42712
42713 /*
42714 ** Move the cursor down to the right-most leaf entry beneath the
42715 ** page to which it is currently pointing.  Notice the difference
42716 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
42717 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
42718 ** finds the right-most entry beneath the *page*.
42719 **
42720 ** The right-most entry is the one with the largest key - the last
42721 ** key in ascending order.
42722 */
42723 static int moveToRightmost(BtCursor *pCur){
42724   Pgno pgno;
42725   int rc = SQLITE_OK;
42726   MemPage *pPage = 0;
42727
42728   assert( cursorHoldsMutex(pCur) );
42729   assert( pCur->eState==CURSOR_VALID );
42730   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
42731     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
42732     pCur->aiIdx[pCur->iPage] = pPage->nCell;
42733     rc = moveToChild(pCur, pgno);
42734   }
42735   if( rc==SQLITE_OK ){
42736     pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
42737     pCur->info.nSize = 0;
42738     pCur->validNKey = 0;
42739   }
42740   return rc;
42741 }
42742
42743 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
42744 ** on success.  Set *pRes to 0 if the cursor actually points to something
42745 ** or set *pRes to 1 if the table is empty.
42746 */
42747 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
42748   int rc;
42749
42750   assert( cursorHoldsMutex(pCur) );
42751   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
42752   rc = moveToRoot(pCur);
42753   if( rc==SQLITE_OK ){
42754     if( pCur->eState==CURSOR_INVALID ){
42755       assert( pCur->apPage[pCur->iPage]->nCell==0 );
42756       *pRes = 1;
42757       rc = SQLITE_OK;
42758     }else{
42759       assert( pCur->apPage[pCur->iPage]->nCell>0 );
42760       *pRes = 0;
42761       rc = moveToLeftmost(pCur);
42762     }
42763   }
42764   return rc;
42765 }
42766
42767 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
42768 ** on success.  Set *pRes to 0 if the cursor actually points to something
42769 ** or set *pRes to 1 if the table is empty.
42770 */
42771 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
42772   int rc;
42773  
42774   assert( cursorHoldsMutex(pCur) );
42775   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
42776
42777   /* If the cursor already points to the last entry, this is a no-op. */
42778   if( CURSOR_VALID==pCur->eState && pCur->atLast ){
42779 #ifdef SQLITE_DEBUG
42780     /* This block serves to assert() that the cursor really does point 
42781     ** to the last entry in the b-tree. */
42782     int ii;
42783     for(ii=0; ii<pCur->iPage; ii++){
42784       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
42785     }
42786     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
42787     assert( pCur->apPage[pCur->iPage]->leaf );
42788 #endif
42789     return SQLITE_OK;
42790   }
42791
42792   rc = moveToRoot(pCur);
42793   if( rc==SQLITE_OK ){
42794     if( CURSOR_INVALID==pCur->eState ){
42795       assert( pCur->apPage[pCur->iPage]->nCell==0 );
42796       *pRes = 1;
42797     }else{
42798       assert( pCur->eState==CURSOR_VALID );
42799       *pRes = 0;
42800       rc = moveToRightmost(pCur);
42801       pCur->atLast = rc==SQLITE_OK ?1:0;
42802     }
42803   }
42804   return rc;
42805 }
42806
42807 /* Move the cursor so that it points to an entry near the key 
42808 ** specified by pIdxKey or intKey.   Return a success code.
42809 **
42810 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
42811 ** must be NULL.  For index tables, pIdxKey is used and intKey
42812 ** is ignored.
42813 **
42814 ** If an exact match is not found, then the cursor is always
42815 ** left pointing at a leaf page which would hold the entry if it
42816 ** were present.  The cursor might point to an entry that comes
42817 ** before or after the key.
42818 **
42819 ** An integer is written into *pRes which is the result of
42820 ** comparing the key with the entry to which the cursor is 
42821 ** pointing.  The meaning of the integer written into
42822 ** *pRes is as follows:
42823 **
42824 **     *pRes<0      The cursor is left pointing at an entry that
42825 **                  is smaller than intKey/pIdxKey or if the table is empty
42826 **                  and the cursor is therefore left point to nothing.
42827 **
42828 **     *pRes==0     The cursor is left pointing at an entry that
42829 **                  exactly matches intKey/pIdxKey.
42830 **
42831 **     *pRes>0      The cursor is left pointing at an entry that
42832 **                  is larger than intKey/pIdxKey.
42833 **
42834 */
42835 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
42836   BtCursor *pCur,          /* The cursor to be moved */
42837   UnpackedRecord *pIdxKey, /* Unpacked index key */
42838   i64 intKey,              /* The table key */
42839   int biasRight,           /* If true, bias the search to the high end */
42840   int *pRes                /* Write search results here */
42841 ){
42842   int rc;
42843
42844   assert( cursorHoldsMutex(pCur) );
42845   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
42846   assert( pRes );
42847   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
42848
42849   /* If the cursor is already positioned at the point we are trying
42850   ** to move to, then just return without doing any work */
42851   if( pCur->eState==CURSOR_VALID && pCur->validNKey 
42852    && pCur->apPage[0]->intKey 
42853   ){
42854     if( pCur->info.nKey==intKey ){
42855       *pRes = 0;
42856       return SQLITE_OK;
42857     }
42858     if( pCur->atLast && pCur->info.nKey<intKey ){
42859       *pRes = -1;
42860       return SQLITE_OK;
42861     }
42862   }
42863
42864   rc = moveToRoot(pCur);
42865   if( rc ){
42866     return rc;
42867   }
42868   assert( pCur->apPage[pCur->iPage] );
42869   assert( pCur->apPage[pCur->iPage]->isInit );
42870   assert( pCur->apPage[pCur->iPage]->nCell>0 || pCur->eState==CURSOR_INVALID );
42871   if( pCur->eState==CURSOR_INVALID ){
42872     *pRes = -1;
42873     assert( pCur->apPage[pCur->iPage]->nCell==0 );
42874     return SQLITE_OK;
42875   }
42876   assert( pCur->apPage[0]->intKey || pIdxKey );
42877   for(;;){
42878     int lwr, upr;
42879     Pgno chldPg;
42880     MemPage *pPage = pCur->apPage[pCur->iPage];
42881     int c;
42882
42883     /* pPage->nCell must be greater than zero. If this is the root-page
42884     ** the cursor would have been INVALID above and this for(;;) loop
42885     ** not run. If this is not the root-page, then the moveToChild() routine
42886     ** would have already detected db corruption. Similarly, pPage must
42887     ** be the right kind (index or table) of b-tree page. Otherwise
42888     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
42889     assert( pPage->nCell>0 );
42890     assert( pPage->intKey==(pIdxKey==0) );
42891     lwr = 0;
42892     upr = pPage->nCell-1;
42893     if( biasRight ){
42894       pCur->aiIdx[pCur->iPage] = (u16)upr;
42895     }else{
42896       pCur->aiIdx[pCur->iPage] = (u16)((upr+lwr)/2);
42897     }
42898     for(;;){
42899       int idx = pCur->aiIdx[pCur->iPage]; /* Index of current cell in pPage */
42900       u8 *pCell;                          /* Pointer to current cell in pPage */
42901
42902       pCur->info.nSize = 0;
42903       pCell = findCell(pPage, idx) + pPage->childPtrSize;
42904       if( pPage->intKey ){
42905         i64 nCellKey;
42906         if( pPage->hasData ){
42907           u32 dummy;
42908           pCell += getVarint32(pCell, dummy);
42909         }
42910         getVarint(pCell, (u64*)&nCellKey);
42911         if( nCellKey==intKey ){
42912           c = 0;
42913         }else if( nCellKey<intKey ){
42914           c = -1;
42915         }else{
42916           assert( nCellKey>intKey );
42917           c = +1;
42918         }
42919         pCur->validNKey = 1;
42920         pCur->info.nKey = nCellKey;
42921       }else{
42922         /* The maximum supported page-size is 32768 bytes. This means that
42923         ** the maximum number of record bytes stored on an index B-Tree
42924         ** page is at most 8198 bytes, which may be stored as a 2-byte
42925         ** varint. This information is used to attempt to avoid parsing 
42926         ** the entire cell by checking for the cases where the record is 
42927         ** stored entirely within the b-tree page by inspecting the first 
42928         ** 2 bytes of the cell.
42929         */
42930         int nCell = pCell[0];
42931         if( !(nCell & 0x80) && nCell<=pPage->maxLocal ){
42932           /* This branch runs if the record-size field of the cell is a
42933           ** single byte varint and the record fits entirely on the main
42934           ** b-tree page.  */
42935           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
42936         }else if( !(pCell[1] & 0x80) 
42937           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
42938         ){
42939           /* The record-size field is a 2 byte varint and the record 
42940           ** fits entirely on the main b-tree page.  */
42941           c = sqlite3VdbeRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
42942         }else{
42943           /* The record flows over onto one or more overflow pages. In
42944           ** this case the whole cell needs to be parsed, a buffer allocated
42945           ** and accessPayload() used to retrieve the record into the
42946           ** buffer before VdbeRecordCompare() can be called. */
42947           void *pCellKey;
42948           u8 * const pCellBody = pCell - pPage->childPtrSize;
42949           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
42950           nCell = (int)pCur->info.nKey;
42951           pCellKey = sqlite3Malloc( nCell );
42952           if( pCellKey==0 ){
42953             rc = SQLITE_NOMEM;
42954             goto moveto_finish;
42955           }
42956           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 0);
42957           if( rc ){
42958             sqlite3_free(pCellKey);
42959             goto moveto_finish;
42960           }
42961           c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
42962           sqlite3_free(pCellKey);
42963         }
42964       }
42965       if( c==0 ){
42966         if( pPage->intKey && !pPage->leaf ){
42967           lwr = idx;
42968           upr = lwr - 1;
42969           break;
42970         }else{
42971           *pRes = 0;
42972           rc = SQLITE_OK;
42973           goto moveto_finish;
42974         }
42975       }
42976       if( c<0 ){
42977         lwr = idx+1;
42978       }else{
42979         upr = idx-1;
42980       }
42981       if( lwr>upr ){
42982         break;
42983       }
42984       pCur->aiIdx[pCur->iPage] = (u16)((lwr+upr)/2);
42985     }
42986     assert( lwr==upr+1 );
42987     assert( pPage->isInit );
42988     if( pPage->leaf ){
42989       chldPg = 0;
42990     }else if( lwr>=pPage->nCell ){
42991       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
42992     }else{
42993       chldPg = get4byte(findCell(pPage, lwr));
42994     }
42995     if( chldPg==0 ){
42996       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
42997       *pRes = c;
42998       rc = SQLITE_OK;
42999       goto moveto_finish;
43000     }
43001     pCur->aiIdx[pCur->iPage] = (u16)lwr;
43002     pCur->info.nSize = 0;
43003     pCur->validNKey = 0;
43004     rc = moveToChild(pCur, chldPg);
43005     if( rc ) goto moveto_finish;
43006   }
43007 moveto_finish:
43008   return rc;
43009 }
43010
43011
43012 /*
43013 ** Return TRUE if the cursor is not pointing at an entry of the table.
43014 **
43015 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
43016 ** past the last entry in the table or sqlite3BtreePrev() moves past
43017 ** the first entry.  TRUE is also returned if the table is empty.
43018 */
43019 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
43020   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
43021   ** have been deleted? This API will need to change to return an error code
43022   ** as well as the boolean result value.
43023   */
43024   return (CURSOR_VALID!=pCur->eState);
43025 }
43026
43027 /*
43028 ** Advance the cursor to the next entry in the database.  If
43029 ** successful then set *pRes=0.  If the cursor
43030 ** was already pointing to the last entry in the database before
43031 ** this routine was called, then set *pRes=1.
43032 */
43033 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
43034   int rc;
43035   int idx;
43036   MemPage *pPage;
43037
43038   assert( cursorHoldsMutex(pCur) );
43039   rc = restoreCursorPosition(pCur);
43040   if( rc!=SQLITE_OK ){
43041     return rc;
43042   }
43043   assert( pRes!=0 );
43044   if( CURSOR_INVALID==pCur->eState ){
43045     *pRes = 1;
43046     return SQLITE_OK;
43047   }
43048   if( pCur->skipNext>0 ){
43049     pCur->skipNext = 0;
43050     *pRes = 0;
43051     return SQLITE_OK;
43052   }
43053   pCur->skipNext = 0;
43054
43055   pPage = pCur->apPage[pCur->iPage];
43056   idx = ++pCur->aiIdx[pCur->iPage];
43057   assert( pPage->isInit );
43058   assert( idx<=pPage->nCell );
43059
43060   pCur->info.nSize = 0;
43061   pCur->validNKey = 0;
43062   if( idx>=pPage->nCell ){
43063     if( !pPage->leaf ){
43064       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
43065       if( rc ) return rc;
43066       rc = moveToLeftmost(pCur);
43067       *pRes = 0;
43068       return rc;
43069     }
43070     do{
43071       if( pCur->iPage==0 ){
43072         *pRes = 1;
43073         pCur->eState = CURSOR_INVALID;
43074         return SQLITE_OK;
43075       }
43076       moveToParent(pCur);
43077       pPage = pCur->apPage[pCur->iPage];
43078     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
43079     *pRes = 0;
43080     if( pPage->intKey ){
43081       rc = sqlite3BtreeNext(pCur, pRes);
43082     }else{
43083       rc = SQLITE_OK;
43084     }
43085     return rc;
43086   }
43087   *pRes = 0;
43088   if( pPage->leaf ){
43089     return SQLITE_OK;
43090   }
43091   rc = moveToLeftmost(pCur);
43092   return rc;
43093 }
43094
43095
43096 /*
43097 ** Step the cursor to the back to the previous entry in the database.  If
43098 ** successful then set *pRes=0.  If the cursor
43099 ** was already pointing to the first entry in the database before
43100 ** this routine was called, then set *pRes=1.
43101 */
43102 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
43103   int rc;
43104   MemPage *pPage;
43105
43106   assert( cursorHoldsMutex(pCur) );
43107   rc = restoreCursorPosition(pCur);
43108   if( rc!=SQLITE_OK ){
43109     return rc;
43110   }
43111   pCur->atLast = 0;
43112   if( CURSOR_INVALID==pCur->eState ){
43113     *pRes = 1;
43114     return SQLITE_OK;
43115   }
43116   if( pCur->skipNext<0 ){
43117     pCur->skipNext = 0;
43118     *pRes = 0;
43119     return SQLITE_OK;
43120   }
43121   pCur->skipNext = 0;
43122
43123   pPage = pCur->apPage[pCur->iPage];
43124   assert( pPage->isInit );
43125   if( !pPage->leaf ){
43126     int idx = pCur->aiIdx[pCur->iPage];
43127     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
43128     if( rc ){
43129       return rc;
43130     }
43131     rc = moveToRightmost(pCur);
43132   }else{
43133     while( pCur->aiIdx[pCur->iPage]==0 ){
43134       if( pCur->iPage==0 ){
43135         pCur->eState = CURSOR_INVALID;
43136         *pRes = 1;
43137         return SQLITE_OK;
43138       }
43139       moveToParent(pCur);
43140     }
43141     pCur->info.nSize = 0;
43142     pCur->validNKey = 0;
43143
43144     pCur->aiIdx[pCur->iPage]--;
43145     pPage = pCur->apPage[pCur->iPage];
43146     if( pPage->intKey && !pPage->leaf ){
43147       rc = sqlite3BtreePrevious(pCur, pRes);
43148     }else{
43149       rc = SQLITE_OK;
43150     }
43151   }
43152   *pRes = 0;
43153   return rc;
43154 }
43155
43156 /*
43157 ** Allocate a new page from the database file.
43158 **
43159 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
43160 ** has already been called on the new page.)  The new page has also
43161 ** been referenced and the calling routine is responsible for calling
43162 ** sqlite3PagerUnref() on the new page when it is done.
43163 **
43164 ** SQLITE_OK is returned on success.  Any other return value indicates
43165 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
43166 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
43167 **
43168 ** If the "nearby" parameter is not 0, then a (feeble) effort is made to 
43169 ** locate a page close to the page number "nearby".  This can be used in an
43170 ** attempt to keep related pages close to each other in the database file,
43171 ** which in turn can make database access faster.
43172 **
43173 ** If the "exact" parameter is not 0, and the page-number nearby exists 
43174 ** anywhere on the free-list, then it is guarenteed to be returned. This
43175 ** is only used by auto-vacuum databases when allocating a new table.
43176 */
43177 static int allocateBtreePage(
43178   BtShared *pBt, 
43179   MemPage **ppPage, 
43180   Pgno *pPgno, 
43181   Pgno nearby,
43182   u8 exact
43183 ){
43184   MemPage *pPage1;
43185   int rc;
43186   u32 n;     /* Number of pages on the freelist */
43187   u32 k;     /* Number of leaves on the trunk of the freelist */
43188   MemPage *pTrunk = 0;
43189   MemPage *pPrevTrunk = 0;
43190   Pgno mxPage;     /* Total size of the database file */
43191
43192   assert( sqlite3_mutex_held(pBt->mutex) );
43193   pPage1 = pBt->pPage1;
43194   mxPage = pagerPagecount(pBt);
43195   n = get4byte(&pPage1->aData[36]);
43196   testcase( n==mxPage-1 );
43197   if( n>=mxPage ){
43198     return SQLITE_CORRUPT_BKPT;
43199   }
43200   if( n>0 ){
43201     /* There are pages on the freelist.  Reuse one of those pages. */
43202     Pgno iTrunk;
43203     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
43204     
43205     /* If the 'exact' parameter was true and a query of the pointer-map
43206     ** shows that the page 'nearby' is somewhere on the free-list, then
43207     ** the entire-list will be searched for that page.
43208     */
43209 #ifndef SQLITE_OMIT_AUTOVACUUM
43210     if( exact && nearby<=mxPage ){
43211       u8 eType;
43212       assert( nearby>0 );
43213       assert( pBt->autoVacuum );
43214       rc = ptrmapGet(pBt, nearby, &eType, 0);
43215       if( rc ) return rc;
43216       if( eType==PTRMAP_FREEPAGE ){
43217         searchList = 1;
43218       }
43219       *pPgno = nearby;
43220     }
43221 #endif
43222
43223     /* Decrement the free-list count by 1. Set iTrunk to the index of the
43224     ** first free-list trunk page. iPrevTrunk is initially 1.
43225     */
43226     rc = sqlite3PagerWrite(pPage1->pDbPage);
43227     if( rc ) return rc;
43228     put4byte(&pPage1->aData[36], n-1);
43229
43230     /* The code within this loop is run only once if the 'searchList' variable
43231     ** is not true. Otherwise, it runs once for each trunk-page on the
43232     ** free-list until the page 'nearby' is located.
43233     */
43234     do {
43235       pPrevTrunk = pTrunk;
43236       if( pPrevTrunk ){
43237         iTrunk = get4byte(&pPrevTrunk->aData[0]);
43238       }else{
43239         iTrunk = get4byte(&pPage1->aData[32]);
43240       }
43241       testcase( iTrunk==mxPage );
43242       if( iTrunk>mxPage ){
43243         rc = SQLITE_CORRUPT_BKPT;
43244       }else{
43245         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
43246       }
43247       if( rc ){
43248         pTrunk = 0;
43249         goto end_allocate_page;
43250       }
43251
43252       k = get4byte(&pTrunk->aData[4]);
43253       if( k==0 && !searchList ){
43254         /* The trunk has no leaves and the list is not being searched. 
43255         ** So extract the trunk page itself and use it as the newly 
43256         ** allocated page */
43257         assert( pPrevTrunk==0 );
43258         rc = sqlite3PagerWrite(pTrunk->pDbPage);
43259         if( rc ){
43260           goto end_allocate_page;
43261         }
43262         *pPgno = iTrunk;
43263         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
43264         *ppPage = pTrunk;
43265         pTrunk = 0;
43266         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
43267       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
43268         /* Value of k is out of range.  Database corruption */
43269         rc = SQLITE_CORRUPT_BKPT;
43270         goto end_allocate_page;
43271 #ifndef SQLITE_OMIT_AUTOVACUUM
43272       }else if( searchList && nearby==iTrunk ){
43273         /* The list is being searched and this trunk page is the page
43274         ** to allocate, regardless of whether it has leaves.
43275         */
43276         assert( *pPgno==iTrunk );
43277         *ppPage = pTrunk;
43278         searchList = 0;
43279         rc = sqlite3PagerWrite(pTrunk->pDbPage);
43280         if( rc ){
43281           goto end_allocate_page;
43282         }
43283         if( k==0 ){
43284           if( !pPrevTrunk ){
43285             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
43286           }else{
43287             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
43288           }
43289         }else{
43290           /* The trunk page is required by the caller but it contains 
43291           ** pointers to free-list leaves. The first leaf becomes a trunk
43292           ** page in this case.
43293           */
43294           MemPage *pNewTrunk;
43295           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
43296           if( iNewTrunk>mxPage ){ 
43297             rc = SQLITE_CORRUPT_BKPT;
43298             goto end_allocate_page;
43299           }
43300           testcase( iNewTrunk==mxPage );
43301           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
43302           if( rc!=SQLITE_OK ){
43303             goto end_allocate_page;
43304           }
43305           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
43306           if( rc!=SQLITE_OK ){
43307             releasePage(pNewTrunk);
43308             goto end_allocate_page;
43309           }
43310           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
43311           put4byte(&pNewTrunk->aData[4], k-1);
43312           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
43313           releasePage(pNewTrunk);
43314           if( !pPrevTrunk ){
43315             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
43316             put4byte(&pPage1->aData[32], iNewTrunk);
43317           }else{
43318             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
43319             if( rc ){
43320               goto end_allocate_page;
43321             }
43322             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
43323           }
43324         }
43325         pTrunk = 0;
43326         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
43327 #endif
43328       }else if( k>0 ){
43329         /* Extract a leaf from the trunk */
43330         u32 closest;
43331         Pgno iPage;
43332         unsigned char *aData = pTrunk->aData;
43333         rc = sqlite3PagerWrite(pTrunk->pDbPage);
43334         if( rc ){
43335           goto end_allocate_page;
43336         }
43337         if( nearby>0 ){
43338           u32 i;
43339           int dist;
43340           closest = 0;
43341           dist = get4byte(&aData[8]) - nearby;
43342           if( dist<0 ) dist = -dist;
43343           for(i=1; i<k; i++){
43344             int d2 = get4byte(&aData[8+i*4]) - nearby;
43345             if( d2<0 ) d2 = -d2;
43346             if( d2<dist ){
43347               closest = i;
43348               dist = d2;
43349             }
43350           }
43351         }else{
43352           closest = 0;
43353         }
43354
43355         iPage = get4byte(&aData[8+closest*4]);
43356         testcase( iPage==mxPage );
43357         if( iPage>mxPage ){
43358           rc = SQLITE_CORRUPT_BKPT;
43359           goto end_allocate_page;
43360         }
43361         testcase( iPage==mxPage );
43362         if( !searchList || iPage==nearby ){
43363           int noContent;
43364           *pPgno = iPage;
43365           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
43366                  ": %d more free pages\n",
43367                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
43368           if( closest<k-1 ){
43369             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
43370           }
43371           put4byte(&aData[4], k-1);
43372           assert( sqlite3PagerIswriteable(pTrunk->pDbPage) );
43373           noContent = !btreeGetHasContent(pBt, *pPgno);
43374           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
43375           if( rc==SQLITE_OK ){
43376             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
43377             if( rc!=SQLITE_OK ){
43378               releasePage(*ppPage);
43379             }
43380           }
43381           searchList = 0;
43382         }
43383       }
43384       releasePage(pPrevTrunk);
43385       pPrevTrunk = 0;
43386     }while( searchList );
43387   }else{
43388     /* There are no pages on the freelist, so create a new page at the
43389     ** end of the file */
43390     int nPage = pagerPagecount(pBt);
43391     *pPgno = nPage + 1;
43392
43393     if( *pPgno==PENDING_BYTE_PAGE(pBt) ){
43394       (*pPgno)++;
43395     }
43396
43397 #ifndef SQLITE_OMIT_AUTOVACUUM
43398     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, *pPgno) ){
43399       /* If *pPgno refers to a pointer-map page, allocate two new pages
43400       ** at the end of the file instead of one. The first allocated page
43401       ** becomes a new pointer-map page, the second is used by the caller.
43402       */
43403       MemPage *pPg = 0;
43404       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", *pPgno));
43405       assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
43406       rc = btreeGetPage(pBt, *pPgno, &pPg, 0);
43407       if( rc==SQLITE_OK ){
43408         rc = sqlite3PagerWrite(pPg->pDbPage);
43409         releasePage(pPg);
43410       }
43411       if( rc ) return rc;
43412       (*pPgno)++;
43413       if( *pPgno==PENDING_BYTE_PAGE(pBt) ){ (*pPgno)++; }
43414     }
43415 #endif
43416
43417     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
43418     rc = btreeGetPage(pBt, *pPgno, ppPage, 0);
43419     if( rc ) return rc;
43420     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
43421     if( rc!=SQLITE_OK ){
43422       releasePage(*ppPage);
43423     }
43424     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
43425   }
43426
43427   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
43428
43429 end_allocate_page:
43430   releasePage(pTrunk);
43431   releasePage(pPrevTrunk);
43432   if( rc==SQLITE_OK ){
43433     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
43434       releasePage(*ppPage);
43435       return SQLITE_CORRUPT_BKPT;
43436     }
43437     (*ppPage)->isInit = 0;
43438   }else{
43439     *ppPage = 0;
43440   }
43441   return rc;
43442 }
43443
43444 /*
43445 ** This function is used to add page iPage to the database file free-list. 
43446 ** It is assumed that the page is not already a part of the free-list.
43447 **
43448 ** The value passed as the second argument to this function is optional.
43449 ** If the caller happens to have a pointer to the MemPage object 
43450 ** corresponding to page iPage handy, it may pass it as the second value. 
43451 ** Otherwise, it may pass NULL.
43452 **
43453 ** If a pointer to a MemPage object is passed as the second argument,
43454 ** its reference count is not altered by this function.
43455 */
43456 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
43457   MemPage *pTrunk = 0;                /* Free-list trunk page */
43458   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
43459   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
43460   MemPage *pPage;                     /* Page being freed. May be NULL. */
43461   int rc;                             /* Return Code */
43462   int nFree;                          /* Initial number of pages on free-list */
43463
43464   assert( sqlite3_mutex_held(pBt->mutex) );
43465   assert( iPage>1 );
43466   assert( !pMemPage || pMemPage->pgno==iPage );
43467
43468   if( pMemPage ){
43469     pPage = pMemPage;
43470     sqlite3PagerRef(pPage->pDbPage);
43471   }else{
43472     pPage = btreePageLookup(pBt, iPage);
43473   }
43474
43475   /* Increment the free page count on pPage1 */
43476   rc = sqlite3PagerWrite(pPage1->pDbPage);
43477   if( rc ) goto freepage_out;
43478   nFree = get4byte(&pPage1->aData[36]);
43479   put4byte(&pPage1->aData[36], nFree+1);
43480
43481   if( pBt->secureDelete ){
43482     /* If the secure_delete option is enabled, then
43483     ** always fully overwrite deleted information with zeros.
43484     */
43485     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
43486      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
43487     ){
43488       goto freepage_out;
43489     }
43490     memset(pPage->aData, 0, pPage->pBt->pageSize);
43491   }
43492
43493   /* If the database supports auto-vacuum, write an entry in the pointer-map
43494   ** to indicate that the page is free.
43495   */
43496   if( ISAUTOVACUUM ){
43497     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
43498     if( rc ) goto freepage_out;
43499   }
43500
43501   /* Now manipulate the actual database free-list structure. There are two
43502   ** possibilities. If the free-list is currently empty, or if the first
43503   ** trunk page in the free-list is full, then this page will become a
43504   ** new free-list trunk page. Otherwise, it will become a leaf of the
43505   ** first trunk page in the current free-list. This block tests if it
43506   ** is possible to add the page as a new free-list leaf.
43507   */
43508   if( nFree!=0 ){
43509     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
43510
43511     iTrunk = get4byte(&pPage1->aData[32]);
43512     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
43513     if( rc!=SQLITE_OK ){
43514       goto freepage_out;
43515     }
43516
43517     nLeaf = get4byte(&pTrunk->aData[4]);
43518     assert( pBt->usableSize>32 );
43519     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
43520       rc = SQLITE_CORRUPT_BKPT;
43521       goto freepage_out;
43522     }
43523     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
43524       /* In this case there is room on the trunk page to insert the page
43525       ** being freed as a new leaf.
43526       **
43527       ** Note that the trunk page is not really full until it contains
43528       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
43529       ** coded.  But due to a coding error in versions of SQLite prior to
43530       ** 3.6.0, databases with freelist trunk pages holding more than
43531       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
43532       ** to maintain backwards compatibility with older versions of SQLite,
43533       ** we will continue to restrict the number of entries to usableSize/4 - 8
43534       ** for now.  At some point in the future (once everyone has upgraded
43535       ** to 3.6.0 or later) we should consider fixing the conditional above
43536       ** to read "usableSize/4-2" instead of "usableSize/4-8".
43537       */
43538       rc = sqlite3PagerWrite(pTrunk->pDbPage);
43539       if( rc==SQLITE_OK ){
43540         put4byte(&pTrunk->aData[4], nLeaf+1);
43541         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
43542         if( pPage && !pBt->secureDelete ){
43543           sqlite3PagerDontWrite(pPage->pDbPage);
43544         }
43545         rc = btreeSetHasContent(pBt, iPage);
43546       }
43547       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
43548       goto freepage_out;
43549     }
43550   }
43551
43552   /* If control flows to this point, then it was not possible to add the
43553   ** the page being freed as a leaf page of the first trunk in the free-list.
43554   ** Possibly because the free-list is empty, or possibly because the 
43555   ** first trunk in the free-list is full. Either way, the page being freed
43556   ** will become the new first trunk page in the free-list.
43557   */
43558   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
43559     goto freepage_out;
43560   }
43561   rc = sqlite3PagerWrite(pPage->pDbPage);
43562   if( rc!=SQLITE_OK ){
43563     goto freepage_out;
43564   }
43565   put4byte(pPage->aData, iTrunk);
43566   put4byte(&pPage->aData[4], 0);
43567   put4byte(&pPage1->aData[32], iPage);
43568   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
43569
43570 freepage_out:
43571   if( pPage ){
43572     pPage->isInit = 0;
43573   }
43574   releasePage(pPage);
43575   releasePage(pTrunk);
43576   return rc;
43577 }
43578 static void freePage(MemPage *pPage, int *pRC){
43579   if( (*pRC)==SQLITE_OK ){
43580     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
43581   }
43582 }
43583
43584 /*
43585 ** Free any overflow pages associated with the given Cell.
43586 */
43587 static int clearCell(MemPage *pPage, unsigned char *pCell){
43588   BtShared *pBt = pPage->pBt;
43589   CellInfo info;
43590   Pgno ovflPgno;
43591   int rc;
43592   int nOvfl;
43593   u16 ovflPageSize;
43594
43595   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
43596   btreeParseCellPtr(pPage, pCell, &info);
43597   if( info.iOverflow==0 ){
43598     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
43599   }
43600   ovflPgno = get4byte(&pCell[info.iOverflow]);
43601   assert( pBt->usableSize > 4 );
43602   ovflPageSize = pBt->usableSize - 4;
43603   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
43604   assert( ovflPgno==0 || nOvfl>0 );
43605   while( nOvfl-- ){
43606     Pgno iNext = 0;
43607     MemPage *pOvfl = 0;
43608     if( ovflPgno<2 || ovflPgno>pagerPagecount(pBt) ){
43609       /* 0 is not a legal page number and page 1 cannot be an 
43610       ** overflow page. Therefore if ovflPgno<2 or past the end of the 
43611       ** file the database must be corrupt. */
43612       return SQLITE_CORRUPT_BKPT;
43613     }
43614     if( nOvfl ){
43615       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
43616       if( rc ) return rc;
43617     }
43618
43619     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
43620      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
43621     ){
43622       /* There is no reason any cursor should have an outstanding reference 
43623       ** to an overflow page belonging to a cell that is being deleted/updated.
43624       ** So if there exists more than one reference to this page, then it 
43625       ** must not really be an overflow page and the database must be corrupt. 
43626       ** It is helpful to detect this before calling freePage2(), as 
43627       ** freePage2() may zero the page contents if secure-delete mode is
43628       ** enabled. If this 'overflow' page happens to be a page that the
43629       ** caller is iterating through or using in some other way, this
43630       ** can be problematic.
43631       */
43632       rc = SQLITE_CORRUPT_BKPT;
43633     }else{
43634       rc = freePage2(pBt, pOvfl, ovflPgno);
43635     }
43636
43637     if( pOvfl ){
43638       sqlite3PagerUnref(pOvfl->pDbPage);
43639     }
43640     if( rc ) return rc;
43641     ovflPgno = iNext;
43642   }
43643   return SQLITE_OK;
43644 }
43645
43646 /*
43647 ** Create the byte sequence used to represent a cell on page pPage
43648 ** and write that byte sequence into pCell[].  Overflow pages are
43649 ** allocated and filled in as necessary.  The calling procedure
43650 ** is responsible for making sure sufficient space has been allocated
43651 ** for pCell[].
43652 **
43653 ** Note that pCell does not necessary need to point to the pPage->aData
43654 ** area.  pCell might point to some temporary storage.  The cell will
43655 ** be constructed in this temporary area then copied into pPage->aData
43656 ** later.
43657 */
43658 static int fillInCell(
43659   MemPage *pPage,                /* The page that contains the cell */
43660   unsigned char *pCell,          /* Complete text of the cell */
43661   const void *pKey, i64 nKey,    /* The key */
43662   const void *pData,int nData,   /* The data */
43663   int nZero,                     /* Extra zero bytes to append to pData */
43664   int *pnSize                    /* Write cell size here */
43665 ){
43666   int nPayload;
43667   const u8 *pSrc;
43668   int nSrc, n, rc;
43669   int spaceLeft;
43670   MemPage *pOvfl = 0;
43671   MemPage *pToRelease = 0;
43672   unsigned char *pPrior;
43673   unsigned char *pPayload;
43674   BtShared *pBt = pPage->pBt;
43675   Pgno pgnoOvfl = 0;
43676   int nHeader;
43677   CellInfo info;
43678
43679   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
43680
43681   /* pPage is not necessarily writeable since pCell might be auxiliary
43682   ** buffer space that is separate from the pPage buffer area */
43683   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
43684             || sqlite3PagerIswriteable(pPage->pDbPage) );
43685
43686   /* Fill in the header. */
43687   nHeader = 0;
43688   if( !pPage->leaf ){
43689     nHeader += 4;
43690   }
43691   if( pPage->hasData ){
43692     nHeader += putVarint(&pCell[nHeader], nData+nZero);
43693   }else{
43694     nData = nZero = 0;
43695   }
43696   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
43697   btreeParseCellPtr(pPage, pCell, &info);
43698   assert( info.nHeader==nHeader );
43699   assert( info.nKey==nKey );
43700   assert( info.nData==(u32)(nData+nZero) );
43701   
43702   /* Fill in the payload */
43703   nPayload = nData + nZero;
43704   if( pPage->intKey ){
43705     pSrc = pData;
43706     nSrc = nData;
43707     nData = 0;
43708   }else{ 
43709     if( NEVER(nKey>0x7fffffff || pKey==0) ){
43710       return SQLITE_CORRUPT_BKPT;
43711     }
43712     nPayload += (int)nKey;
43713     pSrc = pKey;
43714     nSrc = (int)nKey;
43715   }
43716   *pnSize = info.nSize;
43717   spaceLeft = info.nLocal;
43718   pPayload = &pCell[nHeader];
43719   pPrior = &pCell[info.iOverflow];
43720
43721   while( nPayload>0 ){
43722     if( spaceLeft==0 ){
43723 #ifndef SQLITE_OMIT_AUTOVACUUM
43724       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
43725       if( pBt->autoVacuum ){
43726         do{
43727           pgnoOvfl++;
43728         } while( 
43729           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
43730         );
43731       }
43732 #endif
43733       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
43734 #ifndef SQLITE_OMIT_AUTOVACUUM
43735       /* If the database supports auto-vacuum, and the second or subsequent
43736       ** overflow page is being allocated, add an entry to the pointer-map
43737       ** for that page now. 
43738       **
43739       ** If this is the first overflow page, then write a partial entry 
43740       ** to the pointer-map. If we write nothing to this pointer-map slot,
43741       ** then the optimistic overflow chain processing in clearCell()
43742       ** may misinterpret the uninitialised values and delete the
43743       ** wrong pages from the database.
43744       */
43745       if( pBt->autoVacuum && rc==SQLITE_OK ){
43746         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
43747         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
43748         if( rc ){
43749           releasePage(pOvfl);
43750         }
43751       }
43752 #endif
43753       if( rc ){
43754         releasePage(pToRelease);
43755         return rc;
43756       }
43757
43758       /* If pToRelease is not zero than pPrior points into the data area
43759       ** of pToRelease.  Make sure pToRelease is still writeable. */
43760       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
43761
43762       /* If pPrior is part of the data area of pPage, then make sure pPage
43763       ** is still writeable */
43764       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
43765             || sqlite3PagerIswriteable(pPage->pDbPage) );
43766
43767       put4byte(pPrior, pgnoOvfl);
43768       releasePage(pToRelease);
43769       pToRelease = pOvfl;
43770       pPrior = pOvfl->aData;
43771       put4byte(pPrior, 0);
43772       pPayload = &pOvfl->aData[4];
43773       spaceLeft = pBt->usableSize - 4;
43774     }
43775     n = nPayload;
43776     if( n>spaceLeft ) n = spaceLeft;
43777
43778     /* If pToRelease is not zero than pPayload points into the data area
43779     ** of pToRelease.  Make sure pToRelease is still writeable. */
43780     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
43781
43782     /* If pPayload is part of the data area of pPage, then make sure pPage
43783     ** is still writeable */
43784     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
43785             || sqlite3PagerIswriteable(pPage->pDbPage) );
43786
43787     if( nSrc>0 ){
43788       if( n>nSrc ) n = nSrc;
43789       assert( pSrc );
43790       memcpy(pPayload, pSrc, n);
43791     }else{
43792       memset(pPayload, 0, n);
43793     }
43794     nPayload -= n;
43795     pPayload += n;
43796     pSrc += n;
43797     nSrc -= n;
43798     spaceLeft -= n;
43799     if( nSrc==0 ){
43800       nSrc = nData;
43801       pSrc = pData;
43802     }
43803   }
43804   releasePage(pToRelease);
43805   return SQLITE_OK;
43806 }
43807
43808 /*
43809 ** Remove the i-th cell from pPage.  This routine effects pPage only.
43810 ** The cell content is not freed or deallocated.  It is assumed that
43811 ** the cell content has been copied someplace else.  This routine just
43812 ** removes the reference to the cell from pPage.
43813 **
43814 ** "sz" must be the number of bytes in the cell.
43815 */
43816 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
43817   int i;          /* Loop counter */
43818   int pc;         /* Offset to cell content of cell being deleted */
43819   u8 *data;       /* pPage->aData */
43820   u8 *ptr;        /* Used to move bytes around within data[] */
43821   int rc;         /* The return code */
43822   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
43823
43824   if( *pRC ) return;
43825
43826   assert( idx>=0 && idx<pPage->nCell );
43827   assert( sz==cellSize(pPage, idx) );
43828   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
43829   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
43830   data = pPage->aData;
43831   ptr = &data[pPage->cellOffset + 2*idx];
43832   pc = get2byte(ptr);
43833   hdr = pPage->hdrOffset;
43834   testcase( pc==get2byte(&data[hdr+5]) );
43835   testcase( pc+sz==pPage->pBt->usableSize );
43836   if( pc < get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
43837     *pRC = SQLITE_CORRUPT_BKPT;
43838     return;
43839   }
43840   rc = freeSpace(pPage, pc, sz);
43841   if( rc ){
43842     *pRC = rc;
43843     return;
43844   }
43845   for(i=idx+1; i<pPage->nCell; i++, ptr+=2){
43846     ptr[0] = ptr[2];
43847     ptr[1] = ptr[3];
43848   }
43849   pPage->nCell--;
43850   put2byte(&data[hdr+3], pPage->nCell);
43851   pPage->nFree += 2;
43852 }
43853
43854 /*
43855 ** Insert a new cell on pPage at cell index "i".  pCell points to the
43856 ** content of the cell.
43857 **
43858 ** If the cell content will fit on the page, then put it there.  If it
43859 ** will not fit, then make a copy of the cell content into pTemp if
43860 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
43861 ** in pPage->aOvfl[] and make it point to the cell content (either
43862 ** in pTemp or the original pCell) and also record its index. 
43863 ** Allocating a new entry in pPage->aCell[] implies that 
43864 ** pPage->nOverflow is incremented.
43865 **
43866 ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
43867 ** cell. The caller will overwrite them after this function returns. If
43868 ** nSkip is non-zero, then pCell may not point to an invalid memory location 
43869 ** (but pCell+nSkip is always valid).
43870 */
43871 static void insertCell(
43872   MemPage *pPage,   /* Page into which we are copying */
43873   int i,            /* New cell becomes the i-th cell of the page */
43874   u8 *pCell,        /* Content of the new cell */
43875   int sz,           /* Bytes of content in pCell */
43876   u8 *pTemp,        /* Temp storage space for pCell, if needed */
43877   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
43878   int *pRC          /* Read and write return code from here */
43879 ){
43880   int idx = 0;      /* Where to write new cell content in data[] */
43881   int j;            /* Loop counter */
43882   int end;          /* First byte past the last cell pointer in data[] */
43883   int ins;          /* Index in data[] where new cell pointer is inserted */
43884   int cellOffset;   /* Address of first cell pointer in data[] */
43885   u8 *data;         /* The content of the whole page */
43886   u8 *ptr;          /* Used for moving information around in data[] */
43887
43888   int nSkip = (iChild ? 4 : 0);
43889
43890   if( *pRC ) return;
43891
43892   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
43893   assert( pPage->nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
43894   assert( pPage->nOverflow<=ArraySize(pPage->aOvfl) );
43895   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
43896   /* The cell should normally be sized correctly.  However, when moving a
43897   ** malformed cell from a leaf page to an interior page, if the cell size
43898   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
43899   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
43900   ** the term after the || in the following assert(). */
43901   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
43902   if( pPage->nOverflow || sz+2>pPage->nFree ){
43903     if( pTemp ){
43904       memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
43905       pCell = pTemp;
43906     }
43907     if( iChild ){
43908       put4byte(pCell, iChild);
43909     }
43910     j = pPage->nOverflow++;
43911     assert( j<(int)(sizeof(pPage->aOvfl)/sizeof(pPage->aOvfl[0])) );
43912     pPage->aOvfl[j].pCell = pCell;
43913     pPage->aOvfl[j].idx = (u16)i;
43914   }else{
43915     int rc = sqlite3PagerWrite(pPage->pDbPage);
43916     if( rc!=SQLITE_OK ){
43917       *pRC = rc;
43918       return;
43919     }
43920     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
43921     data = pPage->aData;
43922     cellOffset = pPage->cellOffset;
43923     end = cellOffset + 2*pPage->nCell;
43924     ins = cellOffset + 2*i;
43925     rc = allocateSpace(pPage, sz, &idx);
43926     if( rc ){ *pRC = rc; return; }
43927     /* The allocateSpace() routine guarantees the following two properties
43928     ** if it returns success */
43929     assert( idx >= end+2 );
43930     assert( idx+sz <= pPage->pBt->usableSize );
43931     pPage->nCell++;
43932     pPage->nFree -= (u16)(2 + sz);
43933     memcpy(&data[idx+nSkip], pCell+nSkip, sz-nSkip);
43934     if( iChild ){
43935       put4byte(&data[idx], iChild);
43936     }
43937     for(j=end, ptr=&data[j]; j>ins; j-=2, ptr-=2){
43938       ptr[0] = ptr[-2];
43939       ptr[1] = ptr[-1];
43940     }
43941     put2byte(&data[ins], idx);
43942     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
43943 #ifndef SQLITE_OMIT_AUTOVACUUM
43944     if( pPage->pBt->autoVacuum ){
43945       /* The cell may contain a pointer to an overflow page. If so, write
43946       ** the entry for the overflow page into the pointer map.
43947       */
43948       ptrmapPutOvflPtr(pPage, pCell, pRC);
43949     }
43950 #endif
43951   }
43952 }
43953
43954 /*
43955 ** Add a list of cells to a page.  The page should be initially empty.
43956 ** The cells are guaranteed to fit on the page.
43957 */
43958 static void assemblePage(
43959   MemPage *pPage,   /* The page to be assemblied */
43960   int nCell,        /* The number of cells to add to this page */
43961   u8 **apCell,      /* Pointers to cell bodies */
43962   u16 *aSize        /* Sizes of the cells */
43963 ){
43964   int i;            /* Loop counter */
43965   u8 *pCellptr;     /* Address of next cell pointer */
43966   int cellbody;     /* Address of next cell body */
43967   u8 * const data = pPage->aData;             /* Pointer to data for pPage */
43968   const int hdr = pPage->hdrOffset;           /* Offset of header on pPage */
43969   const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
43970
43971   assert( pPage->nOverflow==0 );
43972   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
43973   assert( nCell>=0 && nCell<=MX_CELL(pPage->pBt) && MX_CELL(pPage->pBt)<=5460 );
43974   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
43975
43976   /* Check that the page has just been zeroed by zeroPage() */
43977   assert( pPage->nCell==0 );
43978   assert( get2byte(&data[hdr+5])==nUsable );
43979
43980   pCellptr = &data[pPage->cellOffset + nCell*2];
43981   cellbody = nUsable;
43982   for(i=nCell-1; i>=0; i--){
43983     pCellptr -= 2;
43984     cellbody -= aSize[i];
43985     put2byte(pCellptr, cellbody);
43986     memcpy(&data[cellbody], apCell[i], aSize[i]);
43987   }
43988   put2byte(&data[hdr+3], nCell);
43989   put2byte(&data[hdr+5], cellbody);
43990   pPage->nFree -= (nCell*2 + nUsable - cellbody);
43991   pPage->nCell = (u16)nCell;
43992 }
43993
43994 /*
43995 ** The following parameters determine how many adjacent pages get involved
43996 ** in a balancing operation.  NN is the number of neighbors on either side
43997 ** of the page that participate in the balancing operation.  NB is the
43998 ** total number of pages that participate, including the target page and
43999 ** NN neighbors on either side.
44000 **
44001 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
44002 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
44003 ** in exchange for a larger degradation in INSERT and UPDATE performance.
44004 ** The value of NN appears to give the best results overall.
44005 */
44006 #define NN 1             /* Number of neighbors on either side of pPage */
44007 #define NB (NN*2+1)      /* Total pages involved in the balance */
44008
44009
44010 #ifndef SQLITE_OMIT_QUICKBALANCE
44011 /*
44012 ** This version of balance() handles the common special case where
44013 ** a new entry is being inserted on the extreme right-end of the
44014 ** tree, in other words, when the new entry will become the largest
44015 ** entry in the tree.
44016 **
44017 ** Instead of trying to balance the 3 right-most leaf pages, just add
44018 ** a new page to the right-hand side and put the one new entry in
44019 ** that page.  This leaves the right side of the tree somewhat
44020 ** unbalanced.  But odds are that we will be inserting new entries
44021 ** at the end soon afterwards so the nearly empty page will quickly
44022 ** fill up.  On average.
44023 **
44024 ** pPage is the leaf page which is the right-most page in the tree.
44025 ** pParent is its parent.  pPage must have a single overflow entry
44026 ** which is also the right-most entry on the page.
44027 **
44028 ** The pSpace buffer is used to store a temporary copy of the divider
44029 ** cell that will be inserted into pParent. Such a cell consists of a 4
44030 ** byte page number followed by a variable length integer. In other
44031 ** words, at most 13 bytes. Hence the pSpace buffer must be at
44032 ** least 13 bytes in size.
44033 */
44034 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
44035   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
44036   MemPage *pNew;                       /* Newly allocated page */
44037   int rc;                              /* Return Code */
44038   Pgno pgnoNew;                        /* Page number of pNew */
44039
44040   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
44041   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
44042   assert( pPage->nOverflow==1 );
44043
44044   if( pPage->nCell<=0 ) return SQLITE_CORRUPT_BKPT;
44045
44046   /* Allocate a new page. This page will become the right-sibling of 
44047   ** pPage. Make the parent page writable, so that the new divider cell
44048   ** may be inserted. If both these operations are successful, proceed.
44049   */
44050   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
44051
44052   if( rc==SQLITE_OK ){
44053
44054     u8 *pOut = &pSpace[4];
44055     u8 *pCell = pPage->aOvfl[0].pCell;
44056     u16 szCell = cellSizePtr(pPage, pCell);
44057     u8 *pStop;
44058
44059     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
44060     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
44061     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
44062     assemblePage(pNew, 1, &pCell, &szCell);
44063
44064     /* If this is an auto-vacuum database, update the pointer map
44065     ** with entries for the new page, and any pointer from the 
44066     ** cell on the page to an overflow page. If either of these
44067     ** operations fails, the return code is set, but the contents
44068     ** of the parent page are still manipulated by thh code below.
44069     ** That is Ok, at this point the parent page is guaranteed to
44070     ** be marked as dirty. Returning an error code will cause a
44071     ** rollback, undoing any changes made to the parent page.
44072     */
44073     if( ISAUTOVACUUM ){
44074       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
44075       if( szCell>pNew->minLocal ){
44076         ptrmapPutOvflPtr(pNew, pCell, &rc);
44077       }
44078     }
44079   
44080     /* Create a divider cell to insert into pParent. The divider cell
44081     ** consists of a 4-byte page number (the page number of pPage) and
44082     ** a variable length key value (which must be the same value as the
44083     ** largest key on pPage).
44084     **
44085     ** To find the largest key value on pPage, first find the right-most 
44086     ** cell on pPage. The first two fields of this cell are the 
44087     ** record-length (a variable length integer at most 32-bits in size)
44088     ** and the key value (a variable length integer, may have any value).
44089     ** The first of the while(...) loops below skips over the record-length
44090     ** field. The second while(...) loop copies the key value from the
44091     ** cell on pPage into the pSpace buffer.
44092     */
44093     pCell = findCell(pPage, pPage->nCell-1);
44094     pStop = &pCell[9];
44095     while( (*(pCell++)&0x80) && pCell<pStop );
44096     pStop = &pCell[9];
44097     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
44098
44099     /* Insert the new divider cell into pParent. */
44100     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
44101                0, pPage->pgno, &rc);
44102
44103     /* Set the right-child pointer of pParent to point to the new page. */
44104     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
44105   
44106     /* Release the reference to the new page. */
44107     releasePage(pNew);
44108   }
44109
44110   return rc;
44111 }
44112 #endif /* SQLITE_OMIT_QUICKBALANCE */
44113
44114 #if 0
44115 /*
44116 ** This function does not contribute anything to the operation of SQLite.
44117 ** it is sometimes activated temporarily while debugging code responsible 
44118 ** for setting pointer-map entries.
44119 */
44120 static int ptrmapCheckPages(MemPage **apPage, int nPage){
44121   int i, j;
44122   for(i=0; i<nPage; i++){
44123     Pgno n;
44124     u8 e;
44125     MemPage *pPage = apPage[i];
44126     BtShared *pBt = pPage->pBt;
44127     assert( pPage->isInit );
44128
44129     for(j=0; j<pPage->nCell; j++){
44130       CellInfo info;
44131       u8 *z;
44132      
44133       z = findCell(pPage, j);
44134       btreeParseCellPtr(pPage, z, &info);
44135       if( info.iOverflow ){
44136         Pgno ovfl = get4byte(&z[info.iOverflow]);
44137         ptrmapGet(pBt, ovfl, &e, &n);
44138         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
44139       }
44140       if( !pPage->leaf ){
44141         Pgno child = get4byte(z);
44142         ptrmapGet(pBt, child, &e, &n);
44143         assert( n==pPage->pgno && e==PTRMAP_BTREE );
44144       }
44145     }
44146     if( !pPage->leaf ){
44147       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
44148       ptrmapGet(pBt, child, &e, &n);
44149       assert( n==pPage->pgno && e==PTRMAP_BTREE );
44150     }
44151   }
44152   return 1;
44153 }
44154 #endif
44155
44156 /*
44157 ** This function is used to copy the contents of the b-tree node stored 
44158 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
44159 ** the pointer-map entries for each child page are updated so that the
44160 ** parent page stored in the pointer map is page pTo. If pFrom contained
44161 ** any cells with overflow page pointers, then the corresponding pointer
44162 ** map entries are also updated so that the parent page is page pTo.
44163 **
44164 ** If pFrom is currently carrying any overflow cells (entries in the
44165 ** MemPage.aOvfl[] array), they are not copied to pTo. 
44166 **
44167 ** Before returning, page pTo is reinitialized using btreeInitPage().
44168 **
44169 ** The performance of this function is not critical. It is only used by 
44170 ** the balance_shallower() and balance_deeper() procedures, neither of
44171 ** which are called often under normal circumstances.
44172 */
44173 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
44174   if( (*pRC)==SQLITE_OK ){
44175     BtShared * const pBt = pFrom->pBt;
44176     u8 * const aFrom = pFrom->aData;
44177     u8 * const aTo = pTo->aData;
44178     int const iFromHdr = pFrom->hdrOffset;
44179     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
44180     int rc;
44181     int iData;
44182   
44183   
44184     assert( pFrom->isInit );
44185     assert( pFrom->nFree>=iToHdr );
44186     assert( get2byte(&aFrom[iFromHdr+5])<=pBt->usableSize );
44187   
44188     /* Copy the b-tree node content from page pFrom to page pTo. */
44189     iData = get2byte(&aFrom[iFromHdr+5]);
44190     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
44191     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
44192   
44193     /* Reinitialize page pTo so that the contents of the MemPage structure
44194     ** match the new data. The initialization of pTo can actually fail under
44195     ** fairly obscure circumstances, even though it is a copy of initialized 
44196     ** page pFrom.
44197     */
44198     pTo->isInit = 0;
44199     rc = btreeInitPage(pTo);
44200     if( rc!=SQLITE_OK ){
44201       *pRC = rc;
44202       return;
44203     }
44204   
44205     /* If this is an auto-vacuum database, update the pointer-map entries
44206     ** for any b-tree or overflow pages that pTo now contains the pointers to.
44207     */
44208     if( ISAUTOVACUUM ){
44209       *pRC = setChildPtrmaps(pTo);
44210     }
44211   }
44212 }
44213
44214 /*
44215 ** This routine redistributes cells on the iParentIdx'th child of pParent
44216 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
44217 ** same amount of free space. Usually a single sibling on either side of the
44218 ** page are used in the balancing, though both siblings might come from one
44219 ** side if the page is the first or last child of its parent. If the page 
44220 ** has fewer than 2 siblings (something which can only happen if the page
44221 ** is a root page or a child of a root page) then all available siblings
44222 ** participate in the balancing.
44223 **
44224 ** The number of siblings of the page might be increased or decreased by 
44225 ** one or two in an effort to keep pages nearly full but not over full. 
44226 **
44227 ** Note that when this routine is called, some of the cells on the page
44228 ** might not actually be stored in MemPage.aData[]. This can happen
44229 ** if the page is overfull. This routine ensures that all cells allocated
44230 ** to the page and its siblings fit into MemPage.aData[] before returning.
44231 **
44232 ** In the course of balancing the page and its siblings, cells may be
44233 ** inserted into or removed from the parent page (pParent). Doing so
44234 ** may cause the parent page to become overfull or underfull. If this
44235 ** happens, it is the responsibility of the caller to invoke the correct
44236 ** balancing routine to fix this problem (see the balance() routine). 
44237 **
44238 ** If this routine fails for any reason, it might leave the database
44239 ** in a corrupted state. So if this routine fails, the database should
44240 ** be rolled back.
44241 **
44242 ** The third argument to this function, aOvflSpace, is a pointer to a
44243 ** buffer big enough to hold one page. If while inserting cells into the parent
44244 ** page (pParent) the parent page becomes overfull, this buffer is
44245 ** used to store the parent's overflow cells. Because this function inserts
44246 ** a maximum of four divider cells into the parent page, and the maximum
44247 ** size of a cell stored within an internal node is always less than 1/4
44248 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
44249 ** enough for all overflow cells.
44250 **
44251 ** If aOvflSpace is set to a null pointer, this function returns 
44252 ** SQLITE_NOMEM.
44253 */
44254 static int balance_nonroot(
44255   MemPage *pParent,               /* Parent page of siblings being balanced */
44256   int iParentIdx,                 /* Index of "the page" in pParent */
44257   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
44258   int isRoot                      /* True if pParent is a root-page */
44259 ){
44260   BtShared *pBt;               /* The whole database */
44261   int nCell = 0;               /* Number of cells in apCell[] */
44262   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
44263   int nNew = 0;                /* Number of pages in apNew[] */
44264   int nOld;                    /* Number of pages in apOld[] */
44265   int i, j, k;                 /* Loop counters */
44266   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
44267   int rc = SQLITE_OK;          /* The return code */
44268   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
44269   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
44270   int usableSpace;             /* Bytes in pPage beyond the header */
44271   int pageFlags;               /* Value of pPage->aData[0] */
44272   int subtotal;                /* Subtotal of bytes in cells on one page */
44273   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
44274   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
44275   int szScratch;               /* Size of scratch memory requested */
44276   MemPage *apOld[NB];          /* pPage and up to two siblings */
44277   MemPage *apCopy[NB];         /* Private copies of apOld[] pages */
44278   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
44279   u8 *pRight;                  /* Location in parent of right-sibling pointer */
44280   u8 *apDiv[NB-1];             /* Divider cells in pParent */
44281   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
44282   int szNew[NB+2];             /* Combined size of cells place on i-th page */
44283   u8 **apCell = 0;             /* All cells begin balanced */
44284   u16 *szCell;                 /* Local size of all cells in apCell[] */
44285   u8 *aSpace1;                 /* Space for copies of dividers cells */
44286   Pgno pgno;                   /* Temp var to store a page number in */
44287
44288   pBt = pParent->pBt;
44289   assert( sqlite3_mutex_held(pBt->mutex) );
44290   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
44291
44292 #if 0
44293   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
44294 #endif
44295
44296   /* At this point pParent may have at most one overflow cell. And if
44297   ** this overflow cell is present, it must be the cell with 
44298   ** index iParentIdx. This scenario comes about when this function
44299   ** is called (indirectly) from sqlite3BtreeDelete().
44300   */
44301   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
44302   assert( pParent->nOverflow==0 || pParent->aOvfl[0].idx==iParentIdx );
44303
44304   if( !aOvflSpace ){
44305     return SQLITE_NOMEM;
44306   }
44307
44308   /* Find the sibling pages to balance. Also locate the cells in pParent 
44309   ** that divide the siblings. An attempt is made to find NN siblings on 
44310   ** either side of pPage. More siblings are taken from one side, however, 
44311   ** if there are fewer than NN siblings on the other side. If pParent
44312   ** has NB or fewer children then all children of pParent are taken.  
44313   **
44314   ** This loop also drops the divider cells from the parent page. This
44315   ** way, the remainder of the function does not have to deal with any
44316   ** overflow cells in the parent page, since if any existed they will
44317   ** have already been removed.
44318   */
44319   i = pParent->nOverflow + pParent->nCell;
44320   if( i<2 ){
44321     nxDiv = 0;
44322     nOld = i+1;
44323   }else{
44324     nOld = 3;
44325     if( iParentIdx==0 ){                 
44326       nxDiv = 0;
44327     }else if( iParentIdx==i ){
44328       nxDiv = i-2;
44329     }else{
44330       nxDiv = iParentIdx-1;
44331     }
44332     i = 2;
44333   }
44334   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
44335     pRight = &pParent->aData[pParent->hdrOffset+8];
44336   }else{
44337     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
44338   }
44339   pgno = get4byte(pRight);
44340   while( 1 ){
44341     rc = getAndInitPage(pBt, pgno, &apOld[i]);
44342     if( rc ){
44343       memset(apOld, 0, (i+1)*sizeof(MemPage*));
44344       goto balance_cleanup;
44345     }
44346     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
44347     if( (i--)==0 ) break;
44348
44349     if( i+nxDiv==pParent->aOvfl[0].idx && pParent->nOverflow ){
44350       apDiv[i] = pParent->aOvfl[0].pCell;
44351       pgno = get4byte(apDiv[i]);
44352       szNew[i] = cellSizePtr(pParent, apDiv[i]);
44353       pParent->nOverflow = 0;
44354     }else{
44355       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
44356       pgno = get4byte(apDiv[i]);
44357       szNew[i] = cellSizePtr(pParent, apDiv[i]);
44358
44359       /* Drop the cell from the parent page. apDiv[i] still points to
44360       ** the cell within the parent, even though it has been dropped.
44361       ** This is safe because dropping a cell only overwrites the first
44362       ** four bytes of it, and this function does not need the first
44363       ** four bytes of the divider cell. So the pointer is safe to use
44364       ** later on.  
44365       **
44366       ** Unless SQLite is compiled in secure-delete mode. In this case,
44367       ** the dropCell() routine will overwrite the entire cell with zeroes.
44368       ** In this case, temporarily copy the cell into the aOvflSpace[]
44369       ** buffer. It will be copied out again as soon as the aSpace[] buffer
44370       ** is allocated.  */
44371       if( pBt->secureDelete ){
44372         int iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
44373         if( (iOff+szNew[i])>pBt->usableSize ){
44374           rc = SQLITE_CORRUPT_BKPT;
44375           memset(apOld, 0, (i+1)*sizeof(MemPage*));
44376           goto balance_cleanup;
44377         }else{
44378           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
44379           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
44380         }
44381       }
44382       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
44383     }
44384   }
44385
44386   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
44387   ** alignment */
44388   nMaxCells = (nMaxCells + 3)&~3;
44389
44390   /*
44391   ** Allocate space for memory structures
44392   */
44393   k = pBt->pageSize + ROUND8(sizeof(MemPage));
44394   szScratch =
44395        nMaxCells*sizeof(u8*)                       /* apCell */
44396      + nMaxCells*sizeof(u16)                       /* szCell */
44397      + pBt->pageSize                               /* aSpace1 */
44398      + k*nOld;                                     /* Page copies (apCopy) */
44399   apCell = sqlite3ScratchMalloc( szScratch ); 
44400   if( apCell==0 ){
44401     rc = SQLITE_NOMEM;
44402     goto balance_cleanup;
44403   }
44404   szCell = (u16*)&apCell[nMaxCells];
44405   aSpace1 = (u8*)&szCell[nMaxCells];
44406   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
44407
44408   /*
44409   ** Load pointers to all cells on sibling pages and the divider cells
44410   ** into the local apCell[] array.  Make copies of the divider cells
44411   ** into space obtained from aSpace1[] and remove the the divider Cells
44412   ** from pParent.
44413   **
44414   ** If the siblings are on leaf pages, then the child pointers of the
44415   ** divider cells are stripped from the cells before they are copied
44416   ** into aSpace1[].  In this way, all cells in apCell[] are without
44417   ** child pointers.  If siblings are not leaves, then all cell in
44418   ** apCell[] include child pointers.  Either way, all cells in apCell[]
44419   ** are alike.
44420   **
44421   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
44422   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
44423   */
44424   leafCorrection = apOld[0]->leaf*4;
44425   leafData = apOld[0]->hasData;
44426   for(i=0; i<nOld; i++){
44427     int limit;
44428     
44429     /* Before doing anything else, take a copy of the i'th original sibling
44430     ** The rest of this function will use data from the copies rather
44431     ** that the original pages since the original pages will be in the
44432     ** process of being overwritten.  */
44433     MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
44434     memcpy(pOld, apOld[i], sizeof(MemPage));
44435     pOld->aData = (void*)&pOld[1];
44436     memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
44437
44438     limit = pOld->nCell+pOld->nOverflow;
44439     for(j=0; j<limit; j++){
44440       assert( nCell<nMaxCells );
44441       apCell[nCell] = findOverflowCell(pOld, j);
44442       szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
44443       nCell++;
44444     }
44445     if( i<nOld-1 && !leafData){
44446       u16 sz = (u16)szNew[i];
44447       u8 *pTemp;
44448       assert( nCell<nMaxCells );
44449       szCell[nCell] = sz;
44450       pTemp = &aSpace1[iSpace1];
44451       iSpace1 += sz;
44452       assert( sz<=pBt->pageSize/4 );
44453       assert( iSpace1<=pBt->pageSize );
44454       memcpy(pTemp, apDiv[i], sz);
44455       apCell[nCell] = pTemp+leafCorrection;
44456       assert( leafCorrection==0 || leafCorrection==4 );
44457       szCell[nCell] = szCell[nCell] - leafCorrection;
44458       if( !pOld->leaf ){
44459         assert( leafCorrection==0 );
44460         assert( pOld->hdrOffset==0 );
44461         /* The right pointer of the child page pOld becomes the left
44462         ** pointer of the divider cell */
44463         memcpy(apCell[nCell], &pOld->aData[8], 4);
44464       }else{
44465         assert( leafCorrection==4 );
44466         if( szCell[nCell]<4 ){
44467           /* Do not allow any cells smaller than 4 bytes. */
44468           szCell[nCell] = 4;
44469         }
44470       }
44471       nCell++;
44472     }
44473   }
44474
44475   /*
44476   ** Figure out the number of pages needed to hold all nCell cells.
44477   ** Store this number in "k".  Also compute szNew[] which is the total
44478   ** size of all cells on the i-th page and cntNew[] which is the index
44479   ** in apCell[] of the cell that divides page i from page i+1.  
44480   ** cntNew[k] should equal nCell.
44481   **
44482   ** Values computed by this block:
44483   **
44484   **           k: The total number of sibling pages
44485   **    szNew[i]: Spaced used on the i-th sibling page.
44486   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
44487   **              the right of the i-th sibling page.
44488   ** usableSpace: Number of bytes of space available on each sibling.
44489   ** 
44490   */
44491   usableSpace = pBt->usableSize - 12 + leafCorrection;
44492   for(subtotal=k=i=0; i<nCell; i++){
44493     assert( i<nMaxCells );
44494     subtotal += szCell[i] + 2;
44495     if( subtotal > usableSpace ){
44496       szNew[k] = subtotal - szCell[i];
44497       cntNew[k] = i;
44498       if( leafData ){ i--; }
44499       subtotal = 0;
44500       k++;
44501       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
44502     }
44503   }
44504   szNew[k] = subtotal;
44505   cntNew[k] = nCell;
44506   k++;
44507
44508   /*
44509   ** The packing computed by the previous block is biased toward the siblings
44510   ** on the left side.  The left siblings are always nearly full, while the
44511   ** right-most sibling might be nearly empty.  This block of code attempts
44512   ** to adjust the packing of siblings to get a better balance.
44513   **
44514   ** This adjustment is more than an optimization.  The packing above might
44515   ** be so out of balance as to be illegal.  For example, the right-most
44516   ** sibling might be completely empty.  This adjustment is not optional.
44517   */
44518   for(i=k-1; i>0; i--){
44519     int szRight = szNew[i];  /* Size of sibling on the right */
44520     int szLeft = szNew[i-1]; /* Size of sibling on the left */
44521     int r;              /* Index of right-most cell in left sibling */
44522     int d;              /* Index of first cell to the left of right sibling */
44523
44524     r = cntNew[i-1] - 1;
44525     d = r + 1 - leafData;
44526     assert( d<nMaxCells );
44527     assert( r<nMaxCells );
44528     while( szRight==0 || szRight+szCell[d]+2<=szLeft-(szCell[r]+2) ){
44529       szRight += szCell[d] + 2;
44530       szLeft -= szCell[r] + 2;
44531       cntNew[i-1]--;
44532       r = cntNew[i-1] - 1;
44533       d = r + 1 - leafData;
44534     }
44535     szNew[i] = szRight;
44536     szNew[i-1] = szLeft;
44537   }
44538
44539   /* Either we found one or more cells (cntnew[0])>0) or pPage is
44540   ** a virtual root page.  A virtual root page is when the real root
44541   ** page is page 1 and we are the only child of that page.
44542   */
44543   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
44544
44545   TRACE(("BALANCE: old: %d %d %d  ",
44546     apOld[0]->pgno, 
44547     nOld>=2 ? apOld[1]->pgno : 0,
44548     nOld>=3 ? apOld[2]->pgno : 0
44549   ));
44550
44551   /*
44552   ** Allocate k new pages.  Reuse old pages where possible.
44553   */
44554   if( apOld[0]->pgno<=1 ){
44555     rc = SQLITE_CORRUPT_BKPT;
44556     goto balance_cleanup;
44557   }
44558   pageFlags = apOld[0]->aData[0];
44559   for(i=0; i<k; i++){
44560     MemPage *pNew;
44561     if( i<nOld ){
44562       pNew = apNew[i] = apOld[i];
44563       apOld[i] = 0;
44564       rc = sqlite3PagerWrite(pNew->pDbPage);
44565       nNew++;
44566       if( rc ) goto balance_cleanup;
44567     }else{
44568       assert( i>0 );
44569       rc = allocateBtreePage(pBt, &pNew, &pgno, pgno, 0);
44570       if( rc ) goto balance_cleanup;
44571       apNew[i] = pNew;
44572       nNew++;
44573
44574       /* Set the pointer-map entry for the new sibling page. */
44575       if( ISAUTOVACUUM ){
44576         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
44577         if( rc!=SQLITE_OK ){
44578           goto balance_cleanup;
44579         }
44580       }
44581     }
44582   }
44583
44584   /* Free any old pages that were not reused as new pages.
44585   */
44586   while( i<nOld ){
44587     freePage(apOld[i], &rc);
44588     if( rc ) goto balance_cleanup;
44589     releasePage(apOld[i]);
44590     apOld[i] = 0;
44591     i++;
44592   }
44593
44594   /*
44595   ** Put the new pages in accending order.  This helps to
44596   ** keep entries in the disk file in order so that a scan
44597   ** of the table is a linear scan through the file.  That
44598   ** in turn helps the operating system to deliver pages
44599   ** from the disk more rapidly.
44600   **
44601   ** An O(n^2) insertion sort algorithm is used, but since
44602   ** n is never more than NB (a small constant), that should
44603   ** not be a problem.
44604   **
44605   ** When NB==3, this one optimization makes the database
44606   ** about 25% faster for large insertions and deletions.
44607   */
44608   for(i=0; i<k-1; i++){
44609     int minV = apNew[i]->pgno;
44610     int minI = i;
44611     for(j=i+1; j<k; j++){
44612       if( apNew[j]->pgno<(unsigned)minV ){
44613         minI = j;
44614         minV = apNew[j]->pgno;
44615       }
44616     }
44617     if( minI>i ){
44618       int t;
44619       MemPage *pT;
44620       t = apNew[i]->pgno;
44621       pT = apNew[i];
44622       apNew[i] = apNew[minI];
44623       apNew[minI] = pT;
44624     }
44625   }
44626   TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
44627     apNew[0]->pgno, szNew[0],
44628     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
44629     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
44630     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
44631     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
44632
44633   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
44634   put4byte(pRight, apNew[nNew-1]->pgno);
44635
44636   /*
44637   ** Evenly distribute the data in apCell[] across the new pages.
44638   ** Insert divider cells into pParent as necessary.
44639   */
44640   j = 0;
44641   for(i=0; i<nNew; i++){
44642     /* Assemble the new sibling page. */
44643     MemPage *pNew = apNew[i];
44644     assert( j<nMaxCells );
44645     zeroPage(pNew, pageFlags);
44646     assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
44647     assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
44648     assert( pNew->nOverflow==0 );
44649
44650     j = cntNew[i];
44651
44652     /* If the sibling page assembled above was not the right-most sibling,
44653     ** insert a divider cell into the parent page.
44654     */
44655     assert( i<nNew-1 || j==nCell );
44656     if( j<nCell ){
44657       u8 *pCell;
44658       u8 *pTemp;
44659       int sz;
44660
44661       assert( j<nMaxCells );
44662       pCell = apCell[j];
44663       sz = szCell[j] + leafCorrection;
44664       pTemp = &aOvflSpace[iOvflSpace];
44665       if( !pNew->leaf ){
44666         memcpy(&pNew->aData[8], pCell, 4);
44667       }else if( leafData ){
44668         /* If the tree is a leaf-data tree, and the siblings are leaves, 
44669         ** then there is no divider cell in apCell[]. Instead, the divider 
44670         ** cell consists of the integer key for the right-most cell of 
44671         ** the sibling-page assembled above only.
44672         */
44673         CellInfo info;
44674         j--;
44675         btreeParseCellPtr(pNew, apCell[j], &info);
44676         pCell = pTemp;
44677         sz = 4 + putVarint(&pCell[4], info.nKey);
44678         pTemp = 0;
44679       }else{
44680         pCell -= 4;
44681         /* Obscure case for non-leaf-data trees: If the cell at pCell was
44682         ** previously stored on a leaf node, and its reported size was 4
44683         ** bytes, then it may actually be smaller than this 
44684         ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
44685         ** any cell). But it is important to pass the correct size to 
44686         ** insertCell(), so reparse the cell now.
44687         **
44688         ** Note that this can never happen in an SQLite data file, as all
44689         ** cells are at least 4 bytes. It only happens in b-trees used
44690         ** to evaluate "IN (SELECT ...)" and similar clauses.
44691         */
44692         if( szCell[j]==4 ){
44693           assert(leafCorrection==4);
44694           sz = cellSizePtr(pParent, pCell);
44695         }
44696       }
44697       iOvflSpace += sz;
44698       assert( sz<=pBt->pageSize/4 );
44699       assert( iOvflSpace<=pBt->pageSize );
44700       insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
44701       if( rc!=SQLITE_OK ) goto balance_cleanup;
44702       assert( sqlite3PagerIswriteable(pParent->pDbPage) );
44703
44704       j++;
44705       nxDiv++;
44706     }
44707   }
44708   assert( j==nCell );
44709   assert( nOld>0 );
44710   assert( nNew>0 );
44711   if( (pageFlags & PTF_LEAF)==0 ){
44712     u8 *zChild = &apCopy[nOld-1]->aData[8];
44713     memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
44714   }
44715
44716   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
44717     /* The root page of the b-tree now contains no cells. The only sibling
44718     ** page is the right-child of the parent. Copy the contents of the
44719     ** child page into the parent, decreasing the overall height of the
44720     ** b-tree structure by one. This is described as the "balance-shallower"
44721     ** sub-algorithm in some documentation.
44722     **
44723     ** If this is an auto-vacuum database, the call to copyNodeContent() 
44724     ** sets all pointer-map entries corresponding to database image pages 
44725     ** for which the pointer is stored within the content being copied.
44726     **
44727     ** The second assert below verifies that the child page is defragmented
44728     ** (it must be, as it was just reconstructed using assemblePage()). This
44729     ** is important if the parent page happens to be page 1 of the database
44730     ** image.  */
44731     assert( nNew==1 );
44732     assert( apNew[0]->nFree == 
44733         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2) 
44734     );
44735     copyNodeContent(apNew[0], pParent, &rc);
44736     freePage(apNew[0], &rc);
44737   }else if( ISAUTOVACUUM ){
44738     /* Fix the pointer-map entries for all the cells that were shifted around. 
44739     ** There are several different types of pointer-map entries that need to
44740     ** be dealt with by this routine. Some of these have been set already, but
44741     ** many have not. The following is a summary:
44742     **
44743     **   1) The entries associated with new sibling pages that were not
44744     **      siblings when this function was called. These have already
44745     **      been set. We don't need to worry about old siblings that were
44746     **      moved to the free-list - the freePage() code has taken care
44747     **      of those.
44748     **
44749     **   2) The pointer-map entries associated with the first overflow
44750     **      page in any overflow chains used by new divider cells. These 
44751     **      have also already been taken care of by the insertCell() code.
44752     **
44753     **   3) If the sibling pages are not leaves, then the child pages of
44754     **      cells stored on the sibling pages may need to be updated.
44755     **
44756     **   4) If the sibling pages are not internal intkey nodes, then any
44757     **      overflow pages used by these cells may need to be updated
44758     **      (internal intkey nodes never contain pointers to overflow pages).
44759     **
44760     **   5) If the sibling pages are not leaves, then the pointer-map
44761     **      entries for the right-child pages of each sibling may need
44762     **      to be updated.
44763     **
44764     ** Cases 1 and 2 are dealt with above by other code. The next
44765     ** block deals with cases 3 and 4 and the one after that, case 5. Since
44766     ** setting a pointer map entry is a relatively expensive operation, this
44767     ** code only sets pointer map entries for child or overflow pages that have
44768     ** actually moved between pages.  */
44769     MemPage *pNew = apNew[0];
44770     MemPage *pOld = apCopy[0];
44771     int nOverflow = pOld->nOverflow;
44772     int iNextOld = pOld->nCell + nOverflow;
44773     int iOverflow = (nOverflow ? pOld->aOvfl[0].idx : -1);
44774     j = 0;                             /* Current 'old' sibling page */
44775     k = 0;                             /* Current 'new' sibling page */
44776     for(i=0; i<nCell; i++){
44777       int isDivider = 0;
44778       while( i==iNextOld ){
44779         /* Cell i is the cell immediately following the last cell on old
44780         ** sibling page j. If the siblings are not leaf pages of an
44781         ** intkey b-tree, then cell i was a divider cell. */
44782         pOld = apCopy[++j];
44783         iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
44784         if( pOld->nOverflow ){
44785           nOverflow = pOld->nOverflow;
44786           iOverflow = i + !leafData + pOld->aOvfl[0].idx;
44787         }
44788         isDivider = !leafData;  
44789       }
44790
44791       assert(nOverflow>0 || iOverflow<i );
44792       assert(nOverflow<2 || pOld->aOvfl[0].idx==pOld->aOvfl[1].idx-1);
44793       assert(nOverflow<3 || pOld->aOvfl[1].idx==pOld->aOvfl[2].idx-1);
44794       if( i==iOverflow ){
44795         isDivider = 1;
44796         if( (--nOverflow)>0 ){
44797           iOverflow++;
44798         }
44799       }
44800
44801       if( i==cntNew[k] ){
44802         /* Cell i is the cell immediately following the last cell on new
44803         ** sibling page k. If the siblings are not leaf pages of an
44804         ** intkey b-tree, then cell i is a divider cell.  */
44805         pNew = apNew[++k];
44806         if( !leafData ) continue;
44807       }
44808       assert( j<nOld );
44809       assert( k<nNew );
44810
44811       /* If the cell was originally divider cell (and is not now) or
44812       ** an overflow cell, or if the cell was located on a different sibling
44813       ** page before the balancing, then the pointer map entries associated
44814       ** with any child or overflow pages need to be updated.  */
44815       if( isDivider || pOld->pgno!=pNew->pgno ){
44816         if( !leafCorrection ){
44817           ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
44818         }
44819         if( szCell[i]>pNew->minLocal ){
44820           ptrmapPutOvflPtr(pNew, apCell[i], &rc);
44821         }
44822       }
44823     }
44824
44825     if( !leafCorrection ){
44826       for(i=0; i<nNew; i++){
44827         u32 key = get4byte(&apNew[i]->aData[8]);
44828         ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
44829       }
44830     }
44831
44832 #if 0
44833     /* The ptrmapCheckPages() contains assert() statements that verify that
44834     ** all pointer map pages are set correctly. This is helpful while 
44835     ** debugging. This is usually disabled because a corrupt database may
44836     ** cause an assert() statement to fail.  */
44837     ptrmapCheckPages(apNew, nNew);
44838     ptrmapCheckPages(&pParent, 1);
44839 #endif
44840   }
44841
44842   assert( pParent->isInit );
44843   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
44844           nOld, nNew, nCell));
44845
44846   /*
44847   ** Cleanup before returning.
44848   */
44849 balance_cleanup:
44850   sqlite3ScratchFree(apCell);
44851   for(i=0; i<nOld; i++){
44852     releasePage(apOld[i]);
44853   }
44854   for(i=0; i<nNew; i++){
44855     releasePage(apNew[i]);
44856   }
44857
44858   return rc;
44859 }
44860
44861
44862 /*
44863 ** This function is called when the root page of a b-tree structure is
44864 ** overfull (has one or more overflow pages).
44865 **
44866 ** A new child page is allocated and the contents of the current root
44867 ** page, including overflow cells, are copied into the child. The root
44868 ** page is then overwritten to make it an empty page with the right-child 
44869 ** pointer pointing to the new page.
44870 **
44871 ** Before returning, all pointer-map entries corresponding to pages 
44872 ** that the new child-page now contains pointers to are updated. The
44873 ** entry corresponding to the new right-child pointer of the root
44874 ** page is also updated.
44875 **
44876 ** If successful, *ppChild is set to contain a reference to the child 
44877 ** page and SQLITE_OK is returned. In this case the caller is required
44878 ** to call releasePage() on *ppChild exactly once. If an error occurs,
44879 ** an error code is returned and *ppChild is set to 0.
44880 */
44881 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
44882   int rc;                        /* Return value from subprocedures */
44883   MemPage *pChild = 0;           /* Pointer to a new child page */
44884   Pgno pgnoChild = 0;            /* Page number of the new child page */
44885   BtShared *pBt = pRoot->pBt;    /* The BTree */
44886
44887   assert( pRoot->nOverflow>0 );
44888   assert( sqlite3_mutex_held(pBt->mutex) );
44889
44890   /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
44891   ** page that will become the new right-child of pPage. Copy the contents
44892   ** of the node stored on pRoot into the new child page.
44893   */
44894   rc = sqlite3PagerWrite(pRoot->pDbPage);
44895   if( rc==SQLITE_OK ){
44896     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
44897     copyNodeContent(pRoot, pChild, &rc);
44898     if( ISAUTOVACUUM ){
44899       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
44900     }
44901   }
44902   if( rc ){
44903     *ppChild = 0;
44904     releasePage(pChild);
44905     return rc;
44906   }
44907   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
44908   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
44909   assert( pChild->nCell==pRoot->nCell );
44910
44911   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
44912
44913   /* Copy the overflow cells from pRoot to pChild */
44914   memcpy(pChild->aOvfl, pRoot->aOvfl, pRoot->nOverflow*sizeof(pRoot->aOvfl[0]));
44915   pChild->nOverflow = pRoot->nOverflow;
44916
44917   /* Zero the contents of pRoot. Then install pChild as the right-child. */
44918   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
44919   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
44920
44921   *ppChild = pChild;
44922   return SQLITE_OK;
44923 }
44924
44925 /*
44926 ** The page that pCur currently points to has just been modified in
44927 ** some way. This function figures out if this modification means the
44928 ** tree needs to be balanced, and if so calls the appropriate balancing 
44929 ** routine. Balancing routines are:
44930 **
44931 **   balance_quick()
44932 **   balance_deeper()
44933 **   balance_nonroot()
44934 */
44935 static int balance(BtCursor *pCur){
44936   int rc = SQLITE_OK;
44937   const int nMin = pCur->pBt->usableSize * 2 / 3;
44938   u8 aBalanceQuickSpace[13];
44939   u8 *pFree = 0;
44940
44941   TESTONLY( int balance_quick_called = 0 );
44942   TESTONLY( int balance_deeper_called = 0 );
44943
44944   do {
44945     int iPage = pCur->iPage;
44946     MemPage *pPage = pCur->apPage[iPage];
44947
44948     if( iPage==0 ){
44949       if( pPage->nOverflow ){
44950         /* The root page of the b-tree is overfull. In this case call the
44951         ** balance_deeper() function to create a new child for the root-page
44952         ** and copy the current contents of the root-page to it. The
44953         ** next iteration of the do-loop will balance the child page.
44954         */ 
44955         assert( (balance_deeper_called++)==0 );
44956         rc = balance_deeper(pPage, &pCur->apPage[1]);
44957         if( rc==SQLITE_OK ){
44958           pCur->iPage = 1;
44959           pCur->aiIdx[0] = 0;
44960           pCur->aiIdx[1] = 0;
44961           assert( pCur->apPage[1]->nOverflow );
44962         }
44963       }else{
44964         break;
44965       }
44966     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
44967       break;
44968     }else{
44969       MemPage * const pParent = pCur->apPage[iPage-1];
44970       int const iIdx = pCur->aiIdx[iPage-1];
44971
44972       rc = sqlite3PagerWrite(pParent->pDbPage);
44973       if( rc==SQLITE_OK ){
44974 #ifndef SQLITE_OMIT_QUICKBALANCE
44975         if( pPage->hasData
44976          && pPage->nOverflow==1
44977          && pPage->aOvfl[0].idx==pPage->nCell
44978          && pParent->pgno!=1
44979          && pParent->nCell==iIdx
44980         ){
44981           /* Call balance_quick() to create a new sibling of pPage on which
44982           ** to store the overflow cell. balance_quick() inserts a new cell
44983           ** into pParent, which may cause pParent overflow. If this
44984           ** happens, the next interation of the do-loop will balance pParent 
44985           ** use either balance_nonroot() or balance_deeper(). Until this
44986           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
44987           ** buffer. 
44988           **
44989           ** The purpose of the following assert() is to check that only a
44990           ** single call to balance_quick() is made for each call to this
44991           ** function. If this were not verified, a subtle bug involving reuse
44992           ** of the aBalanceQuickSpace[] might sneak in.
44993           */
44994           assert( (balance_quick_called++)==0 );
44995           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
44996         }else
44997 #endif
44998         {
44999           /* In this case, call balance_nonroot() to redistribute cells
45000           ** between pPage and up to 2 of its sibling pages. This involves
45001           ** modifying the contents of pParent, which may cause pParent to
45002           ** become overfull or underfull. The next iteration of the do-loop
45003           ** will balance the parent page to correct this.
45004           ** 
45005           ** If the parent page becomes overfull, the overflow cell or cells
45006           ** are stored in the pSpace buffer allocated immediately below. 
45007           ** A subsequent iteration of the do-loop will deal with this by
45008           ** calling balance_nonroot() (balance_deeper() may be called first,
45009           ** but it doesn't deal with overflow cells - just moves them to a
45010           ** different page). Once this subsequent call to balance_nonroot() 
45011           ** has completed, it is safe to release the pSpace buffer used by
45012           ** the previous call, as the overflow cell data will have been 
45013           ** copied either into the body of a database page or into the new
45014           ** pSpace buffer passed to the latter call to balance_nonroot().
45015           */
45016           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
45017           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1);
45018           if( pFree ){
45019             /* If pFree is not NULL, it points to the pSpace buffer used 
45020             ** by a previous call to balance_nonroot(). Its contents are
45021             ** now stored either on real database pages or within the 
45022             ** new pSpace buffer, so it may be safely freed here. */
45023             sqlite3PageFree(pFree);
45024           }
45025
45026           /* The pSpace buffer will be freed after the next call to
45027           ** balance_nonroot(), or just before this function returns, whichever
45028           ** comes first. */
45029           pFree = pSpace;
45030         }
45031       }
45032
45033       pPage->nOverflow = 0;
45034
45035       /* The next iteration of the do-loop balances the parent page. */
45036       releasePage(pPage);
45037       pCur->iPage--;
45038     }
45039   }while( rc==SQLITE_OK );
45040
45041   if( pFree ){
45042     sqlite3PageFree(pFree);
45043   }
45044   return rc;
45045 }
45046
45047
45048 /*
45049 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
45050 ** and the data is given by (pData,nData).  The cursor is used only to
45051 ** define what table the record should be inserted into.  The cursor
45052 ** is left pointing at a random location.
45053 **
45054 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
45055 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
45056 **
45057 ** If the seekResult parameter is non-zero, then a successful call to
45058 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
45059 ** been performed. seekResult is the search result returned (a negative
45060 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
45061 ** a positive value if pCur points at an etry that is larger than 
45062 ** (pKey, nKey)). 
45063 **
45064 ** If the seekResult parameter is non-zero, then the caller guarantees that
45065 ** cursor pCur is pointing at the existing copy of a row that is to be
45066 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
45067 ** point to any entry or to no entry at all and so this function has to seek
45068 ** the cursor before the new key can be inserted.
45069 */
45070 SQLITE_PRIVATE int sqlite3BtreeInsert(
45071   BtCursor *pCur,                /* Insert data into the table of this cursor */
45072   const void *pKey, i64 nKey,    /* The key of the new record */
45073   const void *pData, int nData,  /* The data of the new record */
45074   int nZero,                     /* Number of extra 0 bytes to append to data */
45075   int appendBias,                /* True if this is likely an append */
45076   int seekResult                 /* Result of prior MovetoUnpacked() call */
45077 ){
45078   int rc;
45079   int loc = seekResult;          /* -1: before desired location  +1: after */
45080   int szNew = 0;
45081   int idx;
45082   MemPage *pPage;
45083   Btree *p = pCur->pBtree;
45084   BtShared *pBt = p->pBt;
45085   unsigned char *oldCell;
45086   unsigned char *newCell = 0;
45087
45088   if( pCur->eState==CURSOR_FAULT ){
45089     assert( pCur->skipNext!=SQLITE_OK );
45090     return pCur->skipNext;
45091   }
45092
45093   assert( cursorHoldsMutex(pCur) );
45094   assert( pCur->wrFlag && pBt->inTransaction==TRANS_WRITE && !pBt->readOnly );
45095   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
45096
45097   /* Assert that the caller has been consistent. If this cursor was opened
45098   ** expecting an index b-tree, then the caller should be inserting blob
45099   ** keys with no associated data. If the cursor was opened expecting an
45100   ** intkey table, the caller should be inserting integer keys with a
45101   ** blob of associated data.  */
45102   assert( (pKey==0)==(pCur->pKeyInfo==0) );
45103
45104   /* If this is an insert into a table b-tree, invalidate any incrblob 
45105   ** cursors open on the row being replaced (assuming this is a replace
45106   ** operation - if it is not, the following is a no-op).  */
45107   if( pCur->pKeyInfo==0 ){
45108     invalidateIncrblobCursors(p, nKey, 0);
45109   }
45110
45111   /* Save the positions of any other cursors open on this table.
45112   **
45113   ** In some cases, the call to btreeMoveto() below is a no-op. For
45114   ** example, when inserting data into a table with auto-generated integer
45115   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
45116   ** integer key to use. It then calls this function to actually insert the 
45117   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
45118   ** that the cursor is already where it needs to be and returns without
45119   ** doing any work. To avoid thwarting these optimizations, it is important
45120   ** not to clear the cursor here.
45121   */
45122   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
45123   if( rc ) return rc;
45124   if( !loc ){
45125     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
45126     if( rc ) return rc;
45127   }
45128   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
45129
45130   pPage = pCur->apPage[pCur->iPage];
45131   assert( pPage->intKey || nKey>=0 );
45132   assert( pPage->leaf || !pPage->intKey );
45133
45134   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
45135           pCur->pgnoRoot, nKey, nData, pPage->pgno,
45136           loc==0 ? "overwrite" : "new entry"));
45137   assert( pPage->isInit );
45138   allocateTempSpace(pBt);
45139   newCell = pBt->pTmpSpace;
45140   if( newCell==0 ) return SQLITE_NOMEM;
45141   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
45142   if( rc ) goto end_insert;
45143   assert( szNew==cellSizePtr(pPage, newCell) );
45144   assert( szNew<=MX_CELL_SIZE(pBt) );
45145   idx = pCur->aiIdx[pCur->iPage];
45146   if( loc==0 ){
45147     u16 szOld;
45148     assert( idx<pPage->nCell );
45149     rc = sqlite3PagerWrite(pPage->pDbPage);
45150     if( rc ){
45151       goto end_insert;
45152     }
45153     oldCell = findCell(pPage, idx);
45154     if( !pPage->leaf ){
45155       memcpy(newCell, oldCell, 4);
45156     }
45157     szOld = cellSizePtr(pPage, oldCell);
45158     rc = clearCell(pPage, oldCell);
45159     dropCell(pPage, idx, szOld, &rc);
45160     if( rc ) goto end_insert;
45161   }else if( loc<0 && pPage->nCell>0 ){
45162     assert( pPage->leaf );
45163     idx = ++pCur->aiIdx[pCur->iPage];
45164   }else{
45165     assert( pPage->leaf );
45166   }
45167   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
45168   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
45169
45170   /* If no error has occured and pPage has an overflow cell, call balance() 
45171   ** to redistribute the cells within the tree. Since balance() may move
45172   ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
45173   ** variables.
45174   **
45175   ** Previous versions of SQLite called moveToRoot() to move the cursor
45176   ** back to the root page as balance() used to invalidate the contents
45177   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
45178   ** set the cursor state to "invalid". This makes common insert operations
45179   ** slightly faster.
45180   **
45181   ** There is a subtle but important optimization here too. When inserting
45182   ** multiple records into an intkey b-tree using a single cursor (as can
45183   ** happen while processing an "INSERT INTO ... SELECT" statement), it
45184   ** is advantageous to leave the cursor pointing to the last entry in
45185   ** the b-tree if possible. If the cursor is left pointing to the last
45186   ** entry in the table, and the next row inserted has an integer key
45187   ** larger than the largest existing key, it is possible to insert the
45188   ** row without seeking the cursor. This can be a big performance boost.
45189   */
45190   pCur->info.nSize = 0;
45191   pCur->validNKey = 0;
45192   if( rc==SQLITE_OK && pPage->nOverflow ){
45193     rc = balance(pCur);
45194
45195     /* Must make sure nOverflow is reset to zero even if the balance()
45196     ** fails. Internal data structure corruption will result otherwise. 
45197     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
45198     ** from trying to save the current position of the cursor.  */
45199     pCur->apPage[pCur->iPage]->nOverflow = 0;
45200     pCur->eState = CURSOR_INVALID;
45201   }
45202   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
45203
45204 end_insert:
45205   return rc;
45206 }
45207
45208 /*
45209 ** Delete the entry that the cursor is pointing to.  The cursor
45210 ** is left pointing at a arbitrary location.
45211 */
45212 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
45213   Btree *p = pCur->pBtree;
45214   BtShared *pBt = p->pBt;              
45215   int rc;                              /* Return code */
45216   MemPage *pPage;                      /* Page to delete cell from */
45217   unsigned char *pCell;                /* Pointer to cell to delete */
45218   int iCellIdx;                        /* Index of cell to delete */
45219   int iCellDepth;                      /* Depth of node containing pCell */ 
45220
45221   assert( cursorHoldsMutex(pCur) );
45222   assert( pBt->inTransaction==TRANS_WRITE );
45223   assert( !pBt->readOnly );
45224   assert( pCur->wrFlag );
45225   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
45226   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
45227
45228   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) 
45229    || NEVER(pCur->eState!=CURSOR_VALID)
45230   ){
45231     return SQLITE_ERROR;  /* Something has gone awry. */
45232   }
45233
45234   /* If this is a delete operation to remove a row from a table b-tree,
45235   ** invalidate any incrblob cursors open on the row being deleted.  */
45236   if( pCur->pKeyInfo==0 ){
45237     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
45238   }
45239
45240   iCellDepth = pCur->iPage;
45241   iCellIdx = pCur->aiIdx[iCellDepth];
45242   pPage = pCur->apPage[iCellDepth];
45243   pCell = findCell(pPage, iCellIdx);
45244
45245   /* If the page containing the entry to delete is not a leaf page, move
45246   ** the cursor to the largest entry in the tree that is smaller than
45247   ** the entry being deleted. This cell will replace the cell being deleted
45248   ** from the internal node. The 'previous' entry is used for this instead
45249   ** of the 'next' entry, as the previous entry is always a part of the
45250   ** sub-tree headed by the child page of the cell being deleted. This makes
45251   ** balancing the tree following the delete operation easier.  */
45252   if( !pPage->leaf ){
45253     int notUsed;
45254     rc = sqlite3BtreePrevious(pCur, &notUsed);
45255     if( rc ) return rc;
45256   }
45257
45258   /* Save the positions of any other cursors open on this table before
45259   ** making any modifications. Make the page containing the entry to be 
45260   ** deleted writable. Then free any overflow pages associated with the 
45261   ** entry and finally remove the cell itself from within the page.  
45262   */
45263   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
45264   if( rc ) return rc;
45265   rc = sqlite3PagerWrite(pPage->pDbPage);
45266   if( rc ) return rc;
45267   rc = clearCell(pPage, pCell);
45268   dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), &rc);
45269   if( rc ) return rc;
45270
45271   /* If the cell deleted was not located on a leaf page, then the cursor
45272   ** is currently pointing to the largest entry in the sub-tree headed
45273   ** by the child-page of the cell that was just deleted from an internal
45274   ** node. The cell from the leaf node needs to be moved to the internal
45275   ** node to replace the deleted cell.  */
45276   if( !pPage->leaf ){
45277     MemPage *pLeaf = pCur->apPage[pCur->iPage];
45278     int nCell;
45279     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
45280     unsigned char *pTmp;
45281
45282     pCell = findCell(pLeaf, pLeaf->nCell-1);
45283     nCell = cellSizePtr(pLeaf, pCell);
45284     assert( MX_CELL_SIZE(pBt)>=nCell );
45285
45286     allocateTempSpace(pBt);
45287     pTmp = pBt->pTmpSpace;
45288
45289     rc = sqlite3PagerWrite(pLeaf->pDbPage);
45290     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
45291     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
45292     if( rc ) return rc;
45293   }
45294
45295   /* Balance the tree. If the entry deleted was located on a leaf page,
45296   ** then the cursor still points to that page. In this case the first
45297   ** call to balance() repairs the tree, and the if(...) condition is
45298   ** never true.
45299   **
45300   ** Otherwise, if the entry deleted was on an internal node page, then
45301   ** pCur is pointing to the leaf page from which a cell was removed to
45302   ** replace the cell deleted from the internal node. This is slightly
45303   ** tricky as the leaf node may be underfull, and the internal node may
45304   ** be either under or overfull. In this case run the balancing algorithm
45305   ** on the leaf node first. If the balance proceeds far enough up the
45306   ** tree that we can be sure that any problem in the internal node has
45307   ** been corrected, so be it. Otherwise, after balancing the leaf node,
45308   ** walk the cursor up the tree to the internal node and balance it as 
45309   ** well.  */
45310   rc = balance(pCur);
45311   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
45312     while( pCur->iPage>iCellDepth ){
45313       releasePage(pCur->apPage[pCur->iPage--]);
45314     }
45315     rc = balance(pCur);
45316   }
45317
45318   if( rc==SQLITE_OK ){
45319     moveToRoot(pCur);
45320   }
45321   return rc;
45322 }
45323
45324 /*
45325 ** Create a new BTree table.  Write into *piTable the page
45326 ** number for the root page of the new table.
45327 **
45328 ** The type of type is determined by the flags parameter.  Only the
45329 ** following values of flags are currently in use.  Other values for
45330 ** flags might not work:
45331 **
45332 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
45333 **     BTREE_ZERODATA                  Used for SQL indices
45334 */
45335 static int btreeCreateTable(Btree *p, int *piTable, int flags){
45336   BtShared *pBt = p->pBt;
45337   MemPage *pRoot;
45338   Pgno pgnoRoot;
45339   int rc;
45340
45341   assert( sqlite3BtreeHoldsMutex(p) );
45342   assert( pBt->inTransaction==TRANS_WRITE );
45343   assert( !pBt->readOnly );
45344
45345 #ifdef SQLITE_OMIT_AUTOVACUUM
45346   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
45347   if( rc ){
45348     return rc;
45349   }
45350 #else
45351   if( pBt->autoVacuum ){
45352     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
45353     MemPage *pPageMove; /* The page to move to. */
45354
45355     /* Creating a new table may probably require moving an existing database
45356     ** to make room for the new tables root page. In case this page turns
45357     ** out to be an overflow page, delete all overflow page-map caches
45358     ** held by open cursors.
45359     */
45360     invalidateAllOverflowCache(pBt);
45361
45362     /* Read the value of meta[3] from the database to determine where the
45363     ** root page of the new table should go. meta[3] is the largest root-page
45364     ** created so far, so the new root-page is (meta[3]+1).
45365     */
45366     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
45367     pgnoRoot++;
45368
45369     /* The new root-page may not be allocated on a pointer-map page, or the
45370     ** PENDING_BYTE page.
45371     */
45372     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
45373         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
45374       pgnoRoot++;
45375     }
45376     assert( pgnoRoot>=3 );
45377
45378     /* Allocate a page. The page that currently resides at pgnoRoot will
45379     ** be moved to the allocated page (unless the allocated page happens
45380     ** to reside at pgnoRoot).
45381     */
45382     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, 1);
45383     if( rc!=SQLITE_OK ){
45384       return rc;
45385     }
45386
45387     if( pgnoMove!=pgnoRoot ){
45388       /* pgnoRoot is the page that will be used for the root-page of
45389       ** the new table (assuming an error did not occur). But we were
45390       ** allocated pgnoMove. If required (i.e. if it was not allocated
45391       ** by extending the file), the current page at position pgnoMove
45392       ** is already journaled.
45393       */
45394       u8 eType = 0;
45395       Pgno iPtrPage = 0;
45396
45397       releasePage(pPageMove);
45398
45399       /* Move the page currently at pgnoRoot to pgnoMove. */
45400       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
45401       if( rc!=SQLITE_OK ){
45402         return rc;
45403       }
45404       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
45405       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
45406         rc = SQLITE_CORRUPT_BKPT;
45407       }
45408       if( rc!=SQLITE_OK ){
45409         releasePage(pRoot);
45410         return rc;
45411       }
45412       assert( eType!=PTRMAP_ROOTPAGE );
45413       assert( eType!=PTRMAP_FREEPAGE );
45414       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
45415       releasePage(pRoot);
45416
45417       /* Obtain the page at pgnoRoot */
45418       if( rc!=SQLITE_OK ){
45419         return rc;
45420       }
45421       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
45422       if( rc!=SQLITE_OK ){
45423         return rc;
45424       }
45425       rc = sqlite3PagerWrite(pRoot->pDbPage);
45426       if( rc!=SQLITE_OK ){
45427         releasePage(pRoot);
45428         return rc;
45429       }
45430     }else{
45431       pRoot = pPageMove;
45432     } 
45433
45434     /* Update the pointer-map and meta-data with the new root-page number. */
45435     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
45436     if( rc ){
45437       releasePage(pRoot);
45438       return rc;
45439     }
45440     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
45441     if( rc ){
45442       releasePage(pRoot);
45443       return rc;
45444     }
45445
45446   }else{
45447     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
45448     if( rc ) return rc;
45449   }
45450 #endif
45451   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
45452   zeroPage(pRoot, flags | PTF_LEAF);
45453   sqlite3PagerUnref(pRoot->pDbPage);
45454   *piTable = (int)pgnoRoot;
45455   return SQLITE_OK;
45456 }
45457 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
45458   int rc;
45459   sqlite3BtreeEnter(p);
45460   rc = btreeCreateTable(p, piTable, flags);
45461   sqlite3BtreeLeave(p);
45462   return rc;
45463 }
45464
45465 /*
45466 ** Erase the given database page and all its children.  Return
45467 ** the page to the freelist.
45468 */
45469 static int clearDatabasePage(
45470   BtShared *pBt,           /* The BTree that contains the table */
45471   Pgno pgno,               /* Page number to clear */
45472   int freePageFlag,        /* Deallocate page if true */
45473   int *pnChange            /* Add number of Cells freed to this counter */
45474 ){
45475   MemPage *pPage;
45476   int rc;
45477   unsigned char *pCell;
45478   int i;
45479
45480   assert( sqlite3_mutex_held(pBt->mutex) );
45481   if( pgno>pagerPagecount(pBt) ){
45482     return SQLITE_CORRUPT_BKPT;
45483   }
45484
45485   rc = getAndInitPage(pBt, pgno, &pPage);
45486   if( rc ) return rc;
45487   for(i=0; i<pPage->nCell; i++){
45488     pCell = findCell(pPage, i);
45489     if( !pPage->leaf ){
45490       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
45491       if( rc ) goto cleardatabasepage_out;
45492     }
45493     rc = clearCell(pPage, pCell);
45494     if( rc ) goto cleardatabasepage_out;
45495   }
45496   if( !pPage->leaf ){
45497     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[8]), 1, pnChange);
45498     if( rc ) goto cleardatabasepage_out;
45499   }else if( pnChange ){
45500     assert( pPage->intKey );
45501     *pnChange += pPage->nCell;
45502   }
45503   if( freePageFlag ){
45504     freePage(pPage, &rc);
45505   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
45506     zeroPage(pPage, pPage->aData[0] | PTF_LEAF);
45507   }
45508
45509 cleardatabasepage_out:
45510   releasePage(pPage);
45511   return rc;
45512 }
45513
45514 /*
45515 ** Delete all information from a single table in the database.  iTable is
45516 ** the page number of the root of the table.  After this routine returns,
45517 ** the root page is empty, but still exists.
45518 **
45519 ** This routine will fail with SQLITE_LOCKED if there are any open
45520 ** read cursors on the table.  Open write cursors are moved to the
45521 ** root of the table.
45522 **
45523 ** If pnChange is not NULL, then table iTable must be an intkey table. The
45524 ** integer value pointed to by pnChange is incremented by the number of
45525 ** entries in the table.
45526 */
45527 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
45528   int rc;
45529   BtShared *pBt = p->pBt;
45530   sqlite3BtreeEnter(p);
45531   assert( p->inTrans==TRANS_WRITE );
45532
45533   /* Invalidate all incrblob cursors open on table iTable (assuming iTable
45534   ** is the root of a table b-tree - if it is not, the following call is
45535   ** a no-op).  */
45536   invalidateIncrblobCursors(p, 0, 1);
45537
45538   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
45539   if( SQLITE_OK==rc ){
45540     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
45541   }
45542   sqlite3BtreeLeave(p);
45543   return rc;
45544 }
45545
45546 /*
45547 ** Erase all information in a table and add the root of the table to
45548 ** the freelist.  Except, the root of the principle table (the one on
45549 ** page 1) is never added to the freelist.
45550 **
45551 ** This routine will fail with SQLITE_LOCKED if there are any open
45552 ** cursors on the table.
45553 **
45554 ** If AUTOVACUUM is enabled and the page at iTable is not the last
45555 ** root page in the database file, then the last root page 
45556 ** in the database file is moved into the slot formerly occupied by
45557 ** iTable and that last slot formerly occupied by the last root page
45558 ** is added to the freelist instead of iTable.  In this say, all
45559 ** root pages are kept at the beginning of the database file, which
45560 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
45561 ** page number that used to be the last root page in the file before
45562 ** the move.  If no page gets moved, *piMoved is set to 0.
45563 ** The last root page is recorded in meta[3] and the value of
45564 ** meta[3] is updated by this procedure.
45565 */
45566 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
45567   int rc;
45568   MemPage *pPage = 0;
45569   BtShared *pBt = p->pBt;
45570
45571   assert( sqlite3BtreeHoldsMutex(p) );
45572   assert( p->inTrans==TRANS_WRITE );
45573
45574   /* It is illegal to drop a table if any cursors are open on the
45575   ** database. This is because in auto-vacuum mode the backend may
45576   ** need to move another root-page to fill a gap left by the deleted
45577   ** root page. If an open cursor was using this page a problem would 
45578   ** occur.
45579   **
45580   ** This error is caught long before control reaches this point.
45581   */
45582   if( NEVER(pBt->pCursor) ){
45583     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
45584     return SQLITE_LOCKED_SHAREDCACHE;
45585   }
45586
45587   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
45588   if( rc ) return rc;
45589   rc = sqlite3BtreeClearTable(p, iTable, 0);
45590   if( rc ){
45591     releasePage(pPage);
45592     return rc;
45593   }
45594
45595   *piMoved = 0;
45596
45597   if( iTable>1 ){
45598 #ifdef SQLITE_OMIT_AUTOVACUUM
45599     freePage(pPage, &rc);
45600     releasePage(pPage);
45601 #else
45602     if( pBt->autoVacuum ){
45603       Pgno maxRootPgno;
45604       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
45605
45606       if( iTable==maxRootPgno ){
45607         /* If the table being dropped is the table with the largest root-page
45608         ** number in the database, put the root page on the free list. 
45609         */
45610         freePage(pPage, &rc);
45611         releasePage(pPage);
45612         if( rc!=SQLITE_OK ){
45613           return rc;
45614         }
45615       }else{
45616         /* The table being dropped does not have the largest root-page
45617         ** number in the database. So move the page that does into the 
45618         ** gap left by the deleted root-page.
45619         */
45620         MemPage *pMove;
45621         releasePage(pPage);
45622         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
45623         if( rc!=SQLITE_OK ){
45624           return rc;
45625         }
45626         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
45627         releasePage(pMove);
45628         if( rc!=SQLITE_OK ){
45629           return rc;
45630         }
45631         pMove = 0;
45632         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
45633         freePage(pMove, &rc);
45634         releasePage(pMove);
45635         if( rc!=SQLITE_OK ){
45636           return rc;
45637         }
45638         *piMoved = maxRootPgno;
45639       }
45640
45641       /* Set the new 'max-root-page' value in the database header. This
45642       ** is the old value less one, less one more if that happens to
45643       ** be a root-page number, less one again if that is the
45644       ** PENDING_BYTE_PAGE.
45645       */
45646       maxRootPgno--;
45647       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
45648              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
45649         maxRootPgno--;
45650       }
45651       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
45652
45653       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
45654     }else{
45655       freePage(pPage, &rc);
45656       releasePage(pPage);
45657     }
45658 #endif
45659   }else{
45660     /* If sqlite3BtreeDropTable was called on page 1.
45661     ** This really never should happen except in a corrupt
45662     ** database. 
45663     */
45664     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
45665     releasePage(pPage);
45666   }
45667   return rc;  
45668 }
45669 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
45670   int rc;
45671   sqlite3BtreeEnter(p);
45672   rc = btreeDropTable(p, iTable, piMoved);
45673   sqlite3BtreeLeave(p);
45674   return rc;
45675 }
45676
45677
45678 /*
45679 ** This function may only be called if the b-tree connection already
45680 ** has a read or write transaction open on the database.
45681 **
45682 ** Read the meta-information out of a database file.  Meta[0]
45683 ** is the number of free pages currently in the database.  Meta[1]
45684 ** through meta[15] are available for use by higher layers.  Meta[0]
45685 ** is read-only, the others are read/write.
45686 ** 
45687 ** The schema layer numbers meta values differently.  At the schema
45688 ** layer (and the SetCookie and ReadCookie opcodes) the number of
45689 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
45690 */
45691 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
45692   BtShared *pBt = p->pBt;
45693
45694   sqlite3BtreeEnter(p);
45695   assert( p->inTrans>TRANS_NONE );
45696   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
45697   assert( pBt->pPage1 );
45698   assert( idx>=0 && idx<=15 );
45699
45700   *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
45701
45702   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
45703   ** database, mark the database as read-only.  */
45704 #ifdef SQLITE_OMIT_AUTOVACUUM
45705   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ) pBt->readOnly = 1;
45706 #endif
45707
45708   sqlite3BtreeLeave(p);
45709 }
45710
45711 /*
45712 ** Write meta-information back into the database.  Meta[0] is
45713 ** read-only and may not be written.
45714 */
45715 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
45716   BtShared *pBt = p->pBt;
45717   unsigned char *pP1;
45718   int rc;
45719   assert( idx>=1 && idx<=15 );
45720   sqlite3BtreeEnter(p);
45721   assert( p->inTrans==TRANS_WRITE );
45722   assert( pBt->pPage1!=0 );
45723   pP1 = pBt->pPage1->aData;
45724   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
45725   if( rc==SQLITE_OK ){
45726     put4byte(&pP1[36 + idx*4], iMeta);
45727 #ifndef SQLITE_OMIT_AUTOVACUUM
45728     if( idx==BTREE_INCR_VACUUM ){
45729       assert( pBt->autoVacuum || iMeta==0 );
45730       assert( iMeta==0 || iMeta==1 );
45731       pBt->incrVacuum = (u8)iMeta;
45732     }
45733 #endif
45734   }
45735   sqlite3BtreeLeave(p);
45736   return rc;
45737 }
45738
45739 #ifndef SQLITE_OMIT_BTREECOUNT
45740 /*
45741 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
45742 ** number of entries in the b-tree and write the result to *pnEntry.
45743 **
45744 ** SQLITE_OK is returned if the operation is successfully executed. 
45745 ** Otherwise, if an error is encountered (i.e. an IO error or database
45746 ** corruption) an SQLite error code is returned.
45747 */
45748 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
45749   i64 nEntry = 0;                      /* Value to return in *pnEntry */
45750   int rc;                              /* Return code */
45751   rc = moveToRoot(pCur);
45752
45753   /* Unless an error occurs, the following loop runs one iteration for each
45754   ** page in the B-Tree structure (not including overflow pages). 
45755   */
45756   while( rc==SQLITE_OK ){
45757     int iIdx;                          /* Index of child node in parent */
45758     MemPage *pPage;                    /* Current page of the b-tree */
45759
45760     /* If this is a leaf page or the tree is not an int-key tree, then 
45761     ** this page contains countable entries. Increment the entry counter
45762     ** accordingly.
45763     */
45764     pPage = pCur->apPage[pCur->iPage];
45765     if( pPage->leaf || !pPage->intKey ){
45766       nEntry += pPage->nCell;
45767     }
45768
45769     /* pPage is a leaf node. This loop navigates the cursor so that it 
45770     ** points to the first interior cell that it points to the parent of
45771     ** the next page in the tree that has not yet been visited. The
45772     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
45773     ** of the page, or to the number of cells in the page if the next page
45774     ** to visit is the right-child of its parent.
45775     **
45776     ** If all pages in the tree have been visited, return SQLITE_OK to the
45777     ** caller.
45778     */
45779     if( pPage->leaf ){
45780       do {
45781         if( pCur->iPage==0 ){
45782           /* All pages of the b-tree have been visited. Return successfully. */
45783           *pnEntry = nEntry;
45784           return SQLITE_OK;
45785         }
45786         moveToParent(pCur);
45787       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
45788
45789       pCur->aiIdx[pCur->iPage]++;
45790       pPage = pCur->apPage[pCur->iPage];
45791     }
45792
45793     /* Descend to the child node of the cell that the cursor currently 
45794     ** points at. This is the right-child if (iIdx==pPage->nCell).
45795     */
45796     iIdx = pCur->aiIdx[pCur->iPage];
45797     if( iIdx==pPage->nCell ){
45798       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
45799     }else{
45800       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
45801     }
45802   }
45803
45804   /* An error has occurred. Return an error code. */
45805   return rc;
45806 }
45807 #endif
45808
45809 /*
45810 ** Return the pager associated with a BTree.  This routine is used for
45811 ** testing and debugging only.
45812 */
45813 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
45814   return p->pBt->pPager;
45815 }
45816
45817 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
45818 /*
45819 ** Append a message to the error message string.
45820 */
45821 static void checkAppendMsg(
45822   IntegrityCk *pCheck,
45823   char *zMsg1,
45824   const char *zFormat,
45825   ...
45826 ){
45827   va_list ap;
45828   if( !pCheck->mxErr ) return;
45829   pCheck->mxErr--;
45830   pCheck->nErr++;
45831   va_start(ap, zFormat);
45832   if( pCheck->errMsg.nChar ){
45833     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
45834   }
45835   if( zMsg1 ){
45836     sqlite3StrAccumAppend(&pCheck->errMsg, zMsg1, -1);
45837   }
45838   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
45839   va_end(ap);
45840   if( pCheck->errMsg.mallocFailed ){
45841     pCheck->mallocFailed = 1;
45842   }
45843 }
45844 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
45845
45846 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
45847 /*
45848 ** Add 1 to the reference count for page iPage.  If this is the second
45849 ** reference to the page, add an error message to pCheck->zErrMsg.
45850 ** Return 1 if there are 2 ore more references to the page and 0 if
45851 ** if this is the first reference to the page.
45852 **
45853 ** Also check that the page number is in bounds.
45854 */
45855 static int checkRef(IntegrityCk *pCheck, Pgno iPage, char *zContext){
45856   if( iPage==0 ) return 1;
45857   if( iPage>pCheck->nPage ){
45858     checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
45859     return 1;
45860   }
45861   if( pCheck->anRef[iPage]==1 ){
45862     checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
45863     return 1;
45864   }
45865   return  (pCheck->anRef[iPage]++)>1;
45866 }
45867
45868 #ifndef SQLITE_OMIT_AUTOVACUUM
45869 /*
45870 ** Check that the entry in the pointer-map for page iChild maps to 
45871 ** page iParent, pointer type ptrType. If not, append an error message
45872 ** to pCheck.
45873 */
45874 static void checkPtrmap(
45875   IntegrityCk *pCheck,   /* Integrity check context */
45876   Pgno iChild,           /* Child page number */
45877   u8 eType,              /* Expected pointer map type */
45878   Pgno iParent,          /* Expected pointer map parent page number */
45879   char *zContext         /* Context description (used for error msg) */
45880 ){
45881   int rc;
45882   u8 ePtrmapType;
45883   Pgno iPtrmapParent;
45884
45885   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
45886   if( rc!=SQLITE_OK ){
45887     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
45888     checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
45889     return;
45890   }
45891
45892   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
45893     checkAppendMsg(pCheck, zContext, 
45894       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
45895       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
45896   }
45897 }
45898 #endif
45899
45900 /*
45901 ** Check the integrity of the freelist or of an overflow page list.
45902 ** Verify that the number of pages on the list is N.
45903 */
45904 static void checkList(
45905   IntegrityCk *pCheck,  /* Integrity checking context */
45906   int isFreeList,       /* True for a freelist.  False for overflow page list */
45907   int iPage,            /* Page number for first page in the list */
45908   int N,                /* Expected number of pages in the list */
45909   char *zContext        /* Context for error messages */
45910 ){
45911   int i;
45912   int expected = N;
45913   int iFirst = iPage;
45914   while( N-- > 0 && pCheck->mxErr ){
45915     DbPage *pOvflPage;
45916     unsigned char *pOvflData;
45917     if( iPage<1 ){
45918       checkAppendMsg(pCheck, zContext,
45919          "%d of %d pages missing from overflow list starting at %d",
45920           N+1, expected, iFirst);
45921       break;
45922     }
45923     if( checkRef(pCheck, iPage, zContext) ) break;
45924     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
45925       checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
45926       break;
45927     }
45928     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
45929     if( isFreeList ){
45930       int n = get4byte(&pOvflData[4]);
45931 #ifndef SQLITE_OMIT_AUTOVACUUM
45932       if( pCheck->pBt->autoVacuum ){
45933         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0, zContext);
45934       }
45935 #endif
45936       if( n>pCheck->pBt->usableSize/4-2 ){
45937         checkAppendMsg(pCheck, zContext,
45938            "freelist leaf count too big on page %d", iPage);
45939         N--;
45940       }else{
45941         for(i=0; i<n; i++){
45942           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
45943 #ifndef SQLITE_OMIT_AUTOVACUUM
45944           if( pCheck->pBt->autoVacuum ){
45945             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
45946           }
45947 #endif
45948           checkRef(pCheck, iFreePage, zContext);
45949         }
45950         N -= n;
45951       }
45952     }
45953 #ifndef SQLITE_OMIT_AUTOVACUUM
45954     else{
45955       /* If this database supports auto-vacuum and iPage is not the last
45956       ** page in this overflow list, check that the pointer-map entry for
45957       ** the following page matches iPage.
45958       */
45959       if( pCheck->pBt->autoVacuum && N>0 ){
45960         i = get4byte(pOvflData);
45961         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage, zContext);
45962       }
45963     }
45964 #endif
45965     iPage = get4byte(pOvflData);
45966     sqlite3PagerUnref(pOvflPage);
45967   }
45968 }
45969 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
45970
45971 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
45972 /*
45973 ** Do various sanity checks on a single page of a tree.  Return
45974 ** the tree depth.  Root pages return 0.  Parents of root pages
45975 ** return 1, and so forth.
45976 ** 
45977 ** These checks are done:
45978 **
45979 **      1.  Make sure that cells and freeblocks do not overlap
45980 **          but combine to completely cover the page.
45981 **  NO  2.  Make sure cell keys are in order.
45982 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
45983 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
45984 **      5.  Check the integrity of overflow pages.
45985 **      6.  Recursively call checkTreePage on all children.
45986 **      7.  Verify that the depth of all children is the same.
45987 **      8.  Make sure this page is at least 33% full or else it is
45988 **          the root of the tree.
45989 */
45990 static int checkTreePage(
45991   IntegrityCk *pCheck,  /* Context for the sanity check */
45992   int iPage,            /* Page number of the page to check */
45993   char *zParentContext, /* Parent context */
45994   i64 *pnParentMinKey, 
45995   i64 *pnParentMaxKey
45996 ){
45997   MemPage *pPage;
45998   int i, rc, depth, d2, pgno, cnt;
45999   int hdr, cellStart;
46000   int nCell;
46001   u8 *data;
46002   BtShared *pBt;
46003   int usableSize;
46004   char zContext[100];
46005   char *hit = 0;
46006   i64 nMinKey = 0;
46007   i64 nMaxKey = 0;
46008
46009   sqlite3_snprintf(sizeof(zContext), zContext, "Page %d: ", iPage);
46010
46011   /* Check that the page exists
46012   */
46013   pBt = pCheck->pBt;
46014   usableSize = pBt->usableSize;
46015   if( iPage==0 ) return 0;
46016   if( checkRef(pCheck, iPage, zParentContext) ) return 0;
46017   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
46018     checkAppendMsg(pCheck, zContext,
46019        "unable to get the page. error code=%d", rc);
46020     return 0;
46021   }
46022
46023   /* Clear MemPage.isInit to make sure the corruption detection code in
46024   ** btreeInitPage() is executed.  */
46025   pPage->isInit = 0;
46026   if( (rc = btreeInitPage(pPage))!=0 ){
46027     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
46028     checkAppendMsg(pCheck, zContext, 
46029                    "btreeInitPage() returns error code %d", rc);
46030     releasePage(pPage);
46031     return 0;
46032   }
46033
46034   /* Check out all the cells.
46035   */
46036   depth = 0;
46037   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
46038     u8 *pCell;
46039     u32 sz;
46040     CellInfo info;
46041
46042     /* Check payload overflow pages
46043     */
46044     sqlite3_snprintf(sizeof(zContext), zContext,
46045              "On tree page %d cell %d: ", iPage, i);
46046     pCell = findCell(pPage,i);
46047     btreeParseCellPtr(pPage, pCell, &info);
46048     sz = info.nData;
46049     if( !pPage->intKey ) sz += (int)info.nKey;
46050     /* For intKey pages, check that the keys are in order.
46051     */
46052     else if( i==0 ) nMinKey = nMaxKey = info.nKey;
46053     else{
46054       if( info.nKey <= nMaxKey ){
46055         checkAppendMsg(pCheck, zContext, 
46056             "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
46057       }
46058       nMaxKey = info.nKey;
46059     }
46060     assert( sz==info.nPayload );
46061     if( (sz>info.nLocal) 
46062      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
46063     ){
46064       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
46065       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
46066 #ifndef SQLITE_OMIT_AUTOVACUUM
46067       if( pBt->autoVacuum ){
46068         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage, zContext);
46069       }
46070 #endif
46071       checkList(pCheck, 0, pgnoOvfl, nPage, zContext);
46072     }
46073
46074     /* Check sanity of left child page.
46075     */
46076     if( !pPage->leaf ){
46077       pgno = get4byte(pCell);
46078 #ifndef SQLITE_OMIT_AUTOVACUUM
46079       if( pBt->autoVacuum ){
46080         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
46081       }
46082 #endif
46083       d2 = checkTreePage(pCheck, pgno, zContext, &nMinKey, i==0 ? NULL : &nMaxKey);
46084       if( i>0 && d2!=depth ){
46085         checkAppendMsg(pCheck, zContext, "Child page depth differs");
46086       }
46087       depth = d2;
46088     }
46089   }
46090
46091   if( !pPage->leaf ){
46092     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
46093     sqlite3_snprintf(sizeof(zContext), zContext, 
46094                      "On page %d at right child: ", iPage);
46095 #ifndef SQLITE_OMIT_AUTOVACUUM
46096     if( pBt->autoVacuum ){
46097       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage, zContext);
46098     }
46099 #endif
46100     checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
46101   }
46102  
46103   /* For intKey leaf pages, check that the min/max keys are in order
46104   ** with any left/parent/right pages.
46105   */
46106   if( pPage->leaf && pPage->intKey ){
46107     /* if we are a left child page */
46108     if( pnParentMinKey ){
46109       /* if we are the left most child page */
46110       if( !pnParentMaxKey ){
46111         if( nMaxKey > *pnParentMinKey ){
46112           checkAppendMsg(pCheck, zContext, 
46113               "Rowid %lld out of order (max larger than parent min of %lld)",
46114               nMaxKey, *pnParentMinKey);
46115         }
46116       }else{
46117         if( nMinKey <= *pnParentMinKey ){
46118           checkAppendMsg(pCheck, zContext, 
46119               "Rowid %lld out of order (min less than parent min of %lld)",
46120               nMinKey, *pnParentMinKey);
46121         }
46122         if( nMaxKey > *pnParentMaxKey ){
46123           checkAppendMsg(pCheck, zContext, 
46124               "Rowid %lld out of order (max larger than parent max of %lld)",
46125               nMaxKey, *pnParentMaxKey);
46126         }
46127         *pnParentMinKey = nMaxKey;
46128       }
46129     /* else if we're a right child page */
46130     } else if( pnParentMaxKey ){
46131       if( nMinKey <= *pnParentMaxKey ){
46132         checkAppendMsg(pCheck, zContext, 
46133             "Rowid %lld out of order (min less than parent max of %lld)",
46134             nMinKey, *pnParentMaxKey);
46135       }
46136     }
46137   }
46138
46139   /* Check for complete coverage of the page
46140   */
46141   data = pPage->aData;
46142   hdr = pPage->hdrOffset;
46143   hit = sqlite3PageMalloc( pBt->pageSize );
46144   if( hit==0 ){
46145     pCheck->mallocFailed = 1;
46146   }else{
46147     u16 contentOffset = get2byte(&data[hdr+5]);
46148     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
46149     memset(hit+contentOffset, 0, usableSize-contentOffset);
46150     memset(hit, 1, contentOffset);
46151     nCell = get2byte(&data[hdr+3]);
46152     cellStart = hdr + 12 - 4*pPage->leaf;
46153     for(i=0; i<nCell; i++){
46154       int pc = get2byte(&data[cellStart+i*2]);
46155       u16 size = 1024;
46156       int j;
46157       if( pc<=usableSize-4 ){
46158         size = cellSizePtr(pPage, &data[pc]);
46159       }
46160       if( (pc+size-1)>=usableSize ){
46161         checkAppendMsg(pCheck, 0, 
46162             "Corruption detected in cell %d on page %d",i,iPage);
46163       }else{
46164         for(j=pc+size-1; j>=pc; j--) hit[j]++;
46165       }
46166     }
46167     i = get2byte(&data[hdr+1]);
46168     while( i>0 ){
46169       int size, j;
46170       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
46171       size = get2byte(&data[i+2]);
46172       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
46173       for(j=i+size-1; j>=i; j--) hit[j]++;
46174       j = get2byte(&data[i]);
46175       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
46176       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
46177       i = j;
46178     }
46179     for(i=cnt=0; i<usableSize; i++){
46180       if( hit[i]==0 ){
46181         cnt++;
46182       }else if( hit[i]>1 ){
46183         checkAppendMsg(pCheck, 0,
46184           "Multiple uses for byte %d of page %d", i, iPage);
46185         break;
46186       }
46187     }
46188     if( cnt!=data[hdr+7] ){
46189       checkAppendMsg(pCheck, 0, 
46190           "Fragmentation of %d bytes reported as %d on page %d",
46191           cnt, data[hdr+7], iPage);
46192     }
46193   }
46194   sqlite3PageFree(hit);
46195   releasePage(pPage);
46196   return depth+1;
46197 }
46198 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
46199
46200 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
46201 /*
46202 ** This routine does a complete check of the given BTree file.  aRoot[] is
46203 ** an array of pages numbers were each page number is the root page of
46204 ** a table.  nRoot is the number of entries in aRoot.
46205 **
46206 ** A read-only or read-write transaction must be opened before calling
46207 ** this function.
46208 **
46209 ** Write the number of error seen in *pnErr.  Except for some memory
46210 ** allocation errors,  an error message held in memory obtained from
46211 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
46212 ** returned.  If a memory allocation error occurs, NULL is returned.
46213 */
46214 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
46215   Btree *p,     /* The btree to be checked */
46216   int *aRoot,   /* An array of root pages numbers for individual trees */
46217   int nRoot,    /* Number of entries in aRoot[] */
46218   int mxErr,    /* Stop reporting errors after this many */
46219   int *pnErr    /* Write number of errors seen to this variable */
46220 ){
46221   Pgno i;
46222   int nRef;
46223   IntegrityCk sCheck;
46224   BtShared *pBt = p->pBt;
46225   char zErr[100];
46226
46227   sqlite3BtreeEnter(p);
46228   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
46229   nRef = sqlite3PagerRefcount(pBt->pPager);
46230   sCheck.pBt = pBt;
46231   sCheck.pPager = pBt->pPager;
46232   sCheck.nPage = pagerPagecount(sCheck.pBt);
46233   sCheck.mxErr = mxErr;
46234   sCheck.nErr = 0;
46235   sCheck.mallocFailed = 0;
46236   *pnErr = 0;
46237   if( sCheck.nPage==0 ){
46238     sqlite3BtreeLeave(p);
46239     return 0;
46240   }
46241   sCheck.anRef = sqlite3Malloc( (sCheck.nPage+1)*sizeof(sCheck.anRef[0]) );
46242   if( !sCheck.anRef ){
46243     *pnErr = 1;
46244     sqlite3BtreeLeave(p);
46245     return 0;
46246   }
46247   for(i=0; i<=sCheck.nPage; i++){ sCheck.anRef[i] = 0; }
46248   i = PENDING_BYTE_PAGE(pBt);
46249   if( i<=sCheck.nPage ){
46250     sCheck.anRef[i] = 1;
46251   }
46252   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), 20000);
46253
46254   /* Check the integrity of the freelist
46255   */
46256   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
46257             get4byte(&pBt->pPage1->aData[36]), "Main freelist: ");
46258
46259   /* Check all the tables.
46260   */
46261   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
46262     if( aRoot[i]==0 ) continue;
46263 #ifndef SQLITE_OMIT_AUTOVACUUM
46264     if( pBt->autoVacuum && aRoot[i]>1 ){
46265       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0, 0);
46266     }
46267 #endif
46268     checkTreePage(&sCheck, aRoot[i], "List of tree roots: ", NULL, NULL);
46269   }
46270
46271   /* Make sure every page in the file is referenced
46272   */
46273   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
46274 #ifdef SQLITE_OMIT_AUTOVACUUM
46275     if( sCheck.anRef[i]==0 ){
46276       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
46277     }
46278 #else
46279     /* If the database supports auto-vacuum, make sure no tables contain
46280     ** references to pointer-map pages.
46281     */
46282     if( sCheck.anRef[i]==0 && 
46283        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
46284       checkAppendMsg(&sCheck, 0, "Page %d is never used", i);
46285     }
46286     if( sCheck.anRef[i]!=0 && 
46287        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
46288       checkAppendMsg(&sCheck, 0, "Pointer map page %d is referenced", i);
46289     }
46290 #endif
46291   }
46292
46293   /* Make sure this analysis did not leave any unref() pages.
46294   ** This is an internal consistency check; an integrity check
46295   ** of the integrity check.
46296   */
46297   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
46298     checkAppendMsg(&sCheck, 0, 
46299       "Outstanding page count goes from %d to %d during this analysis",
46300       nRef, sqlite3PagerRefcount(pBt->pPager)
46301     );
46302   }
46303
46304   /* Clean  up and report errors.
46305   */
46306   sqlite3BtreeLeave(p);
46307   sqlite3_free(sCheck.anRef);
46308   if( sCheck.mallocFailed ){
46309     sqlite3StrAccumReset(&sCheck.errMsg);
46310     *pnErr = sCheck.nErr+1;
46311     return 0;
46312   }
46313   *pnErr = sCheck.nErr;
46314   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
46315   return sqlite3StrAccumFinish(&sCheck.errMsg);
46316 }
46317 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
46318
46319 /*
46320 ** Return the full pathname of the underlying database file.
46321 **
46322 ** The pager filename is invariant as long as the pager is
46323 ** open so it is safe to access without the BtShared mutex.
46324 */
46325 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
46326   assert( p->pBt->pPager!=0 );
46327   return sqlite3PagerFilename(p->pBt->pPager);
46328 }
46329
46330 /*
46331 ** Return the pathname of the journal file for this database. The return
46332 ** value of this routine is the same regardless of whether the journal file
46333 ** has been created or not.
46334 **
46335 ** The pager journal filename is invariant as long as the pager is
46336 ** open so it is safe to access without the BtShared mutex.
46337 */
46338 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
46339   assert( p->pBt->pPager!=0 );
46340   return sqlite3PagerJournalname(p->pBt->pPager);
46341 }
46342
46343 /*
46344 ** Return non-zero if a transaction is active.
46345 */
46346 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
46347   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
46348   return (p && (p->inTrans==TRANS_WRITE));
46349 }
46350
46351 /*
46352 ** Return non-zero if a read (or write) transaction is active.
46353 */
46354 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
46355   assert( p );
46356   assert( sqlite3_mutex_held(p->db->mutex) );
46357   return p->inTrans!=TRANS_NONE;
46358 }
46359
46360 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
46361   assert( p );
46362   assert( sqlite3_mutex_held(p->db->mutex) );
46363   return p->nBackup!=0;
46364 }
46365
46366 /*
46367 ** This function returns a pointer to a blob of memory associated with
46368 ** a single shared-btree. The memory is used by client code for its own
46369 ** purposes (for example, to store a high-level schema associated with 
46370 ** the shared-btree). The btree layer manages reference counting issues.
46371 **
46372 ** The first time this is called on a shared-btree, nBytes bytes of memory
46373 ** are allocated, zeroed, and returned to the caller. For each subsequent 
46374 ** call the nBytes parameter is ignored and a pointer to the same blob
46375 ** of memory returned. 
46376 **
46377 ** If the nBytes parameter is 0 and the blob of memory has not yet been
46378 ** allocated, a null pointer is returned. If the blob has already been
46379 ** allocated, it is returned as normal.
46380 **
46381 ** Just before the shared-btree is closed, the function passed as the 
46382 ** xFree argument when the memory allocation was made is invoked on the 
46383 ** blob of allocated memory. This function should not call sqlite3_free()
46384 ** on the memory, the btree layer does that.
46385 */
46386 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
46387   BtShared *pBt = p->pBt;
46388   sqlite3BtreeEnter(p);
46389   if( !pBt->pSchema && nBytes ){
46390     pBt->pSchema = sqlite3MallocZero(nBytes);
46391     pBt->xFreeSchema = xFree;
46392   }
46393   sqlite3BtreeLeave(p);
46394   return pBt->pSchema;
46395 }
46396
46397 /*
46398 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
46399 ** btree as the argument handle holds an exclusive lock on the 
46400 ** sqlite_master table. Otherwise SQLITE_OK.
46401 */
46402 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
46403   int rc;
46404   assert( sqlite3_mutex_held(p->db->mutex) );
46405   sqlite3BtreeEnter(p);
46406   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
46407   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
46408   sqlite3BtreeLeave(p);
46409   return rc;
46410 }
46411
46412
46413 #ifndef SQLITE_OMIT_SHARED_CACHE
46414 /*
46415 ** Obtain a lock on the table whose root page is iTab.  The
46416 ** lock is a write lock if isWritelock is true or a read lock
46417 ** if it is false.
46418 */
46419 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
46420   int rc = SQLITE_OK;
46421   assert( p->inTrans!=TRANS_NONE );
46422   if( p->sharable ){
46423     u8 lockType = READ_LOCK + isWriteLock;
46424     assert( READ_LOCK+1==WRITE_LOCK );
46425     assert( isWriteLock==0 || isWriteLock==1 );
46426
46427     sqlite3BtreeEnter(p);
46428     rc = querySharedCacheTableLock(p, iTab, lockType);
46429     if( rc==SQLITE_OK ){
46430       rc = setSharedCacheTableLock(p, iTab, lockType);
46431     }
46432     sqlite3BtreeLeave(p);
46433   }
46434   return rc;
46435 }
46436 #endif
46437
46438 #ifndef SQLITE_OMIT_INCRBLOB
46439 /*
46440 ** Argument pCsr must be a cursor opened for writing on an 
46441 ** INTKEY table currently pointing at a valid table entry. 
46442 ** This function modifies the data stored as part of that entry.
46443 **
46444 ** Only the data content may only be modified, it is not possible to 
46445 ** change the length of the data stored. If this function is called with
46446 ** parameters that attempt to write past the end of the existing data,
46447 ** no modifications are made and SQLITE_CORRUPT is returned.
46448 */
46449 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
46450   int rc;
46451   assert( cursorHoldsMutex(pCsr) );
46452   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
46453   assert( pCsr->isIncrblobHandle );
46454
46455   rc = restoreCursorPosition(pCsr);
46456   if( rc!=SQLITE_OK ){
46457     return rc;
46458   }
46459   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
46460   if( pCsr->eState!=CURSOR_VALID ){
46461     return SQLITE_ABORT;
46462   }
46463
46464   /* Check some assumptions: 
46465   **   (a) the cursor is open for writing,
46466   **   (b) there is a read/write transaction open,
46467   **   (c) the connection holds a write-lock on the table (if required),
46468   **   (d) there are no conflicting read-locks, and
46469   **   (e) the cursor points at a valid row of an intKey table.
46470   */
46471   if( !pCsr->wrFlag ){
46472     return SQLITE_READONLY;
46473   }
46474   assert( !pCsr->pBt->readOnly && pCsr->pBt->inTransaction==TRANS_WRITE );
46475   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
46476   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
46477   assert( pCsr->apPage[pCsr->iPage]->intKey );
46478
46479   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
46480 }
46481
46482 /* 
46483 ** Set a flag on this cursor to cache the locations of pages from the 
46484 ** overflow list for the current row. This is used by cursors opened
46485 ** for incremental blob IO only.
46486 **
46487 ** This function sets a flag only. The actual page location cache
46488 ** (stored in BtCursor.aOverflow[]) is allocated and used by function
46489 ** accessPayload() (the worker function for sqlite3BtreeData() and
46490 ** sqlite3BtreePutData()).
46491 */
46492 SQLITE_PRIVATE void sqlite3BtreeCacheOverflow(BtCursor *pCur){
46493   assert( cursorHoldsMutex(pCur) );
46494   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
46495   assert(!pCur->isIncrblobHandle);
46496   assert(!pCur->aOverflow);
46497   pCur->isIncrblobHandle = 1;
46498 }
46499 #endif
46500
46501 /************** End of btree.c ***********************************************/
46502 /************** Begin file backup.c ******************************************/
46503 /*
46504 ** 2009 January 28
46505 **
46506 ** The author disclaims copyright to this source code.  In place of
46507 ** a legal notice, here is a blessing:
46508 **
46509 **    May you do good and not evil.
46510 **    May you find forgiveness for yourself and forgive others.
46511 **    May you share freely, never taking more than you give.
46512 **
46513 *************************************************************************
46514 ** This file contains the implementation of the sqlite3_backup_XXX() 
46515 ** API functions and the related features.
46516 */
46517
46518 /* Macro to find the minimum of two numeric values.
46519 */
46520 #ifndef MIN
46521 # define MIN(x,y) ((x)<(y)?(x):(y))
46522 #endif
46523
46524 /*
46525 ** Structure allocated for each backup operation.
46526 */
46527 struct sqlite3_backup {
46528   sqlite3* pDestDb;        /* Destination database handle */
46529   Btree *pDest;            /* Destination b-tree file */
46530   u32 iDestSchema;         /* Original schema cookie in destination */
46531   int bDestLocked;         /* True once a write-transaction is open on pDest */
46532
46533   Pgno iNext;              /* Page number of the next source page to copy */
46534   sqlite3* pSrcDb;         /* Source database handle */
46535   Btree *pSrc;             /* Source b-tree file */
46536
46537   int rc;                  /* Backup process error code */
46538
46539   /* These two variables are set by every call to backup_step(). They are
46540   ** read by calls to backup_remaining() and backup_pagecount().
46541   */
46542   Pgno nRemaining;         /* Number of pages left to copy */
46543   Pgno nPagecount;         /* Total number of pages to copy */
46544
46545   int isAttached;          /* True once backup has been registered with pager */
46546   sqlite3_backup *pNext;   /* Next backup associated with source pager */
46547 };
46548
46549 /*
46550 ** THREAD SAFETY NOTES:
46551 **
46552 **   Once it has been created using backup_init(), a single sqlite3_backup
46553 **   structure may be accessed via two groups of thread-safe entry points:
46554 **
46555 **     * Via the sqlite3_backup_XXX() API function backup_step() and 
46556 **       backup_finish(). Both these functions obtain the source database
46557 **       handle mutex and the mutex associated with the source BtShared 
46558 **       structure, in that order.
46559 **
46560 **     * Via the BackupUpdate() and BackupRestart() functions, which are
46561 **       invoked by the pager layer to report various state changes in
46562 **       the page cache associated with the source database. The mutex
46563 **       associated with the source database BtShared structure will always 
46564 **       be held when either of these functions are invoked.
46565 **
46566 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
46567 **   backup_pagecount() are not thread-safe functions. If they are called
46568 **   while some other thread is calling backup_step() or backup_finish(),
46569 **   the values returned may be invalid. There is no way for a call to
46570 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
46571 **   or backup_pagecount().
46572 **
46573 **   Depending on the SQLite configuration, the database handles and/or
46574 **   the Btree objects may have their own mutexes that require locking.
46575 **   Non-sharable Btrees (in-memory databases for example), do not have
46576 **   associated mutexes.
46577 */
46578
46579 /*
46580 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
46581 ** in connection handle pDb. If such a database cannot be found, return
46582 ** a NULL pointer and write an error message to pErrorDb.
46583 **
46584 ** If the "temp" database is requested, it may need to be opened by this 
46585 ** function. If an error occurs while doing so, return 0 and write an 
46586 ** error message to pErrorDb.
46587 */
46588 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
46589   int i = sqlite3FindDbName(pDb, zDb);
46590
46591   if( i==1 ){
46592     Parse *pParse;
46593     int rc = 0;
46594     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
46595     if( pParse==0 ){
46596       sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
46597       rc = SQLITE_NOMEM;
46598     }else{
46599       pParse->db = pDb;
46600       if( sqlite3OpenTempDatabase(pParse) ){
46601         sqlite3Error(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
46602         rc = SQLITE_ERROR;
46603       }
46604       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
46605       sqlite3StackFree(pErrorDb, pParse);
46606     }
46607     if( rc ){
46608       return 0;
46609     }
46610   }
46611
46612   if( i<0 ){
46613     sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
46614     return 0;
46615   }
46616
46617   return pDb->aDb[i].pBt;
46618 }
46619
46620 /*
46621 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
46622 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
46623 ** a pointer to the new sqlite3_backup object.
46624 **
46625 ** If an error occurs, NULL is returned and an error code and error message
46626 ** stored in database handle pDestDb.
46627 */
46628 SQLITE_API sqlite3_backup *sqlite3_backup_init(
46629   sqlite3* pDestDb,                     /* Database to write to */
46630   const char *zDestDb,                  /* Name of database within pDestDb */
46631   sqlite3* pSrcDb,                      /* Database connection to read from */
46632   const char *zSrcDb                    /* Name of database within pSrcDb */
46633 ){
46634   sqlite3_backup *p;                    /* Value to return */
46635
46636   /* Lock the source database handle. The destination database
46637   ** handle is not locked in this routine, but it is locked in
46638   ** sqlite3_backup_step(). The user is required to ensure that no
46639   ** other thread accesses the destination handle for the duration
46640   ** of the backup operation.  Any attempt to use the destination
46641   ** database connection while a backup is in progress may cause
46642   ** a malfunction or a deadlock.
46643   */
46644   sqlite3_mutex_enter(pSrcDb->mutex);
46645   sqlite3_mutex_enter(pDestDb->mutex);
46646
46647   if( pSrcDb==pDestDb ){
46648     sqlite3Error(
46649         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
46650     );
46651     p = 0;
46652   }else {
46653     /* Allocate space for a new sqlite3_backup object */
46654     p = (sqlite3_backup *)sqlite3_malloc(sizeof(sqlite3_backup));
46655     if( !p ){
46656       sqlite3Error(pDestDb, SQLITE_NOMEM, 0);
46657     }
46658   }
46659
46660   /* If the allocation succeeded, populate the new object. */
46661   if( p ){
46662     memset(p, 0, sizeof(sqlite3_backup));
46663     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
46664     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
46665     p->pDestDb = pDestDb;
46666     p->pSrcDb = pSrcDb;
46667     p->iNext = 1;
46668     p->isAttached = 0;
46669
46670     if( 0==p->pSrc || 0==p->pDest ){
46671       /* One (or both) of the named databases did not exist. An error has
46672       ** already been written into the pDestDb handle. All that is left
46673       ** to do here is free the sqlite3_backup structure.
46674       */
46675       sqlite3_free(p);
46676       p = 0;
46677     }
46678   }
46679   if( p ){
46680     p->pSrc->nBackup++;
46681   }
46682
46683   sqlite3_mutex_leave(pDestDb->mutex);
46684   sqlite3_mutex_leave(pSrcDb->mutex);
46685   return p;
46686 }
46687
46688 /*
46689 ** Argument rc is an SQLite error code. Return true if this error is 
46690 ** considered fatal if encountered during a backup operation. All errors
46691 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
46692 */
46693 static int isFatalError(int rc){
46694   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
46695 }
46696
46697 /*
46698 ** Parameter zSrcData points to a buffer containing the data for 
46699 ** page iSrcPg from the source database. Copy this data into the 
46700 ** destination database.
46701 */
46702 static int backupOnePage(sqlite3_backup *p, Pgno iSrcPg, const u8 *zSrcData){
46703   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
46704   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
46705   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
46706   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
46707   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
46708
46709   int rc = SQLITE_OK;
46710   i64 iOff;
46711
46712   assert( p->bDestLocked );
46713   assert( !isFatalError(p->rc) );
46714   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
46715   assert( zSrcData );
46716
46717   /* Catch the case where the destination is an in-memory database and the
46718   ** page sizes of the source and destination differ. 
46719   */
46720   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(sqlite3BtreePager(p->pDest)) ){
46721     rc = SQLITE_READONLY;
46722   }
46723
46724   /* This loop runs once for each destination page spanned by the source 
46725   ** page. For each iteration, variable iOff is set to the byte offset
46726   ** of the destination page.
46727   */
46728   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
46729     DbPage *pDestPg = 0;
46730     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
46731     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
46732     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
46733      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
46734     ){
46735       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
46736       u8 *zDestData = sqlite3PagerGetData(pDestPg);
46737       u8 *zOut = &zDestData[iOff%nDestPgsz];
46738
46739       /* Copy the data from the source page into the destination page.
46740       ** Then clear the Btree layer MemPage.isInit flag. Both this module
46741       ** and the pager code use this trick (clearing the first byte
46742       ** of the page 'extra' space to invalidate the Btree layers
46743       ** cached parse of the page). MemPage.isInit is marked 
46744       ** "MUST BE FIRST" for this purpose.
46745       */
46746       memcpy(zOut, zIn, nCopy);
46747       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
46748     }
46749     sqlite3PagerUnref(pDestPg);
46750   }
46751
46752   return rc;
46753 }
46754
46755 /*
46756 ** If pFile is currently larger than iSize bytes, then truncate it to
46757 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
46758 ** this function is a no-op.
46759 **
46760 ** Return SQLITE_OK if everything is successful, or an SQLite error 
46761 ** code if an error occurs.
46762 */
46763 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
46764   i64 iCurrent;
46765   int rc = sqlite3OsFileSize(pFile, &iCurrent);
46766   if( rc==SQLITE_OK && iCurrent>iSize ){
46767     rc = sqlite3OsTruncate(pFile, iSize);
46768   }
46769   return rc;
46770 }
46771
46772 /*
46773 ** Register this backup object with the associated source pager for
46774 ** callbacks when pages are changed or the cache invalidated.
46775 */
46776 static void attachBackupObject(sqlite3_backup *p){
46777   sqlite3_backup **pp;
46778   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
46779   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
46780   p->pNext = *pp;
46781   *pp = p;
46782   p->isAttached = 1;
46783 }
46784
46785 /*
46786 ** Copy nPage pages from the source b-tree to the destination.
46787 */
46788 SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
46789   int rc;
46790
46791   sqlite3_mutex_enter(p->pSrcDb->mutex);
46792   sqlite3BtreeEnter(p->pSrc);
46793   if( p->pDestDb ){
46794     sqlite3_mutex_enter(p->pDestDb->mutex);
46795   }
46796
46797   rc = p->rc;
46798   if( !isFatalError(rc) ){
46799     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
46800     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
46801     int ii;                            /* Iterator variable */
46802     int nSrcPage = -1;                 /* Size of source db in pages */
46803     int bCloseTrans = 0;               /* True if src db requires unlocking */
46804
46805     /* If the source pager is currently in a write-transaction, return
46806     ** SQLITE_BUSY immediately.
46807     */
46808     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
46809       rc = SQLITE_BUSY;
46810     }else{
46811       rc = SQLITE_OK;
46812     }
46813
46814     /* Lock the destination database, if it is not locked already. */
46815     if( SQLITE_OK==rc && p->bDestLocked==0
46816      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
46817     ){
46818       p->bDestLocked = 1;
46819       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
46820     }
46821
46822     /* If there is no open read-transaction on the source database, open
46823     ** one now. If a transaction is opened here, then it will be closed
46824     ** before this function exits.
46825     */
46826     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
46827       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
46828       bCloseTrans = 1;
46829     }
46830   
46831     /* Now that there is a read-lock on the source database, query the
46832     ** source pager for the number of pages in the database.
46833     */
46834     if( rc==SQLITE_OK ){
46835       rc = sqlite3PagerPagecount(pSrcPager, &nSrcPage);
46836     }
46837     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
46838       const Pgno iSrcPg = p->iNext;                 /* Source page number */
46839       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
46840         DbPage *pSrcPg;                             /* Source page object */
46841         rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
46842         if( rc==SQLITE_OK ){
46843           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
46844           sqlite3PagerUnref(pSrcPg);
46845         }
46846       }
46847       p->iNext++;
46848     }
46849     if( rc==SQLITE_OK ){
46850       p->nPagecount = nSrcPage;
46851       p->nRemaining = nSrcPage+1-p->iNext;
46852       if( p->iNext>(Pgno)nSrcPage ){
46853         rc = SQLITE_DONE;
46854       }else if( !p->isAttached ){
46855         attachBackupObject(p);
46856       }
46857     }
46858   
46859     /* Update the schema version field in the destination database. This
46860     ** is to make sure that the schema-version really does change in
46861     ** the case where the source and destination databases have the
46862     ** same schema version.
46863     */
46864     if( rc==SQLITE_DONE 
46865      && (rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1))==SQLITE_OK
46866     ){
46867       const int nSrcPagesize = sqlite3BtreeGetPageSize(p->pSrc);
46868       const int nDestPagesize = sqlite3BtreeGetPageSize(p->pDest);
46869       int nDestTruncate;
46870   
46871       if( p->pDestDb ){
46872         sqlite3ResetInternalSchema(p->pDestDb, 0);
46873       }
46874
46875       /* Set nDestTruncate to the final number of pages in the destination
46876       ** database. The complication here is that the destination page
46877       ** size may be different to the source page size. 
46878       **
46879       ** If the source page size is smaller than the destination page size, 
46880       ** round up. In this case the call to sqlite3OsTruncate() below will
46881       ** fix the size of the file. However it is important to call
46882       ** sqlite3PagerTruncateImage() here so that any pages in the 
46883       ** destination file that lie beyond the nDestTruncate page mark are
46884       ** journalled by PagerCommitPhaseOne() before they are destroyed
46885       ** by the file truncation.
46886       */
46887       if( nSrcPagesize<nDestPagesize ){
46888         int ratio = nDestPagesize/nSrcPagesize;
46889         nDestTruncate = (nSrcPage+ratio-1)/ratio;
46890         if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
46891           nDestTruncate--;
46892         }
46893       }else{
46894         nDestTruncate = nSrcPage * (nSrcPagesize/nDestPagesize);
46895       }
46896       sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
46897
46898       if( nSrcPagesize<nDestPagesize ){
46899         /* If the source page-size is smaller than the destination page-size,
46900         ** two extra things may need to happen:
46901         **
46902         **   * The destination may need to be truncated, and
46903         **
46904         **   * Data stored on the pages immediately following the 
46905         **     pending-byte page in the source database may need to be
46906         **     copied into the destination database.
46907         */
46908         const i64 iSize = (i64)nSrcPagesize * (i64)nSrcPage;
46909         sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
46910
46911         assert( pFile );
46912         assert( (i64)nDestTruncate*(i64)nDestPagesize >= iSize || (
46913               nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
46914            && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+nDestPagesize
46915         ));
46916         if( SQLITE_OK==(rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1))
46917          && SQLITE_OK==(rc = backupTruncateFile(pFile, iSize))
46918          && SQLITE_OK==(rc = sqlite3PagerSync(pDestPager))
46919         ){
46920           i64 iOff;
46921           i64 iEnd = MIN(PENDING_BYTE + nDestPagesize, iSize);
46922           for(
46923             iOff=PENDING_BYTE+nSrcPagesize; 
46924             rc==SQLITE_OK && iOff<iEnd; 
46925             iOff+=nSrcPagesize
46926           ){
46927             PgHdr *pSrcPg = 0;
46928             const Pgno iSrcPg = (Pgno)((iOff/nSrcPagesize)+1);
46929             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
46930             if( rc==SQLITE_OK ){
46931               u8 *zData = sqlite3PagerGetData(pSrcPg);
46932               rc = sqlite3OsWrite(pFile, zData, nSrcPagesize, iOff);
46933             }
46934             sqlite3PagerUnref(pSrcPg);
46935           }
46936         }
46937       }else{
46938         rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
46939       }
46940   
46941       /* Finish committing the transaction to the destination database. */
46942       if( SQLITE_OK==rc
46943        && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest))
46944       ){
46945         rc = SQLITE_DONE;
46946       }
46947     }
46948   
46949     /* If bCloseTrans is true, then this function opened a read transaction
46950     ** on the source database. Close the read transaction here. There is
46951     ** no need to check the return values of the btree methods here, as
46952     ** "committing" a read-only transaction cannot fail.
46953     */
46954     if( bCloseTrans ){
46955       TESTONLY( int rc2 );
46956       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
46957       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc);
46958       assert( rc2==SQLITE_OK );
46959     }
46960   
46961     p->rc = rc;
46962   }
46963   if( p->pDestDb ){
46964     sqlite3_mutex_leave(p->pDestDb->mutex);
46965   }
46966   sqlite3BtreeLeave(p->pSrc);
46967   sqlite3_mutex_leave(p->pSrcDb->mutex);
46968   return rc;
46969 }
46970
46971 /*
46972 ** Release all resources associated with an sqlite3_backup* handle.
46973 */
46974 SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
46975   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
46976   sqlite3_mutex *mutex;                /* Mutex to protect source database */
46977   int rc;                              /* Value to return */
46978
46979   /* Enter the mutexes */
46980   if( p==0 ) return SQLITE_OK;
46981   sqlite3_mutex_enter(p->pSrcDb->mutex);
46982   sqlite3BtreeEnter(p->pSrc);
46983   mutex = p->pSrcDb->mutex;
46984   if( p->pDestDb ){
46985     sqlite3_mutex_enter(p->pDestDb->mutex);
46986   }
46987
46988   /* Detach this backup from the source pager. */
46989   if( p->pDestDb ){
46990     p->pSrc->nBackup--;
46991   }
46992   if( p->isAttached ){
46993     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
46994     while( *pp!=p ){
46995       pp = &(*pp)->pNext;
46996     }
46997     *pp = p->pNext;
46998   }
46999
47000   /* If a transaction is still open on the Btree, roll it back. */
47001   sqlite3BtreeRollback(p->pDest);
47002
47003   /* Set the error code of the destination database handle. */
47004   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
47005   sqlite3Error(p->pDestDb, rc, 0);
47006
47007   /* Exit the mutexes and free the backup context structure. */
47008   if( p->pDestDb ){
47009     sqlite3_mutex_leave(p->pDestDb->mutex);
47010   }
47011   sqlite3BtreeLeave(p->pSrc);
47012   if( p->pDestDb ){
47013     sqlite3_free(p);
47014   }
47015   sqlite3_mutex_leave(mutex);
47016   return rc;
47017 }
47018
47019 /*
47020 ** Return the number of pages still to be backed up as of the most recent
47021 ** call to sqlite3_backup_step().
47022 */
47023 SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
47024   return p->nRemaining;
47025 }
47026
47027 /*
47028 ** Return the total number of pages in the source database as of the most 
47029 ** recent call to sqlite3_backup_step().
47030 */
47031 SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
47032   return p->nPagecount;
47033 }
47034
47035 /*
47036 ** This function is called after the contents of page iPage of the
47037 ** source database have been modified. If page iPage has already been 
47038 ** copied into the destination database, then the data written to the
47039 ** destination is now invalidated. The destination copy of iPage needs
47040 ** to be updated with the new data before the backup operation is
47041 ** complete.
47042 **
47043 ** It is assumed that the mutex associated with the BtShared object
47044 ** corresponding to the source database is held when this function is
47045 ** called.
47046 */
47047 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
47048   sqlite3_backup *p;                   /* Iterator variable */
47049   for(p=pBackup; p; p=p->pNext){
47050     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
47051     if( !isFatalError(p->rc) && iPage<p->iNext ){
47052       /* The backup process p has already copied page iPage. But now it
47053       ** has been modified by a transaction on the source pager. Copy
47054       ** the new data into the backup.
47055       */
47056       int rc = backupOnePage(p, iPage, aData);
47057       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
47058       if( rc!=SQLITE_OK ){
47059         p->rc = rc;
47060       }
47061     }
47062   }
47063 }
47064
47065 /*
47066 ** Restart the backup process. This is called when the pager layer
47067 ** detects that the database has been modified by an external database
47068 ** connection. In this case there is no way of knowing which of the
47069 ** pages that have been copied into the destination database are still 
47070 ** valid and which are not, so the entire process needs to be restarted.
47071 **
47072 ** It is assumed that the mutex associated with the BtShared object
47073 ** corresponding to the source database is held when this function is
47074 ** called.
47075 */
47076 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
47077   sqlite3_backup *p;                   /* Iterator variable */
47078   for(p=pBackup; p; p=p->pNext){
47079     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
47080     p->iNext = 1;
47081   }
47082 }
47083
47084 #ifndef SQLITE_OMIT_VACUUM
47085 /*
47086 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
47087 ** must be active for both files.
47088 **
47089 ** The size of file pTo may be reduced by this operation. If anything 
47090 ** goes wrong, the transaction on pTo is rolled back. If successful, the 
47091 ** transaction is committed before returning.
47092 */
47093 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
47094   int rc;
47095   sqlite3_backup b;
47096   sqlite3BtreeEnter(pTo);
47097   sqlite3BtreeEnter(pFrom);
47098
47099   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
47100   ** to 0. This is used by the implementations of sqlite3_backup_step()
47101   ** and sqlite3_backup_finish() to detect that they are being called
47102   ** from this function, not directly by the user.
47103   */
47104   memset(&b, 0, sizeof(b));
47105   b.pSrcDb = pFrom->db;
47106   b.pSrc = pFrom;
47107   b.pDest = pTo;
47108   b.iNext = 1;
47109
47110   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
47111   ** file. By passing this as the number of pages to copy to
47112   ** sqlite3_backup_step(), we can guarantee that the copy finishes 
47113   ** within a single call (unless an error occurs). The assert() statement
47114   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
47115   ** or an error code.
47116   */
47117   sqlite3_backup_step(&b, 0x7FFFFFFF);
47118   assert( b.rc!=SQLITE_OK );
47119   rc = sqlite3_backup_finish(&b);
47120   if( rc==SQLITE_OK ){
47121     pTo->pBt->pageSizeFixed = 0;
47122   }
47123
47124   sqlite3BtreeLeave(pFrom);
47125   sqlite3BtreeLeave(pTo);
47126   return rc;
47127 }
47128 #endif /* SQLITE_OMIT_VACUUM */
47129
47130 /************** End of backup.c **********************************************/
47131 /************** Begin file vdbemem.c *****************************************/
47132 /*
47133 ** 2004 May 26
47134 **
47135 ** The author disclaims copyright to this source code.  In place of
47136 ** a legal notice, here is a blessing:
47137 **
47138 **    May you do good and not evil.
47139 **    May you find forgiveness for yourself and forgive others.
47140 **    May you share freely, never taking more than you give.
47141 **
47142 *************************************************************************
47143 **
47144 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
47145 ** stores a single value in the VDBE.  Mem is an opaque structure visible
47146 ** only within the VDBE.  Interface routines refer to a Mem using the
47147 ** name sqlite_value
47148 */
47149
47150 /*
47151 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
47152 ** P if required.
47153 */
47154 #define expandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
47155
47156 /*
47157 ** If pMem is an object with a valid string representation, this routine
47158 ** ensures the internal encoding for the string representation is
47159 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
47160 **
47161 ** If pMem is not a string object, or the encoding of the string
47162 ** representation is already stored using the requested encoding, then this
47163 ** routine is a no-op.
47164 **
47165 ** SQLITE_OK is returned if the conversion is successful (or not required).
47166 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
47167 ** between formats.
47168 */
47169 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
47170   int rc;
47171   assert( (pMem->flags&MEM_RowSet)==0 );
47172   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
47173            || desiredEnc==SQLITE_UTF16BE );
47174   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
47175     return SQLITE_OK;
47176   }
47177   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
47178 #ifdef SQLITE_OMIT_UTF16
47179   return SQLITE_ERROR;
47180 #else
47181
47182   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
47183   ** then the encoding of the value may not have changed.
47184   */
47185   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
47186   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
47187   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
47188   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
47189   return rc;
47190 #endif
47191 }
47192
47193 /*
47194 ** Make sure pMem->z points to a writable allocation of at least 
47195 ** n bytes.
47196 **
47197 ** If the memory cell currently contains string or blob data
47198 ** and the third argument passed to this function is true, the 
47199 ** current content of the cell is preserved. Otherwise, it may
47200 ** be discarded.  
47201 **
47202 ** This function sets the MEM_Dyn flag and clears any xDel callback.
47203 ** It also clears MEM_Ephem and MEM_Static. If the preserve flag is 
47204 ** not set, Mem.n is zeroed.
47205 */
47206 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve){
47207   assert( 1 >=
47208     ((pMem->zMalloc && pMem->zMalloc==pMem->z) ? 1 : 0) +
47209     (((pMem->flags&MEM_Dyn)&&pMem->xDel) ? 1 : 0) + 
47210     ((pMem->flags&MEM_Ephem) ? 1 : 0) + 
47211     ((pMem->flags&MEM_Static) ? 1 : 0)
47212   );
47213   assert( (pMem->flags&MEM_RowSet)==0 );
47214
47215   if( n<32 ) n = 32;
47216   if( sqlite3DbMallocSize(pMem->db, pMem->zMalloc)<n ){
47217     if( preserve && pMem->z==pMem->zMalloc ){
47218       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
47219       preserve = 0;
47220     }else{
47221       sqlite3DbFree(pMem->db, pMem->zMalloc);
47222       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
47223     }
47224   }
47225
47226   if( pMem->z && preserve && pMem->zMalloc && pMem->z!=pMem->zMalloc ){
47227     memcpy(pMem->zMalloc, pMem->z, pMem->n);
47228   }
47229   if( pMem->flags&MEM_Dyn && pMem->xDel ){
47230     pMem->xDel((void *)(pMem->z));
47231   }
47232
47233   pMem->z = pMem->zMalloc;
47234   if( pMem->z==0 ){
47235     pMem->flags = MEM_Null;
47236   }else{
47237     pMem->flags &= ~(MEM_Ephem|MEM_Static);
47238   }
47239   pMem->xDel = 0;
47240   return (pMem->z ? SQLITE_OK : SQLITE_NOMEM);
47241 }
47242
47243 /*
47244 ** Make the given Mem object MEM_Dyn.  In other words, make it so
47245 ** that any TEXT or BLOB content is stored in memory obtained from
47246 ** malloc().  In this way, we know that the memory is safe to be
47247 ** overwritten or altered.
47248 **
47249 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
47250 */
47251 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
47252   int f;
47253   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
47254   assert( (pMem->flags&MEM_RowSet)==0 );
47255   expandBlob(pMem);
47256   f = pMem->flags;
47257   if( (f&(MEM_Str|MEM_Blob)) && pMem->z!=pMem->zMalloc ){
47258     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
47259       return SQLITE_NOMEM;
47260     }
47261     pMem->z[pMem->n] = 0;
47262     pMem->z[pMem->n+1] = 0;
47263     pMem->flags |= MEM_Term;
47264   }
47265
47266   return SQLITE_OK;
47267 }
47268
47269 /*
47270 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
47271 ** blob stored in dynamically allocated space.
47272 */
47273 #ifndef SQLITE_OMIT_INCRBLOB
47274 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
47275   if( pMem->flags & MEM_Zero ){
47276     int nByte;
47277     assert( pMem->flags&MEM_Blob );
47278     assert( (pMem->flags&MEM_RowSet)==0 );
47279     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
47280
47281     /* Set nByte to the number of bytes required to store the expanded blob. */
47282     nByte = pMem->n + pMem->u.nZero;
47283     if( nByte<=0 ){
47284       nByte = 1;
47285     }
47286     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
47287       return SQLITE_NOMEM;
47288     }
47289
47290     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
47291     pMem->n += pMem->u.nZero;
47292     pMem->flags &= ~(MEM_Zero|MEM_Term);
47293   }
47294   return SQLITE_OK;
47295 }
47296 #endif
47297
47298
47299 /*
47300 ** Make sure the given Mem is \u0000 terminated.
47301 */
47302 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
47303   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
47304   if( (pMem->flags & MEM_Term)!=0 || (pMem->flags & MEM_Str)==0 ){
47305     return SQLITE_OK;   /* Nothing to do */
47306   }
47307   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
47308     return SQLITE_NOMEM;
47309   }
47310   pMem->z[pMem->n] = 0;
47311   pMem->z[pMem->n+1] = 0;
47312   pMem->flags |= MEM_Term;
47313   return SQLITE_OK;
47314 }
47315
47316 /*
47317 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
47318 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
47319 ** is a no-op.
47320 **
47321 ** Existing representations MEM_Int and MEM_Real are *not* invalidated.
47322 **
47323 ** A MEM_Null value will never be passed to this function. This function is
47324 ** used for converting values to text for returning to the user (i.e. via
47325 ** sqlite3_value_text()), or for ensuring that values to be used as btree
47326 ** keys are strings. In the former case a NULL pointer is returned the
47327 ** user and the later is an internal programming error.
47328 */
47329 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, int enc){
47330   int rc = SQLITE_OK;
47331   int fg = pMem->flags;
47332   const int nByte = 32;
47333
47334   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
47335   assert( !(fg&MEM_Zero) );
47336   assert( !(fg&(MEM_Str|MEM_Blob)) );
47337   assert( fg&(MEM_Int|MEM_Real) );
47338   assert( (pMem->flags&MEM_RowSet)==0 );
47339   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
47340
47341
47342   if( sqlite3VdbeMemGrow(pMem, nByte, 0) ){
47343     return SQLITE_NOMEM;
47344   }
47345
47346   /* For a Real or Integer, use sqlite3_mprintf() to produce the UTF-8
47347   ** string representation of the value. Then, if the required encoding
47348   ** is UTF-16le or UTF-16be do a translation.
47349   ** 
47350   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
47351   */
47352   if( fg & MEM_Int ){
47353     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
47354   }else{
47355     assert( fg & MEM_Real );
47356     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->r);
47357   }
47358   pMem->n = sqlite3Strlen30(pMem->z);
47359   pMem->enc = SQLITE_UTF8;
47360   pMem->flags |= MEM_Str|MEM_Term;
47361   sqlite3VdbeChangeEncoding(pMem, enc);
47362   return rc;
47363 }
47364
47365 /*
47366 ** Memory cell pMem contains the context of an aggregate function.
47367 ** This routine calls the finalize method for that function.  The
47368 ** result of the aggregate is stored back into pMem.
47369 **
47370 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
47371 ** otherwise.
47372 */
47373 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
47374   int rc = SQLITE_OK;
47375   if( ALWAYS(pFunc && pFunc->xFinalize) ){
47376     sqlite3_context ctx;
47377     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
47378     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
47379     memset(&ctx, 0, sizeof(ctx));
47380     ctx.s.flags = MEM_Null;
47381     ctx.s.db = pMem->db;
47382     ctx.pMem = pMem;
47383     ctx.pFunc = pFunc;
47384     pFunc->xFinalize(&ctx);
47385     assert( 0==(pMem->flags&MEM_Dyn) && !pMem->xDel );
47386     sqlite3DbFree(pMem->db, pMem->zMalloc);
47387     memcpy(pMem, &ctx.s, sizeof(ctx.s));
47388     rc = ctx.isError;
47389   }
47390   return rc;
47391 }
47392
47393 /*
47394 ** If the memory cell contains a string value that must be freed by
47395 ** invoking an external callback, free it now. Calling this function
47396 ** does not free any Mem.zMalloc buffer.
47397 */
47398 SQLITE_PRIVATE void sqlite3VdbeMemReleaseExternal(Mem *p){
47399   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
47400   testcase( p->flags & MEM_Agg );
47401   testcase( p->flags & MEM_Dyn );
47402   testcase( p->flags & MEM_RowSet );
47403   testcase( p->flags & MEM_Frame );
47404   if( p->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame) ){
47405     if( p->flags&MEM_Agg ){
47406       sqlite3VdbeMemFinalize(p, p->u.pDef);
47407       assert( (p->flags & MEM_Agg)==0 );
47408       sqlite3VdbeMemRelease(p);
47409     }else if( p->flags&MEM_Dyn && p->xDel ){
47410       assert( (p->flags&MEM_RowSet)==0 );
47411       p->xDel((void *)p->z);
47412       p->xDel = 0;
47413     }else if( p->flags&MEM_RowSet ){
47414       sqlite3RowSetClear(p->u.pRowSet);
47415     }else if( p->flags&MEM_Frame ){
47416       sqlite3VdbeMemSetNull(p);
47417     }
47418   }
47419 }
47420
47421 /*
47422 ** Release any memory held by the Mem. This may leave the Mem in an
47423 ** inconsistent state, for example with (Mem.z==0) and
47424 ** (Mem.type==SQLITE_TEXT).
47425 */
47426 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
47427   sqlite3VdbeMemReleaseExternal(p);
47428   sqlite3DbFree(p->db, p->zMalloc);
47429   p->z = 0;
47430   p->zMalloc = 0;
47431   p->xDel = 0;
47432 }
47433
47434 /*
47435 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
47436 ** If the double is too large, return 0x8000000000000000.
47437 **
47438 ** Most systems appear to do this simply by assigning
47439 ** variables and without the extra range tests.  But
47440 ** there are reports that windows throws an expection
47441 ** if the floating point value is out of range. (See ticket #2880.)
47442 ** Because we do not completely understand the problem, we will
47443 ** take the conservative approach and always do range tests
47444 ** before attempting the conversion.
47445 */
47446 static i64 doubleToInt64(double r){
47447 #ifdef SQLITE_OMIT_FLOATING_POINT
47448   /* When floating-point is omitted, double and int64 are the same thing */
47449   return r;
47450 #else
47451   /*
47452   ** Many compilers we encounter do not define constants for the
47453   ** minimum and maximum 64-bit integers, or they define them
47454   ** inconsistently.  And many do not understand the "LL" notation.
47455   ** So we define our own static constants here using nothing
47456   ** larger than a 32-bit integer constant.
47457   */
47458   static const i64 maxInt = LARGEST_INT64;
47459   static const i64 minInt = SMALLEST_INT64;
47460
47461   if( r<(double)minInt ){
47462     return minInt;
47463   }else if( r>(double)maxInt ){
47464     /* minInt is correct here - not maxInt.  It turns out that assigning
47465     ** a very large positive number to an integer results in a very large
47466     ** negative integer.  This makes no sense, but it is what x86 hardware
47467     ** does so for compatibility we will do the same in software. */
47468     return minInt;
47469   }else{
47470     return (i64)r;
47471   }
47472 #endif
47473 }
47474
47475 /*
47476 ** Return some kind of integer value which is the best we can do
47477 ** at representing the value that *pMem describes as an integer.
47478 ** If pMem is an integer, then the value is exact.  If pMem is
47479 ** a floating-point then the value returned is the integer part.
47480 ** If pMem is a string or blob, then we make an attempt to convert
47481 ** it into a integer and return that.  If pMem represents an
47482 ** an SQL-NULL value, return 0.
47483 **
47484 ** If pMem represents a string value, its encoding might be changed.
47485 */
47486 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
47487   int flags;
47488   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
47489   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
47490   flags = pMem->flags;
47491   if( flags & MEM_Int ){
47492     return pMem->u.i;
47493   }else if( flags & MEM_Real ){
47494     return doubleToInt64(pMem->r);
47495   }else if( flags & (MEM_Str|MEM_Blob) ){
47496     i64 value;
47497     pMem->flags |= MEM_Str;
47498     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
47499        || sqlite3VdbeMemNulTerminate(pMem) ){
47500       return 0;
47501     }
47502     assert( pMem->z );
47503     sqlite3Atoi64(pMem->z, &value);
47504     return value;
47505   }else{
47506     return 0;
47507   }
47508 }
47509
47510 /*
47511 ** Return the best representation of pMem that we can get into a
47512 ** double.  If pMem is already a double or an integer, return its
47513 ** value.  If it is a string or blob, try to convert it to a double.
47514 ** If it is a NULL, return 0.0.
47515 */
47516 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
47517   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
47518   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
47519   if( pMem->flags & MEM_Real ){
47520     return pMem->r;
47521   }else if( pMem->flags & MEM_Int ){
47522     return (double)pMem->u.i;
47523   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
47524     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
47525     double val = (double)0;
47526     pMem->flags |= MEM_Str;
47527     if( sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8)
47528        || sqlite3VdbeMemNulTerminate(pMem) ){
47529       /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
47530       return (double)0;
47531     }
47532     assert( pMem->z );
47533     sqlite3AtoF(pMem->z, &val);
47534     return val;
47535   }else{
47536     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
47537     return (double)0;
47538   }
47539 }
47540
47541 /*
47542 ** The MEM structure is already a MEM_Real.  Try to also make it a
47543 ** MEM_Int if we can.
47544 */
47545 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
47546   assert( pMem->flags & MEM_Real );
47547   assert( (pMem->flags & MEM_RowSet)==0 );
47548   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
47549   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
47550
47551   pMem->u.i = doubleToInt64(pMem->r);
47552
47553   /* Only mark the value as an integer if
47554   **
47555   **    (1) the round-trip conversion real->int->real is a no-op, and
47556   **    (2) The integer is neither the largest nor the smallest
47557   **        possible integer (ticket #3922)
47558   **
47559   ** The second and third terms in the following conditional enforces
47560   ** the second condition under the assumption that addition overflow causes
47561   ** values to wrap around.  On x86 hardware, the third term is always
47562   ** true and could be omitted.  But we leave it in because other
47563   ** architectures might behave differently.
47564   */
47565   if( pMem->r==(double)pMem->u.i && pMem->u.i>SMALLEST_INT64
47566       && ALWAYS(pMem->u.i<LARGEST_INT64) ){
47567     pMem->flags |= MEM_Int;
47568   }
47569 }
47570
47571 /*
47572 ** Convert pMem to type integer.  Invalidate any prior representations.
47573 */
47574 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
47575   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
47576   assert( (pMem->flags & MEM_RowSet)==0 );
47577   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
47578
47579   pMem->u.i = sqlite3VdbeIntValue(pMem);
47580   MemSetTypeFlag(pMem, MEM_Int);
47581   return SQLITE_OK;
47582 }
47583
47584 /*
47585 ** Convert pMem so that it is of type MEM_Real.
47586 ** Invalidate any prior representations.
47587 */
47588 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
47589   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
47590   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
47591
47592   pMem->r = sqlite3VdbeRealValue(pMem);
47593   MemSetTypeFlag(pMem, MEM_Real);
47594   return SQLITE_OK;
47595 }
47596
47597 /*
47598 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
47599 ** Invalidate any prior representations.
47600 **
47601 ** Every effort is made to force the conversion, even if the input
47602 ** is a string that does not look completely like a number.  Convert
47603 ** as much of the string as we can and ignore the rest.
47604 */
47605 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
47606   int rc;
47607   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 );
47608   assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
47609   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
47610   rc = sqlite3VdbeChangeEncoding(pMem, SQLITE_UTF8);
47611   if( rc ) return rc;
47612   rc = sqlite3VdbeMemNulTerminate(pMem);
47613   if( rc ) return rc;
47614   if( sqlite3Atoi64(pMem->z, &pMem->u.i) ){
47615     MemSetTypeFlag(pMem, MEM_Int);
47616   }else{
47617     pMem->r = sqlite3VdbeRealValue(pMem);
47618     MemSetTypeFlag(pMem, MEM_Real);
47619     sqlite3VdbeIntegerAffinity(pMem);
47620   }
47621   return SQLITE_OK;
47622 }
47623
47624 /*
47625 ** Delete any previous value and set the value stored in *pMem to NULL.
47626 */
47627 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
47628   if( pMem->flags & MEM_Frame ){
47629     sqlite3VdbeFrameDelete(pMem->u.pFrame);
47630   }
47631   if( pMem->flags & MEM_RowSet ){
47632     sqlite3RowSetClear(pMem->u.pRowSet);
47633   }
47634   MemSetTypeFlag(pMem, MEM_Null);
47635   pMem->type = SQLITE_NULL;
47636 }
47637
47638 /*
47639 ** Delete any previous value and set the value to be a BLOB of length
47640 ** n containing all zeros.
47641 */
47642 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
47643   sqlite3VdbeMemRelease(pMem);
47644   pMem->flags = MEM_Blob|MEM_Zero;
47645   pMem->type = SQLITE_BLOB;
47646   pMem->n = 0;
47647   if( n<0 ) n = 0;
47648   pMem->u.nZero = n;
47649   pMem->enc = SQLITE_UTF8;
47650
47651 #ifdef SQLITE_OMIT_INCRBLOB
47652   sqlite3VdbeMemGrow(pMem, n, 0);
47653   if( pMem->z ){
47654     pMem->n = n;
47655     memset(pMem->z, 0, n);
47656   }
47657 #endif
47658 }
47659
47660 /*
47661 ** Delete any previous value and set the value stored in *pMem to val,
47662 ** manifest type INTEGER.
47663 */
47664 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
47665   sqlite3VdbeMemRelease(pMem);
47666   pMem->u.i = val;
47667   pMem->flags = MEM_Int;
47668   pMem->type = SQLITE_INTEGER;
47669 }
47670
47671 #ifndef SQLITE_OMIT_FLOATING_POINT
47672 /*
47673 ** Delete any previous value and set the value stored in *pMem to val,
47674 ** manifest type REAL.
47675 */
47676 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
47677   if( sqlite3IsNaN(val) ){
47678     sqlite3VdbeMemSetNull(pMem);
47679   }else{
47680     sqlite3VdbeMemRelease(pMem);
47681     pMem->r = val;
47682     pMem->flags = MEM_Real;
47683     pMem->type = SQLITE_FLOAT;
47684   }
47685 }
47686 #endif
47687
47688 /*
47689 ** Delete any previous value and set the value of pMem to be an
47690 ** empty boolean index.
47691 */
47692 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
47693   sqlite3 *db = pMem->db;
47694   assert( db!=0 );
47695   assert( (pMem->flags & MEM_RowSet)==0 );
47696   sqlite3VdbeMemRelease(pMem);
47697   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
47698   if( db->mallocFailed ){
47699     pMem->flags = MEM_Null;
47700   }else{
47701     assert( pMem->zMalloc );
47702     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, 
47703                                        sqlite3DbMallocSize(db, pMem->zMalloc));
47704     assert( pMem->u.pRowSet!=0 );
47705     pMem->flags = MEM_RowSet;
47706   }
47707 }
47708
47709 /*
47710 ** Return true if the Mem object contains a TEXT or BLOB that is
47711 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
47712 */
47713 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
47714   assert( p->db!=0 );
47715   if( p->flags & (MEM_Str|MEM_Blob) ){
47716     int n = p->n;
47717     if( p->flags & MEM_Zero ){
47718       n += p->u.nZero;
47719     }
47720     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
47721   }
47722   return 0; 
47723 }
47724
47725 /*
47726 ** Size of struct Mem not including the Mem.zMalloc member.
47727 */
47728 #define MEMCELLSIZE (size_t)(&(((Mem *)0)->zMalloc))
47729
47730 /*
47731 ** Make an shallow copy of pFrom into pTo.  Prior contents of
47732 ** pTo are freed.  The pFrom->z field is not duplicated.  If
47733 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
47734 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
47735 */
47736 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
47737   assert( (pFrom->flags & MEM_RowSet)==0 );
47738   sqlite3VdbeMemReleaseExternal(pTo);
47739   memcpy(pTo, pFrom, MEMCELLSIZE);
47740   pTo->xDel = 0;
47741   if( (pFrom->flags&MEM_Static)==0 ){
47742     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
47743     assert( srcType==MEM_Ephem || srcType==MEM_Static );
47744     pTo->flags |= srcType;
47745   }
47746 }
47747
47748 /*
47749 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
47750 ** freed before the copy is made.
47751 */
47752 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
47753   int rc = SQLITE_OK;
47754
47755   assert( (pFrom->flags & MEM_RowSet)==0 );
47756   sqlite3VdbeMemReleaseExternal(pTo);
47757   memcpy(pTo, pFrom, MEMCELLSIZE);
47758   pTo->flags &= ~MEM_Dyn;
47759
47760   if( pTo->flags&(MEM_Str|MEM_Blob) ){
47761     if( 0==(pFrom->flags&MEM_Static) ){
47762       pTo->flags |= MEM_Ephem;
47763       rc = sqlite3VdbeMemMakeWriteable(pTo);
47764     }
47765   }
47766
47767   return rc;
47768 }
47769
47770 /*
47771 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
47772 ** freed. If pFrom contains ephemeral data, a copy is made.
47773 **
47774 ** pFrom contains an SQL NULL when this routine returns.
47775 */
47776 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
47777   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
47778   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
47779   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
47780
47781   sqlite3VdbeMemRelease(pTo);
47782   memcpy(pTo, pFrom, sizeof(Mem));
47783   pFrom->flags = MEM_Null;
47784   pFrom->xDel = 0;
47785   pFrom->zMalloc = 0;
47786 }
47787
47788 /*
47789 ** Change the value of a Mem to be a string or a BLOB.
47790 **
47791 ** The memory management strategy depends on the value of the xDel
47792 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
47793 ** string is copied into a (possibly existing) buffer managed by the 
47794 ** Mem structure. Otherwise, any existing buffer is freed and the
47795 ** pointer copied.
47796 **
47797 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
47798 ** size limit) then no memory allocation occurs.  If the string can be
47799 ** stored without allocating memory, then it is.  If a memory allocation
47800 ** is required to store the string, then value of pMem is unchanged.  In
47801 ** either case, SQLITE_TOOBIG is returned.
47802 */
47803 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
47804   Mem *pMem,          /* Memory cell to set to string value */
47805   const char *z,      /* String pointer */
47806   int n,              /* Bytes in string, or negative */
47807   u8 enc,             /* Encoding of z.  0 for BLOBs */
47808   void (*xDel)(void*) /* Destructor function */
47809 ){
47810   int nByte = n;      /* New value for pMem->n */
47811   int iLimit;         /* Maximum allowed string or blob size */
47812   u16 flags = 0;      /* New value for pMem->flags */
47813
47814   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
47815   assert( (pMem->flags & MEM_RowSet)==0 );
47816
47817   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
47818   if( !z ){
47819     sqlite3VdbeMemSetNull(pMem);
47820     return SQLITE_OK;
47821   }
47822
47823   if( pMem->db ){
47824     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
47825   }else{
47826     iLimit = SQLITE_MAX_LENGTH;
47827   }
47828   flags = (enc==0?MEM_Blob:MEM_Str);
47829   if( nByte<0 ){
47830     assert( enc!=0 );
47831     if( enc==SQLITE_UTF8 ){
47832       for(nByte=0; nByte<=iLimit && z[nByte]; nByte++){}
47833     }else{
47834       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
47835     }
47836     flags |= MEM_Term;
47837   }
47838
47839   /* The following block sets the new values of Mem.z and Mem.xDel. It
47840   ** also sets a flag in local variable "flags" to indicate the memory
47841   ** management (one of MEM_Dyn or MEM_Static).
47842   */
47843   if( xDel==SQLITE_TRANSIENT ){
47844     int nAlloc = nByte;
47845     if( flags&MEM_Term ){
47846       nAlloc += (enc==SQLITE_UTF8?1:2);
47847     }
47848     if( nByte>iLimit ){
47849       return SQLITE_TOOBIG;
47850     }
47851     if( sqlite3VdbeMemGrow(pMem, nAlloc, 0) ){
47852       return SQLITE_NOMEM;
47853     }
47854     memcpy(pMem->z, z, nAlloc);
47855   }else if( xDel==SQLITE_DYNAMIC ){
47856     sqlite3VdbeMemRelease(pMem);
47857     pMem->zMalloc = pMem->z = (char *)z;
47858     pMem->xDel = 0;
47859   }else{
47860     sqlite3VdbeMemRelease(pMem);
47861     pMem->z = (char *)z;
47862     pMem->xDel = xDel;
47863     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
47864   }
47865
47866   pMem->n = nByte;
47867   pMem->flags = flags;
47868   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
47869   pMem->type = (enc==0 ? SQLITE_BLOB : SQLITE_TEXT);
47870
47871 #ifndef SQLITE_OMIT_UTF16
47872   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
47873     return SQLITE_NOMEM;
47874   }
47875 #endif
47876
47877   if( nByte>iLimit ){
47878     return SQLITE_TOOBIG;
47879   }
47880
47881   return SQLITE_OK;
47882 }
47883
47884 /*
47885 ** Compare the values contained by the two memory cells, returning
47886 ** negative, zero or positive if pMem1 is less than, equal to, or greater
47887 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
47888 ** and reals) sorted numerically, followed by text ordered by the collating
47889 ** sequence pColl and finally blob's ordered by memcmp().
47890 **
47891 ** Two NULL values are considered equal by this function.
47892 */
47893 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
47894   int rc;
47895   int f1, f2;
47896   int combined_flags;
47897
47898   f1 = pMem1->flags;
47899   f2 = pMem2->flags;
47900   combined_flags = f1|f2;
47901   assert( (combined_flags & MEM_RowSet)==0 );
47902  
47903   /* If one value is NULL, it is less than the other. If both values
47904   ** are NULL, return 0.
47905   */
47906   if( combined_flags&MEM_Null ){
47907     return (f2&MEM_Null) - (f1&MEM_Null);
47908   }
47909
47910   /* If one value is a number and the other is not, the number is less.
47911   ** If both are numbers, compare as reals if one is a real, or as integers
47912   ** if both values are integers.
47913   */
47914   if( combined_flags&(MEM_Int|MEM_Real) ){
47915     if( !(f1&(MEM_Int|MEM_Real)) ){
47916       return 1;
47917     }
47918     if( !(f2&(MEM_Int|MEM_Real)) ){
47919       return -1;
47920     }
47921     if( (f1 & f2 & MEM_Int)==0 ){
47922       double r1, r2;
47923       if( (f1&MEM_Real)==0 ){
47924         r1 = (double)pMem1->u.i;
47925       }else{
47926         r1 = pMem1->r;
47927       }
47928       if( (f2&MEM_Real)==0 ){
47929         r2 = (double)pMem2->u.i;
47930       }else{
47931         r2 = pMem2->r;
47932       }
47933       if( r1<r2 ) return -1;
47934       if( r1>r2 ) return 1;
47935       return 0;
47936     }else{
47937       assert( f1&MEM_Int );
47938       assert( f2&MEM_Int );
47939       if( pMem1->u.i < pMem2->u.i ) return -1;
47940       if( pMem1->u.i > pMem2->u.i ) return 1;
47941       return 0;
47942     }
47943   }
47944
47945   /* If one value is a string and the other is a blob, the string is less.
47946   ** If both are strings, compare using the collating functions.
47947   */
47948   if( combined_flags&MEM_Str ){
47949     if( (f1 & MEM_Str)==0 ){
47950       return 1;
47951     }
47952     if( (f2 & MEM_Str)==0 ){
47953       return -1;
47954     }
47955
47956     assert( pMem1->enc==pMem2->enc );
47957     assert( pMem1->enc==SQLITE_UTF8 || 
47958             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
47959
47960     /* The collation sequence must be defined at this point, even if
47961     ** the user deletes the collation sequence after the vdbe program is
47962     ** compiled (this was not always the case).
47963     */
47964     assert( !pColl || pColl->xCmp );
47965
47966     if( pColl ){
47967       if( pMem1->enc==pColl->enc ){
47968         /* The strings are already in the correct encoding.  Call the
47969         ** comparison function directly */
47970         return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
47971       }else{
47972         const void *v1, *v2;
47973         int n1, n2;
47974         Mem c1;
47975         Mem c2;
47976         memset(&c1, 0, sizeof(c1));
47977         memset(&c2, 0, sizeof(c2));
47978         sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
47979         sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
47980         v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
47981         n1 = v1==0 ? 0 : c1.n;
47982         v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
47983         n2 = v2==0 ? 0 : c2.n;
47984         rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
47985         sqlite3VdbeMemRelease(&c1);
47986         sqlite3VdbeMemRelease(&c2);
47987         return rc;
47988       }
47989     }
47990     /* If a NULL pointer was passed as the collate function, fall through
47991     ** to the blob case and use memcmp().  */
47992   }
47993  
47994   /* Both values must be blobs.  Compare using memcmp().  */
47995   rc = memcmp(pMem1->z, pMem2->z, (pMem1->n>pMem2->n)?pMem2->n:pMem1->n);
47996   if( rc==0 ){
47997     rc = pMem1->n - pMem2->n;
47998   }
47999   return rc;
48000 }
48001
48002 /*
48003 ** Move data out of a btree key or data field and into a Mem structure.
48004 ** The data or key is taken from the entry that pCur is currently pointing
48005 ** to.  offset and amt determine what portion of the data or key to retrieve.
48006 ** key is true to get the key or false to get data.  The result is written
48007 ** into the pMem element.
48008 **
48009 ** The pMem structure is assumed to be uninitialized.  Any prior content
48010 ** is overwritten without being freed.
48011 **
48012 ** If this routine fails for any reason (malloc returns NULL or unable
48013 ** to read from the disk) then the pMem is left in an inconsistent state.
48014 */
48015 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
48016   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
48017   int offset,       /* Offset from the start of data to return bytes from. */
48018   int amt,          /* Number of bytes to return. */
48019   int key,          /* If true, retrieve from the btree key, not data. */
48020   Mem *pMem         /* OUT: Return data in this Mem structure. */
48021 ){
48022   char *zData;        /* Data from the btree layer */
48023   int available = 0;  /* Number of bytes available on the local btree page */
48024   int rc = SQLITE_OK; /* Return code */
48025
48026   assert( sqlite3BtreeCursorIsValid(pCur) );
48027
48028   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
48029   ** that both the BtShared and database handle mutexes are held. */
48030   assert( (pMem->flags & MEM_RowSet)==0 );
48031   if( key ){
48032     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
48033   }else{
48034     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
48035   }
48036   assert( zData!=0 );
48037
48038   if( offset+amt<=available && (pMem->flags&MEM_Dyn)==0 ){
48039     sqlite3VdbeMemRelease(pMem);
48040     pMem->z = &zData[offset];
48041     pMem->flags = MEM_Blob|MEM_Ephem;
48042   }else if( SQLITE_OK==(rc = sqlite3VdbeMemGrow(pMem, amt+2, 0)) ){
48043     pMem->flags = MEM_Blob|MEM_Dyn|MEM_Term;
48044     pMem->enc = 0;
48045     pMem->type = SQLITE_BLOB;
48046     if( key ){
48047       rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
48048     }else{
48049       rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
48050     }
48051     pMem->z[amt] = 0;
48052     pMem->z[amt+1] = 0;
48053     if( rc!=SQLITE_OK ){
48054       sqlite3VdbeMemRelease(pMem);
48055     }
48056   }
48057   pMem->n = amt;
48058
48059   return rc;
48060 }
48061
48062 /* This function is only available internally, it is not part of the
48063 ** external API. It works in a similar way to sqlite3_value_text(),
48064 ** except the data returned is in the encoding specified by the second
48065 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
48066 ** SQLITE_UTF8.
48067 **
48068 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
48069 ** If that is the case, then the result must be aligned on an even byte
48070 ** boundary.
48071 */
48072 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
48073   if( !pVal ) return 0;
48074
48075   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
48076   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
48077   assert( (pVal->flags & MEM_RowSet)==0 );
48078
48079   if( pVal->flags&MEM_Null ){
48080     return 0;
48081   }
48082   assert( (MEM_Blob>>3) == MEM_Str );
48083   pVal->flags |= (pVal->flags & MEM_Blob)>>3;
48084   expandBlob(pVal);
48085   if( pVal->flags&MEM_Str ){
48086     sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
48087     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
48088       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
48089       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
48090         return 0;
48091       }
48092     }
48093     sqlite3VdbeMemNulTerminate(pVal);
48094   }else{
48095     assert( (pVal->flags&MEM_Blob)==0 );
48096     sqlite3VdbeMemStringify(pVal, enc);
48097     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
48098   }
48099   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
48100               || pVal->db->mallocFailed );
48101   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
48102     return pVal->z;
48103   }else{
48104     return 0;
48105   }
48106 }
48107
48108 /*
48109 ** Create a new sqlite3_value object.
48110 */
48111 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
48112   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
48113   if( p ){
48114     p->flags = MEM_Null;
48115     p->type = SQLITE_NULL;
48116     p->db = db;
48117   }
48118   return p;
48119 }
48120
48121 /*
48122 ** Create a new sqlite3_value object, containing the value of pExpr.
48123 **
48124 ** This only works for very simple expressions that consist of one constant
48125 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
48126 ** be converted directly into a value, then the value is allocated and
48127 ** a pointer written to *ppVal. The caller is responsible for deallocating
48128 ** the value by passing it to sqlite3ValueFree() later on. If the expression
48129 ** cannot be converted to a value, then *ppVal is set to NULL.
48130 */
48131 SQLITE_PRIVATE int sqlite3ValueFromExpr(
48132   sqlite3 *db,              /* The database connection */
48133   Expr *pExpr,              /* The expression to evaluate */
48134   u8 enc,                   /* Encoding to use */
48135   u8 affinity,              /* Affinity to use */
48136   sqlite3_value **ppVal     /* Write the new value here */
48137 ){
48138   int op;
48139   char *zVal = 0;
48140   sqlite3_value *pVal = 0;
48141
48142   if( !pExpr ){
48143     *ppVal = 0;
48144     return SQLITE_OK;
48145   }
48146   op = pExpr->op;
48147   if( op==TK_REGISTER ){
48148     op = pExpr->op2;  /* This only happens with SQLITE_ENABLE_STAT2 */
48149   }
48150
48151   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
48152     pVal = sqlite3ValueNew(db);
48153     if( pVal==0 ) goto no_mem;
48154     if( ExprHasProperty(pExpr, EP_IntValue) ){
48155       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue);
48156     }else{
48157       zVal = sqlite3DbStrDup(db, pExpr->u.zToken);
48158       if( zVal==0 ) goto no_mem;
48159       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
48160       if( op==TK_FLOAT ) pVal->type = SQLITE_FLOAT;
48161     }
48162     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
48163       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
48164     }else{
48165       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
48166     }
48167     if( enc!=SQLITE_UTF8 ){
48168       sqlite3VdbeChangeEncoding(pVal, enc);
48169     }
48170   }else if( op==TK_UMINUS ) {
48171     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) ){
48172       pVal->u.i = -1 * pVal->u.i;
48173       /* (double)-1 In case of SQLITE_OMIT_FLOATING_POINT... */
48174       pVal->r = (double)-1 * pVal->r;
48175     }
48176   }
48177 #ifndef SQLITE_OMIT_BLOB_LITERAL
48178   else if( op==TK_BLOB ){
48179     int nVal;
48180     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
48181     assert( pExpr->u.zToken[1]=='\'' );
48182     pVal = sqlite3ValueNew(db);
48183     if( !pVal ) goto no_mem;
48184     zVal = &pExpr->u.zToken[2];
48185     nVal = sqlite3Strlen30(zVal)-1;
48186     assert( zVal[nVal]=='\'' );
48187     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
48188                          0, SQLITE_DYNAMIC);
48189   }
48190 #endif
48191
48192   if( pVal ){
48193     sqlite3VdbeMemStoreType(pVal);
48194   }
48195   *ppVal = pVal;
48196   return SQLITE_OK;
48197
48198 no_mem:
48199   db->mallocFailed = 1;
48200   sqlite3DbFree(db, zVal);
48201   sqlite3ValueFree(pVal);
48202   *ppVal = 0;
48203   return SQLITE_NOMEM;
48204 }
48205
48206 /*
48207 ** Change the string value of an sqlite3_value object
48208 */
48209 SQLITE_PRIVATE void sqlite3ValueSetStr(
48210   sqlite3_value *v,     /* Value to be set */
48211   int n,                /* Length of string z */
48212   const void *z,        /* Text of the new string */
48213   u8 enc,               /* Encoding to use */
48214   void (*xDel)(void*)   /* Destructor for the string */
48215 ){
48216   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
48217 }
48218
48219 /*
48220 ** Free an sqlite3_value object
48221 */
48222 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
48223   if( !v ) return;
48224   sqlite3VdbeMemRelease((Mem *)v);
48225   sqlite3DbFree(((Mem*)v)->db, v);
48226 }
48227
48228 /*
48229 ** Return the number of bytes in the sqlite3_value object assuming
48230 ** that it uses the encoding "enc"
48231 */
48232 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
48233   Mem *p = (Mem*)pVal;
48234   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
48235     if( p->flags & MEM_Zero ){
48236       return p->n + p->u.nZero;
48237     }else{
48238       return p->n;
48239     }
48240   }
48241   return 0;
48242 }
48243
48244 /************** End of vdbemem.c *********************************************/
48245 /************** Begin file vdbeaux.c *****************************************/
48246 /*
48247 ** 2003 September 6
48248 **
48249 ** The author disclaims copyright to this source code.  In place of
48250 ** a legal notice, here is a blessing:
48251 **
48252 **    May you do good and not evil.
48253 **    May you find forgiveness for yourself and forgive others.
48254 **    May you share freely, never taking more than you give.
48255 **
48256 *************************************************************************
48257 ** This file contains code used for creating, destroying, and populating
48258 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)  Prior
48259 ** to version 2.8.7, all this code was combined into the vdbe.c source file.
48260 ** But that file was getting too big so this subroutines were split out.
48261 */
48262
48263
48264
48265 /*
48266 ** When debugging the code generator in a symbolic debugger, one can
48267 ** set the sqlite3VdbeAddopTrace to 1 and all opcodes will be printed
48268 ** as they are added to the instruction stream.
48269 */
48270 #ifdef SQLITE_DEBUG
48271 SQLITE_PRIVATE int sqlite3VdbeAddopTrace = 0;
48272 #endif
48273
48274
48275 /*
48276 ** Create a new virtual database engine.
48277 */
48278 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(sqlite3 *db){
48279   Vdbe *p;
48280   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
48281   if( p==0 ) return 0;
48282   p->db = db;
48283   if( db->pVdbe ){
48284     db->pVdbe->pPrev = p;
48285   }
48286   p->pNext = db->pVdbe;
48287   p->pPrev = 0;
48288   db->pVdbe = p;
48289   p->magic = VDBE_MAGIC_INIT;
48290   return p;
48291 }
48292
48293 /*
48294 ** Remember the SQL string for a prepared statement.
48295 */
48296 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
48297   assert( isPrepareV2==1 || isPrepareV2==0 );
48298   if( p==0 ) return;
48299 #ifdef SQLITE_OMIT_TRACE
48300   if( !isPrepareV2 ) return;
48301 #endif
48302   assert( p->zSql==0 );
48303   p->zSql = sqlite3DbStrNDup(p->db, z, n);
48304   p->isPrepareV2 = (u8)isPrepareV2;
48305 }
48306
48307 /*
48308 ** Return the SQL associated with a prepared statement
48309 */
48310 SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
48311   Vdbe *p = (Vdbe *)pStmt;
48312   return (p && p->isPrepareV2) ? p->zSql : 0;
48313 }
48314
48315 /*
48316 ** Swap all content between two VDBE structures.
48317 */
48318 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
48319   Vdbe tmp, *pTmp;
48320   char *zTmp;
48321   tmp = *pA;
48322   *pA = *pB;
48323   *pB = tmp;
48324   pTmp = pA->pNext;
48325   pA->pNext = pB->pNext;
48326   pB->pNext = pTmp;
48327   pTmp = pA->pPrev;
48328   pA->pPrev = pB->pPrev;
48329   pB->pPrev = pTmp;
48330   zTmp = pA->zSql;
48331   pA->zSql = pB->zSql;
48332   pB->zSql = zTmp;
48333   pB->isPrepareV2 = pA->isPrepareV2;
48334 }
48335
48336 #ifdef SQLITE_DEBUG
48337 /*
48338 ** Turn tracing on or off
48339 */
48340 SQLITE_PRIVATE void sqlite3VdbeTrace(Vdbe *p, FILE *trace){
48341   p->trace = trace;
48342 }
48343 #endif
48344
48345 /*
48346 ** Resize the Vdbe.aOp array so that it is at least one op larger than 
48347 ** it was.
48348 **
48349 ** If an out-of-memory error occurs while resizing the array, return
48350 ** SQLITE_NOMEM. In this case Vdbe.aOp and Vdbe.nOpAlloc remain 
48351 ** unchanged (this is so that any opcodes already allocated can be 
48352 ** correctly deallocated along with the rest of the Vdbe).
48353 */
48354 static int growOpArray(Vdbe *p){
48355   VdbeOp *pNew;
48356   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
48357   pNew = sqlite3DbRealloc(p->db, p->aOp, nNew*sizeof(Op));
48358   if( pNew ){
48359     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
48360     p->aOp = pNew;
48361   }
48362   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
48363 }
48364
48365 /*
48366 ** Add a new instruction to the list of instructions current in the
48367 ** VDBE.  Return the address of the new instruction.
48368 **
48369 ** Parameters:
48370 **
48371 **    p               Pointer to the VDBE
48372 **
48373 **    op              The opcode for this instruction
48374 **
48375 **    p1, p2, p3      Operands
48376 **
48377 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
48378 ** the sqlite3VdbeChangeP4() function to change the value of the P4
48379 ** operand.
48380 */
48381 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
48382   int i;
48383   VdbeOp *pOp;
48384
48385   i = p->nOp;
48386   assert( p->magic==VDBE_MAGIC_INIT );
48387   assert( op>0 && op<0xff );
48388   if( p->nOpAlloc<=i ){
48389     if( growOpArray(p) ){
48390       return 1;
48391     }
48392   }
48393   p->nOp++;
48394   pOp = &p->aOp[i];
48395   pOp->opcode = (u8)op;
48396   pOp->p5 = 0;
48397   pOp->p1 = p1;
48398   pOp->p2 = p2;
48399   pOp->p3 = p3;
48400   pOp->p4.p = 0;
48401   pOp->p4type = P4_NOTUSED;
48402   p->expired = 0;
48403 #ifdef SQLITE_DEBUG
48404   pOp->zComment = 0;
48405   if( sqlite3VdbeAddopTrace ) sqlite3VdbePrintOp(0, i, &p->aOp[i]);
48406 #endif
48407 #ifdef VDBE_PROFILE
48408   pOp->cycles = 0;
48409   pOp->cnt = 0;
48410 #endif
48411   return i;
48412 }
48413 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
48414   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
48415 }
48416 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
48417   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
48418 }
48419 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
48420   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
48421 }
48422
48423
48424 /*
48425 ** Add an opcode that includes the p4 value as a pointer.
48426 */
48427 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
48428   Vdbe *p,            /* Add the opcode to this VM */
48429   int op,             /* The new opcode */
48430   int p1,             /* The P1 operand */
48431   int p2,             /* The P2 operand */
48432   int p3,             /* The P3 operand */
48433   const char *zP4,    /* The P4 operand */
48434   int p4type          /* P4 operand type */
48435 ){
48436   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
48437   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
48438   return addr;
48439 }
48440
48441 /*
48442 ** Add an opcode that includes the p4 value as an integer.
48443 */
48444 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
48445   Vdbe *p,            /* Add the opcode to this VM */
48446   int op,             /* The new opcode */
48447   int p1,             /* The P1 operand */
48448   int p2,             /* The P2 operand */
48449   int p3,             /* The P3 operand */
48450   int p4              /* The P4 operand as an integer */
48451 ){
48452   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
48453   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
48454   return addr;
48455 }
48456
48457 /*
48458 ** Create a new symbolic label for an instruction that has yet to be
48459 ** coded.  The symbolic label is really just a negative number.  The
48460 ** label can be used as the P2 value of an operation.  Later, when
48461 ** the label is resolved to a specific address, the VDBE will scan
48462 ** through its operation list and change all values of P2 which match
48463 ** the label into the resolved address.
48464 **
48465 ** The VDBE knows that a P2 value is a label because labels are
48466 ** always negative and P2 values are suppose to be non-negative.
48467 ** Hence, a negative P2 value is a label that has yet to be resolved.
48468 **
48469 ** Zero is returned if a malloc() fails.
48470 */
48471 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *p){
48472   int i;
48473   i = p->nLabel++;
48474   assert( p->magic==VDBE_MAGIC_INIT );
48475   if( i>=p->nLabelAlloc ){
48476     int n = p->nLabelAlloc*2 + 5;
48477     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
48478                                        n*sizeof(p->aLabel[0]));
48479     p->nLabelAlloc = sqlite3DbMallocSize(p->db, p->aLabel)/sizeof(p->aLabel[0]);
48480   }
48481   if( p->aLabel ){
48482     p->aLabel[i] = -1;
48483   }
48484   return -1-i;
48485 }
48486
48487 /*
48488 ** Resolve label "x" to be the address of the next instruction to
48489 ** be inserted.  The parameter "x" must have been obtained from
48490 ** a prior call to sqlite3VdbeMakeLabel().
48491 */
48492 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *p, int x){
48493   int j = -1-x;
48494   assert( p->magic==VDBE_MAGIC_INIT );
48495   assert( j>=0 && j<p->nLabel );
48496   if( p->aLabel ){
48497     p->aLabel[j] = p->nOp;
48498   }
48499 }
48500
48501 /*
48502 ** Mark the VDBE as one that can only be run one time.
48503 */
48504 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
48505   p->runOnlyOnce = 1;
48506 }
48507
48508 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
48509
48510 /*
48511 ** The following type and function are used to iterate through all opcodes
48512 ** in a Vdbe main program and each of the sub-programs (triggers) it may 
48513 ** invoke directly or indirectly. It should be used as follows:
48514 **
48515 **   Op *pOp;
48516 **   VdbeOpIter sIter;
48517 **
48518 **   memset(&sIter, 0, sizeof(sIter));
48519 **   sIter.v = v;                            // v is of type Vdbe* 
48520 **   while( (pOp = opIterNext(&sIter)) ){
48521 **     // Do something with pOp
48522 **   }
48523 **   sqlite3DbFree(v->db, sIter.apSub);
48524 ** 
48525 */
48526 typedef struct VdbeOpIter VdbeOpIter;
48527 struct VdbeOpIter {
48528   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
48529   SubProgram **apSub;        /* Array of subprograms */
48530   int nSub;                  /* Number of entries in apSub */
48531   int iAddr;                 /* Address of next instruction to return */
48532   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
48533 };
48534 static Op *opIterNext(VdbeOpIter *p){
48535   Vdbe *v = p->v;
48536   Op *pRet = 0;
48537   Op *aOp;
48538   int nOp;
48539
48540   if( p->iSub<=p->nSub ){
48541
48542     if( p->iSub==0 ){
48543       aOp = v->aOp;
48544       nOp = v->nOp;
48545     }else{
48546       aOp = p->apSub[p->iSub-1]->aOp;
48547       nOp = p->apSub[p->iSub-1]->nOp;
48548     }
48549     assert( p->iAddr<nOp );
48550
48551     pRet = &aOp[p->iAddr];
48552     p->iAddr++;
48553     if( p->iAddr==nOp ){
48554       p->iSub++;
48555       p->iAddr = 0;
48556     }
48557   
48558     if( pRet->p4type==P4_SUBPROGRAM ){
48559       int nByte = (p->nSub+1)*sizeof(SubProgram*);
48560       int j;
48561       for(j=0; j<p->nSub; j++){
48562         if( p->apSub[j]==pRet->p4.pProgram ) break;
48563       }
48564       if( j==p->nSub ){
48565         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
48566         if( !p->apSub ){
48567           pRet = 0;
48568         }else{
48569           p->apSub[p->nSub++] = pRet->p4.pProgram;
48570         }
48571       }
48572     }
48573   }
48574
48575   return pRet;
48576 }
48577
48578 /*
48579 ** Check if the program stored in the VM associated with pParse may
48580 ** throw an ABORT exception (causing the statement, but not entire transaction
48581 ** to be rolled back). This condition is true if the main program or any
48582 ** sub-programs contains any of the following:
48583 **
48584 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
48585 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
48586 **   *  OP_Destroy
48587 **   *  OP_VUpdate
48588 **   *  OP_VRename
48589 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
48590 **
48591 ** Then check that the value of Parse.mayAbort is true if an
48592 ** ABORT may be thrown, or false otherwise. Return true if it does
48593 ** match, or false otherwise. This function is intended to be used as
48594 ** part of an assert statement in the compiler. Similar to:
48595 **
48596 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
48597 */
48598 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
48599   int hasAbort = 0;
48600   Op *pOp;
48601   VdbeOpIter sIter;
48602   memset(&sIter, 0, sizeof(sIter));
48603   sIter.v = v;
48604
48605   while( (pOp = opIterNext(&sIter))!=0 ){
48606     int opcode = pOp->opcode;
48607     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
48608 #ifndef SQLITE_OMIT_FOREIGN_KEY
48609      || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1) 
48610 #endif
48611      || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
48612       && (pOp->p1==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
48613     ){
48614       hasAbort = 1;
48615       break;
48616     }
48617   }
48618   sqlite3DbFree(v->db, sIter.apSub);
48619
48620   /* Return true if hasAbort==mayAbort. Or if a malloc failure occured.
48621   ** If malloc failed, then the while() loop above may not have iterated
48622   ** through all opcodes and hasAbort may be set incorrectly. Return
48623   ** true for this case to prevent the assert() in the callers frame
48624   ** from failing.  */
48625   return ( v->db->mallocFailed || hasAbort==mayAbort );
48626 }
48627 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
48628
48629 /*
48630 ** Loop through the program looking for P2 values that are negative
48631 ** on jump instructions.  Each such value is a label.  Resolve the
48632 ** label by setting the P2 value to its correct non-zero value.
48633 **
48634 ** This routine is called once after all opcodes have been inserted.
48635 **
48636 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
48637 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
48638 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
48639 **
48640 ** The Op.opflags field is set on all opcodes.
48641 */
48642 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
48643   int i;
48644   int nMaxArgs = *pMaxFuncArgs;
48645   Op *pOp;
48646   int *aLabel = p->aLabel;
48647   p->readOnly = 1;
48648   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
48649     u8 opcode = pOp->opcode;
48650
48651     pOp->opflags = sqlite3OpcodeProperty[opcode];
48652     if( opcode==OP_Function || opcode==OP_AggStep ){
48653       if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
48654     }else if( opcode==OP_Transaction && pOp->p2!=0 ){
48655       p->readOnly = 0;
48656 #ifndef SQLITE_OMIT_VIRTUALTABLE
48657     }else if( opcode==OP_VUpdate ){
48658       if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
48659     }else if( opcode==OP_VFilter ){
48660       int n;
48661       assert( p->nOp - i >= 3 );
48662       assert( pOp[-1].opcode==OP_Integer );
48663       n = pOp[-1].p1;
48664       if( n>nMaxArgs ) nMaxArgs = n;
48665 #endif
48666     }
48667
48668     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
48669       assert( -1-pOp->p2<p->nLabel );
48670       pOp->p2 = aLabel[-1-pOp->p2];
48671     }
48672   }
48673   sqlite3DbFree(p->db, p->aLabel);
48674   p->aLabel = 0;
48675
48676   *pMaxFuncArgs = nMaxArgs;
48677 }
48678
48679 /*
48680 ** Return the address of the next instruction to be inserted.
48681 */
48682 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
48683   assert( p->magic==VDBE_MAGIC_INIT );
48684   return p->nOp;
48685 }
48686
48687 /*
48688 ** This function returns a pointer to the array of opcodes associated with
48689 ** the Vdbe passed as the first argument. It is the callers responsibility
48690 ** to arrange for the returned array to be eventually freed using the 
48691 ** vdbeFreeOpArray() function.
48692 **
48693 ** Before returning, *pnOp is set to the number of entries in the returned
48694 ** array. Also, *pnMaxArg is set to the larger of its current value and 
48695 ** the number of entries in the Vdbe.apArg[] array required to execute the 
48696 ** returned program.
48697 */
48698 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
48699   VdbeOp *aOp = p->aOp;
48700   assert( aOp && !p->db->mallocFailed );
48701
48702   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
48703   assert( p->aMutex.nMutex==0 );
48704
48705   resolveP2Values(p, pnMaxArg);
48706   *pnOp = p->nOp;
48707   p->aOp = 0;
48708   return aOp;
48709 }
48710
48711 /*
48712 ** Add a whole list of operations to the operation stack.  Return the
48713 ** address of the first operation added.
48714 */
48715 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp){
48716   int addr;
48717   assert( p->magic==VDBE_MAGIC_INIT );
48718   if( p->nOp + nOp > p->nOpAlloc && growOpArray(p) ){
48719     return 0;
48720   }
48721   addr = p->nOp;
48722   if( ALWAYS(nOp>0) ){
48723     int i;
48724     VdbeOpList const *pIn = aOp;
48725     for(i=0; i<nOp; i++, pIn++){
48726       int p2 = pIn->p2;
48727       VdbeOp *pOut = &p->aOp[i+addr];
48728       pOut->opcode = pIn->opcode;
48729       pOut->p1 = pIn->p1;
48730       if( p2<0 && (sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP)!=0 ){
48731         pOut->p2 = addr + ADDR(p2);
48732       }else{
48733         pOut->p2 = p2;
48734       }
48735       pOut->p3 = pIn->p3;
48736       pOut->p4type = P4_NOTUSED;
48737       pOut->p4.p = 0;
48738       pOut->p5 = 0;
48739 #ifdef SQLITE_DEBUG
48740       pOut->zComment = 0;
48741       if( sqlite3VdbeAddopTrace ){
48742         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
48743       }
48744 #endif
48745     }
48746     p->nOp += nOp;
48747   }
48748   return addr;
48749 }
48750
48751 /*
48752 ** Change the value of the P1 operand for a specific instruction.
48753 ** This routine is useful when a large program is loaded from a
48754 ** static array using sqlite3VdbeAddOpList but we want to make a
48755 ** few minor changes to the program.
48756 */
48757 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, int addr, int val){
48758   assert( p!=0 );
48759   assert( addr>=0 );
48760   if( p->nOp>addr ){
48761     p->aOp[addr].p1 = val;
48762   }
48763 }
48764
48765 /*
48766 ** Change the value of the P2 operand for a specific instruction.
48767 ** This routine is useful for setting a jump destination.
48768 */
48769 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, int addr, int val){
48770   assert( p!=0 );
48771   assert( addr>=0 );
48772   if( p->nOp>addr ){
48773     p->aOp[addr].p2 = val;
48774   }
48775 }
48776
48777 /*
48778 ** Change the value of the P3 operand for a specific instruction.
48779 */
48780 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, int addr, int val){
48781   assert( p!=0 );
48782   assert( addr>=0 );
48783   if( p->nOp>addr ){
48784     p->aOp[addr].p3 = val;
48785   }
48786 }
48787
48788 /*
48789 ** Change the value of the P5 operand for the most recently
48790 ** added operation.
48791 */
48792 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
48793   assert( p!=0 );
48794   if( p->aOp ){
48795     assert( p->nOp>0 );
48796     p->aOp[p->nOp-1].p5 = val;
48797   }
48798 }
48799
48800 /*
48801 ** Change the P2 operand of instruction addr so that it points to
48802 ** the address of the next instruction to be coded.
48803 */
48804 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
48805   sqlite3VdbeChangeP2(p, addr, p->nOp);
48806 }
48807
48808
48809 /*
48810 ** If the input FuncDef structure is ephemeral, then free it.  If
48811 ** the FuncDef is not ephermal, then do nothing.
48812 */
48813 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
48814   if( ALWAYS(pDef) && (pDef->flags & SQLITE_FUNC_EPHEM)!=0 ){
48815     sqlite3DbFree(db, pDef);
48816   }
48817 }
48818
48819 /*
48820 ** Delete a P4 value if necessary.
48821 */
48822 static void freeP4(sqlite3 *db, int p4type, void *p4){
48823   if( p4 ){
48824     switch( p4type ){
48825       case P4_REAL:
48826       case P4_INT64:
48827       case P4_MPRINTF:
48828       case P4_DYNAMIC:
48829       case P4_KEYINFO:
48830       case P4_INTARRAY:
48831       case P4_KEYINFO_HANDOFF: {
48832         sqlite3DbFree(db, p4);
48833         break;
48834       }
48835       case P4_VDBEFUNC: {
48836         VdbeFunc *pVdbeFunc = (VdbeFunc *)p4;
48837         freeEphemeralFunction(db, pVdbeFunc->pFunc);
48838         sqlite3VdbeDeleteAuxData(pVdbeFunc, 0);
48839         sqlite3DbFree(db, pVdbeFunc);
48840         break;
48841       }
48842       case P4_FUNCDEF: {
48843         freeEphemeralFunction(db, (FuncDef*)p4);
48844         break;
48845       }
48846       case P4_MEM: {
48847         sqlite3ValueFree((sqlite3_value*)p4);
48848         break;
48849       }
48850       case P4_VTAB : {
48851         sqlite3VtabUnlock((VTable *)p4);
48852         break;
48853       }
48854       case P4_SUBPROGRAM : {
48855         sqlite3VdbeProgramDelete(db, (SubProgram *)p4, 1);
48856         break;
48857       }
48858     }
48859   }
48860 }
48861
48862 /*
48863 ** Free the space allocated for aOp and any p4 values allocated for the
48864 ** opcodes contained within. If aOp is not NULL it is assumed to contain 
48865 ** nOp entries. 
48866 */
48867 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
48868   if( aOp ){
48869     Op *pOp;
48870     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
48871       freeP4(db, pOp->p4type, pOp->p4.p);
48872 #ifdef SQLITE_DEBUG
48873       sqlite3DbFree(db, pOp->zComment);
48874 #endif     
48875     }
48876   }
48877   sqlite3DbFree(db, aOp);
48878 }
48879
48880 /*
48881 ** Decrement the ref-count on the SubProgram structure passed as the
48882 ** second argument. If the ref-count reaches zero, free the structure.
48883 **
48884 ** The array of VDBE opcodes stored as SubProgram.aOp is freed if
48885 ** either the ref-count reaches zero or parameter freeop is non-zero.
48886 **
48887 ** Since the array of opcodes pointed to by SubProgram.aOp may directly
48888 ** or indirectly contain a reference to the SubProgram structure itself.
48889 ** By passing a non-zero freeop parameter, the caller may ensure that all
48890 ** SubProgram structures and their aOp arrays are freed, even when there
48891 ** are such circular references.
48892 */
48893 SQLITE_PRIVATE void sqlite3VdbeProgramDelete(sqlite3 *db, SubProgram *p, int freeop){
48894   if( p ){
48895     assert( p->nRef>0 );
48896     if( freeop || p->nRef==1 ){
48897       Op *aOp = p->aOp;
48898       p->aOp = 0;
48899       vdbeFreeOpArray(db, aOp, p->nOp);
48900       p->nOp = 0;
48901     }
48902     p->nRef--;
48903     if( p->nRef==0 ){
48904       sqlite3DbFree(db, p);
48905     }
48906   }
48907 }
48908
48909
48910 /*
48911 ** Change N opcodes starting at addr to No-ops.
48912 */
48913 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr, int N){
48914   if( p->aOp ){
48915     VdbeOp *pOp = &p->aOp[addr];
48916     sqlite3 *db = p->db;
48917     while( N-- ){
48918       freeP4(db, pOp->p4type, pOp->p4.p);
48919       memset(pOp, 0, sizeof(pOp[0]));
48920       pOp->opcode = OP_Noop;
48921       pOp++;
48922     }
48923   }
48924 }
48925
48926 /*
48927 ** Change the value of the P4 operand for a specific instruction.
48928 ** This routine is useful when a large program is loaded from a
48929 ** static array using sqlite3VdbeAddOpList but we want to make a
48930 ** few minor changes to the program.
48931 **
48932 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
48933 ** the string is made into memory obtained from sqlite3_malloc().
48934 ** A value of n==0 means copy bytes of zP4 up to and including the
48935 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
48936 **
48937 ** If n==P4_KEYINFO it means that zP4 is a pointer to a KeyInfo structure.
48938 ** A copy is made of the KeyInfo structure into memory obtained from
48939 ** sqlite3_malloc, to be freed when the Vdbe is finalized.
48940 ** n==P4_KEYINFO_HANDOFF indicates that zP4 points to a KeyInfo structure
48941 ** stored in memory that the caller has obtained from sqlite3_malloc. The 
48942 ** caller should not free the allocation, it will be freed when the Vdbe is
48943 ** finalized.
48944 ** 
48945 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
48946 ** to a string or structure that is guaranteed to exist for the lifetime of
48947 ** the Vdbe. In these cases we can just copy the pointer.
48948 **
48949 ** If addr<0 then change P4 on the most recently inserted instruction.
48950 */
48951 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
48952   Op *pOp;
48953   sqlite3 *db;
48954   assert( p!=0 );
48955   db = p->db;
48956   assert( p->magic==VDBE_MAGIC_INIT );
48957   if( p->aOp==0 || db->mallocFailed ){
48958     if ( n!=P4_KEYINFO && n!=P4_VTAB ) {
48959       freeP4(db, n, (void*)*(char**)&zP4);
48960     }
48961     return;
48962   }
48963   assert( p->nOp>0 );
48964   assert( addr<p->nOp );
48965   if( addr<0 ){
48966     addr = p->nOp - 1;
48967   }
48968   pOp = &p->aOp[addr];
48969   freeP4(db, pOp->p4type, pOp->p4.p);
48970   pOp->p4.p = 0;
48971   if( n==P4_INT32 ){
48972     /* Note: this cast is safe, because the origin data point was an int
48973     ** that was cast to a (const char *). */
48974     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
48975     pOp->p4type = P4_INT32;
48976   }else if( zP4==0 ){
48977     pOp->p4.p = 0;
48978     pOp->p4type = P4_NOTUSED;
48979   }else if( n==P4_KEYINFO ){
48980     KeyInfo *pKeyInfo;
48981     int nField, nByte;
48982
48983     nField = ((KeyInfo*)zP4)->nField;
48984     nByte = sizeof(*pKeyInfo) + (nField-1)*sizeof(pKeyInfo->aColl[0]) + nField;
48985     pKeyInfo = sqlite3Malloc( nByte );
48986     pOp->p4.pKeyInfo = pKeyInfo;
48987     if( pKeyInfo ){
48988       u8 *aSortOrder;
48989       memcpy(pKeyInfo, zP4, nByte);
48990       aSortOrder = pKeyInfo->aSortOrder;
48991       if( aSortOrder ){
48992         pKeyInfo->aSortOrder = (unsigned char*)&pKeyInfo->aColl[nField];
48993         memcpy(pKeyInfo->aSortOrder, aSortOrder, nField);
48994       }
48995       pOp->p4type = P4_KEYINFO;
48996     }else{
48997       p->db->mallocFailed = 1;
48998       pOp->p4type = P4_NOTUSED;
48999     }
49000   }else if( n==P4_KEYINFO_HANDOFF ){
49001     pOp->p4.p = (void*)zP4;
49002     pOp->p4type = P4_KEYINFO;
49003   }else if( n==P4_VTAB ){
49004     pOp->p4.p = (void*)zP4;
49005     pOp->p4type = P4_VTAB;
49006     sqlite3VtabLock((VTable *)zP4);
49007     assert( ((VTable *)zP4)->db==p->db );
49008   }else if( n<0 ){
49009     pOp->p4.p = (void*)zP4;
49010     pOp->p4type = (signed char)n;
49011   }else{
49012     if( n==0 ) n = sqlite3Strlen30(zP4);
49013     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
49014     pOp->p4type = P4_DYNAMIC;
49015   }
49016 }
49017
49018 #ifndef NDEBUG
49019 /*
49020 ** Change the comment on the the most recently coded instruction.  Or
49021 ** insert a No-op and add the comment to that new instruction.  This
49022 ** makes the code easier to read during debugging.  None of this happens
49023 ** in a production build.
49024 */
49025 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
49026   va_list ap;
49027   if( !p ) return;
49028   assert( p->nOp>0 || p->aOp==0 );
49029   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
49030   if( p->nOp ){
49031     char **pz = &p->aOp[p->nOp-1].zComment;
49032     va_start(ap, zFormat);
49033     sqlite3DbFree(p->db, *pz);
49034     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
49035     va_end(ap);
49036   }
49037 }
49038 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
49039   va_list ap;
49040   if( !p ) return;
49041   sqlite3VdbeAddOp0(p, OP_Noop);
49042   assert( p->nOp>0 || p->aOp==0 );
49043   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
49044   if( p->nOp ){
49045     char **pz = &p->aOp[p->nOp-1].zComment;
49046     va_start(ap, zFormat);
49047     sqlite3DbFree(p->db, *pz);
49048     *pz = sqlite3VMPrintf(p->db, zFormat, ap);
49049     va_end(ap);
49050   }
49051 }
49052 #endif  /* NDEBUG */
49053
49054 /*
49055 ** Return the opcode for a given address.  If the address is -1, then
49056 ** return the most recently inserted opcode.
49057 **
49058 ** If a memory allocation error has occurred prior to the calling of this
49059 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
49060 ** is readable and writable, but it has no effect.  The return of a dummy
49061 ** opcode allows the call to continue functioning after a OOM fault without
49062 ** having to check to see if the return from this routine is a valid pointer.
49063 **
49064 ** About the #ifdef SQLITE_OMIT_TRACE:  Normally, this routine is never called
49065 ** unless p->nOp>0.  This is because in the absense of SQLITE_OMIT_TRACE,
49066 ** an OP_Trace instruction is always inserted by sqlite3VdbeGet() as soon as
49067 ** a new VDBE is created.  So we are free to set addr to p->nOp-1 without
49068 ** having to double-check to make sure that the result is non-negative. But
49069 ** if SQLITE_OMIT_TRACE is defined, the OP_Trace is omitted and we do need to
49070 ** check the value of p->nOp-1 before continuing.
49071 */
49072 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
49073   static VdbeOp dummy;
49074   assert( p->magic==VDBE_MAGIC_INIT );
49075   if( addr<0 ){
49076 #ifdef SQLITE_OMIT_TRACE
49077     if( p->nOp==0 ) return &dummy;
49078 #endif
49079     addr = p->nOp - 1;
49080   }
49081   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
49082   if( p->db->mallocFailed ){
49083     return &dummy;
49084   }else{
49085     return &p->aOp[addr];
49086   }
49087 }
49088
49089 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
49090      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
49091 /*
49092 ** Compute a string that describes the P4 parameter for an opcode.
49093 ** Use zTemp for any required temporary buffer space.
49094 */
49095 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
49096   char *zP4 = zTemp;
49097   assert( nTemp>=20 );
49098   switch( pOp->p4type ){
49099     case P4_KEYINFO_STATIC:
49100     case P4_KEYINFO: {
49101       int i, j;
49102       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
49103       sqlite3_snprintf(nTemp, zTemp, "keyinfo(%d", pKeyInfo->nField);
49104       i = sqlite3Strlen30(zTemp);
49105       for(j=0; j<pKeyInfo->nField; j++){
49106         CollSeq *pColl = pKeyInfo->aColl[j];
49107         if( pColl ){
49108           int n = sqlite3Strlen30(pColl->zName);
49109           if( i+n>nTemp-6 ){
49110             memcpy(&zTemp[i],",...",4);
49111             break;
49112           }
49113           zTemp[i++] = ',';
49114           if( pKeyInfo->aSortOrder && pKeyInfo->aSortOrder[j] ){
49115             zTemp[i++] = '-';
49116           }
49117           memcpy(&zTemp[i], pColl->zName,n+1);
49118           i += n;
49119         }else if( i+4<nTemp-6 ){
49120           memcpy(&zTemp[i],",nil",4);
49121           i += 4;
49122         }
49123       }
49124       zTemp[i++] = ')';
49125       zTemp[i] = 0;
49126       assert( i<nTemp );
49127       break;
49128     }
49129     case P4_COLLSEQ: {
49130       CollSeq *pColl = pOp->p4.pColl;
49131       sqlite3_snprintf(nTemp, zTemp, "collseq(%.20s)", pColl->zName);
49132       break;
49133     }
49134     case P4_FUNCDEF: {
49135       FuncDef *pDef = pOp->p4.pFunc;
49136       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
49137       break;
49138     }
49139     case P4_INT64: {
49140       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
49141       break;
49142     }
49143     case P4_INT32: {
49144       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
49145       break;
49146     }
49147     case P4_REAL: {
49148       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
49149       break;
49150     }
49151     case P4_MEM: {
49152       Mem *pMem = pOp->p4.pMem;
49153       assert( (pMem->flags & MEM_Null)==0 );
49154       if( pMem->flags & MEM_Str ){
49155         zP4 = pMem->z;
49156       }else if( pMem->flags & MEM_Int ){
49157         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
49158       }else if( pMem->flags & MEM_Real ){
49159         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->r);
49160       }else{
49161         assert( pMem->flags & MEM_Blob );
49162         zP4 = "(blob)";
49163       }
49164       break;
49165     }
49166 #ifndef SQLITE_OMIT_VIRTUALTABLE
49167     case P4_VTAB: {
49168       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
49169       sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
49170       break;
49171     }
49172 #endif
49173     case P4_INTARRAY: {
49174       sqlite3_snprintf(nTemp, zTemp, "intarray");
49175       break;
49176     }
49177     case P4_SUBPROGRAM: {
49178       sqlite3_snprintf(nTemp, zTemp, "program");
49179       break;
49180     }
49181     default: {
49182       zP4 = pOp->p4.z;
49183       if( zP4==0 ){
49184         zP4 = zTemp;
49185         zTemp[0] = 0;
49186       }
49187     }
49188   }
49189   assert( zP4!=0 );
49190   return zP4;
49191 }
49192 #endif
49193
49194 /*
49195 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
49196 */
49197 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
49198   int mask;
49199   assert( i>=0 && i<p->db->nDb && i<sizeof(u32)*8 );
49200   assert( i<(int)sizeof(p->btreeMask)*8 );
49201   mask = ((u32)1)<<i;
49202   if( (p->btreeMask & mask)==0 ){
49203     p->btreeMask |= mask;
49204     sqlite3BtreeMutexArrayInsert(&p->aMutex, p->db->aDb[i].pBt);
49205   }
49206 }
49207
49208
49209 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
49210 /*
49211 ** Print a single opcode.  This routine is used for debugging only.
49212 */
49213 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
49214   char *zP4;
49215   char zPtr[50];
49216   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-4s %.2X %s\n";
49217   if( pOut==0 ) pOut = stdout;
49218   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
49219   fprintf(pOut, zFormat1, pc, 
49220       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
49221 #ifdef SQLITE_DEBUG
49222       pOp->zComment ? pOp->zComment : ""
49223 #else
49224       ""
49225 #endif
49226   );
49227   fflush(pOut);
49228 }
49229 #endif
49230
49231 /*
49232 ** Release an array of N Mem elements
49233 */
49234 static void releaseMemArray(Mem *p, int N){
49235   if( p && N ){
49236     Mem *pEnd;
49237     sqlite3 *db = p->db;
49238     u8 malloc_failed = db->mallocFailed;
49239     for(pEnd=&p[N]; p<pEnd; p++){
49240       assert( (&p[1])==pEnd || p[0].db==p[1].db );
49241
49242       /* This block is really an inlined version of sqlite3VdbeMemRelease()
49243       ** that takes advantage of the fact that the memory cell value is 
49244       ** being set to NULL after releasing any dynamic resources.
49245       **
49246       ** The justification for duplicating code is that according to 
49247       ** callgrind, this causes a certain test case to hit the CPU 4.7 
49248       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
49249       ** sqlite3MemRelease() were called from here. With -O2, this jumps
49250       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
49251       ** with no indexes using a single prepared INSERT statement, bind() 
49252       ** and reset(). Inserts are grouped into a transaction.
49253       */
49254       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
49255         sqlite3VdbeMemRelease(p);
49256       }else if( p->zMalloc ){
49257         sqlite3DbFree(db, p->zMalloc);
49258         p->zMalloc = 0;
49259       }
49260
49261       p->flags = MEM_Null;
49262     }
49263     db->mallocFailed = malloc_failed;
49264   }
49265 }
49266
49267 /*
49268 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
49269 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
49270 */
49271 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
49272   int i;
49273   Mem *aMem = VdbeFrameMem(p);
49274   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
49275   for(i=0; i<p->nChildCsr; i++){
49276     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
49277   }
49278   releaseMemArray(aMem, p->nChildMem);
49279   sqlite3DbFree(p->v->db, p);
49280 }
49281
49282 #ifndef SQLITE_OMIT_EXPLAIN
49283 /*
49284 ** Give a listing of the program in the virtual machine.
49285 **
49286 ** The interface is the same as sqlite3VdbeExec().  But instead of
49287 ** running the code, it invokes the callback once for each instruction.
49288 ** This feature is used to implement "EXPLAIN".
49289 **
49290 ** When p->explain==1, each instruction is listed.  When
49291 ** p->explain==2, only OP_Explain instructions are listed and these
49292 ** are shown in a different format.  p->explain==2 is used to implement
49293 ** EXPLAIN QUERY PLAN.
49294 **
49295 ** When p->explain==1, first the main program is listed, then each of
49296 ** the trigger subprograms are listed one by one.
49297 */
49298 SQLITE_PRIVATE int sqlite3VdbeList(
49299   Vdbe *p                   /* The VDBE */
49300 ){
49301   int nRow;                            /* Stop when row count reaches this */
49302   int nSub = 0;                        /* Number of sub-vdbes seen so far */
49303   SubProgram **apSub = 0;              /* Array of sub-vdbes */
49304   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
49305   sqlite3 *db = p->db;                 /* The database connection */
49306   int i;                               /* Loop counter */
49307   int rc = SQLITE_OK;                  /* Return code */
49308   Mem *pMem = p->pResultSet = &p->aMem[1];  /* First Mem of result set */
49309
49310   assert( p->explain );
49311   assert( p->magic==VDBE_MAGIC_RUN );
49312   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
49313
49314   /* Even though this opcode does not use dynamic strings for
49315   ** the result, result columns may become dynamic if the user calls
49316   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
49317   */
49318   releaseMemArray(pMem, 8);
49319
49320   if( p->rc==SQLITE_NOMEM ){
49321     /* This happens if a malloc() inside a call to sqlite3_column_text() or
49322     ** sqlite3_column_text16() failed.  */
49323     db->mallocFailed = 1;
49324     return SQLITE_ERROR;
49325   }
49326
49327   /* When the number of output rows reaches nRow, that means the
49328   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
49329   ** nRow is the sum of the number of rows in the main program, plus
49330   ** the sum of the number of rows in all trigger subprograms encountered
49331   ** so far.  The nRow value will increase as new trigger subprograms are
49332   ** encountered, but p->pc will eventually catch up to nRow.
49333   */
49334   nRow = p->nOp;
49335   if( p->explain==1 ){
49336     /* The first 8 memory cells are used for the result set.  So we will
49337     ** commandeer the 9th cell to use as storage for an array of pointers
49338     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
49339     ** cells.  */
49340     assert( p->nMem>9 );
49341     pSub = &p->aMem[9];
49342     if( pSub->flags&MEM_Blob ){
49343       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
49344       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
49345       nSub = pSub->n/sizeof(Vdbe*);
49346       apSub = (SubProgram **)pSub->z;
49347     }
49348     for(i=0; i<nSub; i++){
49349       nRow += apSub[i]->nOp;
49350     }
49351   }
49352
49353   do{
49354     i = p->pc++;
49355   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
49356   if( i>=nRow ){
49357     p->rc = SQLITE_OK;
49358     rc = SQLITE_DONE;
49359   }else if( db->u1.isInterrupted ){
49360     p->rc = SQLITE_INTERRUPT;
49361     rc = SQLITE_ERROR;
49362     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
49363   }else{
49364     char *z;
49365     Op *pOp;
49366     if( i<p->nOp ){
49367       /* The output line number is small enough that we are still in the
49368       ** main program. */
49369       pOp = &p->aOp[i];
49370     }else{
49371       /* We are currently listing subprograms.  Figure out which one and
49372       ** pick up the appropriate opcode. */
49373       int j;
49374       i -= p->nOp;
49375       for(j=0; i>=apSub[j]->nOp; j++){
49376         i -= apSub[j]->nOp;
49377       }
49378       pOp = &apSub[j]->aOp[i];
49379     }
49380     if( p->explain==1 ){
49381       pMem->flags = MEM_Int;
49382       pMem->type = SQLITE_INTEGER;
49383       pMem->u.i = i;                                /* Program counter */
49384       pMem++;
49385   
49386       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
49387       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode);  /* Opcode */
49388       assert( pMem->z!=0 );
49389       pMem->n = sqlite3Strlen30(pMem->z);
49390       pMem->type = SQLITE_TEXT;
49391       pMem->enc = SQLITE_UTF8;
49392       pMem++;
49393
49394       /* When an OP_Program opcode is encounter (the only opcode that has
49395       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
49396       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
49397       ** has not already been seen.
49398       */
49399       if( pOp->p4type==P4_SUBPROGRAM ){
49400         int nByte = (nSub+1)*sizeof(SubProgram*);
49401         int j;
49402         for(j=0; j<nSub; j++){
49403           if( apSub[j]==pOp->p4.pProgram ) break;
49404         }
49405         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, 1) ){
49406           apSub = (SubProgram **)pSub->z;
49407           apSub[nSub++] = pOp->p4.pProgram;
49408           pSub->flags |= MEM_Blob;
49409           pSub->n = nSub*sizeof(SubProgram*);
49410         }
49411       }
49412     }
49413
49414     pMem->flags = MEM_Int;
49415     pMem->u.i = pOp->p1;                          /* P1 */
49416     pMem->type = SQLITE_INTEGER;
49417     pMem++;
49418
49419     pMem->flags = MEM_Int;
49420     pMem->u.i = pOp->p2;                          /* P2 */
49421     pMem->type = SQLITE_INTEGER;
49422     pMem++;
49423
49424     if( p->explain==1 ){
49425       pMem->flags = MEM_Int;
49426       pMem->u.i = pOp->p3;                          /* P3 */
49427       pMem->type = SQLITE_INTEGER;
49428       pMem++;
49429     }
49430
49431     if( sqlite3VdbeMemGrow(pMem, 32, 0) ){            /* P4 */
49432       assert( p->db->mallocFailed );
49433       return SQLITE_ERROR;
49434     }
49435     pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
49436     z = displayP4(pOp, pMem->z, 32);
49437     if( z!=pMem->z ){
49438       sqlite3VdbeMemSetStr(pMem, z, -1, SQLITE_UTF8, 0);
49439     }else{
49440       assert( pMem->z!=0 );
49441       pMem->n = sqlite3Strlen30(pMem->z);
49442       pMem->enc = SQLITE_UTF8;
49443     }
49444     pMem->type = SQLITE_TEXT;
49445     pMem++;
49446
49447     if( p->explain==1 ){
49448       if( sqlite3VdbeMemGrow(pMem, 4, 0) ){
49449         assert( p->db->mallocFailed );
49450         return SQLITE_ERROR;
49451       }
49452       pMem->flags = MEM_Dyn|MEM_Str|MEM_Term;
49453       pMem->n = 2;
49454       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
49455       pMem->type = SQLITE_TEXT;
49456       pMem->enc = SQLITE_UTF8;
49457       pMem++;
49458   
49459 #ifdef SQLITE_DEBUG
49460       if( pOp->zComment ){
49461         pMem->flags = MEM_Str|MEM_Term;
49462         pMem->z = pOp->zComment;
49463         pMem->n = sqlite3Strlen30(pMem->z);
49464         pMem->enc = SQLITE_UTF8;
49465         pMem->type = SQLITE_TEXT;
49466       }else
49467 #endif
49468       {
49469         pMem->flags = MEM_Null;                       /* Comment */
49470         pMem->type = SQLITE_NULL;
49471       }
49472     }
49473
49474     p->nResColumn = 8 - 5*(p->explain-1);
49475     p->rc = SQLITE_OK;
49476     rc = SQLITE_ROW;
49477   }
49478   return rc;
49479 }
49480 #endif /* SQLITE_OMIT_EXPLAIN */
49481
49482 #ifdef SQLITE_DEBUG
49483 /*
49484 ** Print the SQL that was used to generate a VDBE program.
49485 */
49486 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
49487   int nOp = p->nOp;
49488   VdbeOp *pOp;
49489   if( nOp<1 ) return;
49490   pOp = &p->aOp[0];
49491   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
49492     const char *z = pOp->p4.z;
49493     while( sqlite3Isspace(*z) ) z++;
49494     printf("SQL: [%s]\n", z);
49495   }
49496 }
49497 #endif
49498
49499 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
49500 /*
49501 ** Print an IOTRACE message showing SQL content.
49502 */
49503 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
49504   int nOp = p->nOp;
49505   VdbeOp *pOp;
49506   if( sqlite3IoTrace==0 ) return;
49507   if( nOp<1 ) return;
49508   pOp = &p->aOp[0];
49509   if( pOp->opcode==OP_Trace && pOp->p4.z!=0 ){
49510     int i, j;
49511     char z[1000];
49512     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
49513     for(i=0; sqlite3Isspace(z[i]); i++){}
49514     for(j=0; z[i]; i++){
49515       if( sqlite3Isspace(z[i]) ){
49516         if( z[i-1]!=' ' ){
49517           z[j++] = ' ';
49518         }
49519       }else{
49520         z[j++] = z[i];
49521       }
49522     }
49523     z[j] = 0;
49524     sqlite3IoTrace("SQL %s\n", z);
49525   }
49526 }
49527 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
49528
49529 /*
49530 ** Allocate space from a fixed size buffer and return a pointer to
49531 ** that space.  If insufficient space is available, return NULL.
49532 **
49533 ** The pBuf parameter is the initial value of a pointer which will
49534 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
49535 ** NULL, it means that memory space has already been allocated and that
49536 ** this routine should not allocate any new memory.  When pBuf is not
49537 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
49538 ** is NULL.
49539 **
49540 ** nByte is the number of bytes of space needed.
49541 **
49542 ** *ppFrom points to available space and pEnd points to the end of the
49543 ** available space.  When space is allocated, *ppFrom is advanced past
49544 ** the end of the allocated space.
49545 **
49546 ** *pnByte is a counter of the number of bytes of space that have failed
49547 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
49548 ** request, then increment *pnByte by the amount of the request.
49549 */
49550 static void *allocSpace(
49551   void *pBuf,          /* Where return pointer will be stored */
49552   int nByte,           /* Number of bytes to allocate */
49553   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
49554   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
49555   int *pnByte          /* If allocation cannot be made, increment *pnByte */
49556 ){
49557   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
49558   if( pBuf ) return pBuf;
49559   nByte = ROUND8(nByte);
49560   if( &(*ppFrom)[nByte] <= pEnd ){
49561     pBuf = (void*)*ppFrom;
49562     *ppFrom += nByte;
49563   }else{
49564     *pnByte += nByte;
49565   }
49566   return pBuf;
49567 }
49568
49569 /*
49570 ** Prepare a virtual machine for execution.  This involves things such
49571 ** as allocating stack space and initializing the program counter.
49572 ** After the VDBE has be prepped, it can be executed by one or more
49573 ** calls to sqlite3VdbeExec().  
49574 **
49575 ** This is the only way to move a VDBE from VDBE_MAGIC_INIT to
49576 ** VDBE_MAGIC_RUN.
49577 **
49578 ** This function may be called more than once on a single virtual machine.
49579 ** The first call is made while compiling the SQL statement. Subsequent
49580 ** calls are made as part of the process of resetting a statement to be
49581 ** re-executed (from a call to sqlite3_reset()). The nVar, nMem, nCursor 
49582 ** and isExplain parameters are only passed correct values the first time
49583 ** the function is called. On subsequent calls, from sqlite3_reset(), nVar
49584 ** is passed -1 and nMem, nCursor and isExplain are all passed zero.
49585 */
49586 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
49587   Vdbe *p,                       /* The VDBE */
49588   int nVar,                      /* Number of '?' see in the SQL statement */
49589   int nMem,                      /* Number of memory cells to allocate */
49590   int nCursor,                   /* Number of cursors to allocate */
49591   int nArg,                      /* Maximum number of args in SubPrograms */
49592   int isExplain,                 /* True if the EXPLAIN keywords is present */
49593   int usesStmtJournal            /* True to set Vdbe.usesStmtJournal */
49594 ){
49595   int n;
49596   sqlite3 *db = p->db;
49597
49598   assert( p!=0 );
49599   assert( p->magic==VDBE_MAGIC_INIT );
49600
49601   /* There should be at least one opcode.
49602   */
49603   assert( p->nOp>0 );
49604
49605   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
49606   p->magic = VDBE_MAGIC_RUN;
49607
49608   /* For each cursor required, also allocate a memory cell. Memory
49609   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
49610   ** the vdbe program. Instead they are used to allocate space for
49611   ** VdbeCursor/BtCursor structures. The blob of memory associated with 
49612   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
49613   ** stores the blob of memory associated with cursor 1, etc.
49614   **
49615   ** See also: allocateCursor().
49616   */
49617   nMem += nCursor;
49618
49619   /* Allocate space for memory registers, SQL variables, VDBE cursors and 
49620   ** an array to marshal SQL function arguments in. This is only done the
49621   ** first time this function is called for a given VDBE, not when it is
49622   ** being called from sqlite3_reset() to reset the virtual machine.
49623   */
49624   if( nVar>=0 && ALWAYS(db->mallocFailed==0) ){
49625     u8 *zCsr = (u8 *)&p->aOp[p->nOp];       /* Memory avaliable for alloation */
49626     u8 *zEnd = (u8 *)&p->aOp[p->nOpAlloc];  /* First byte past available mem */
49627     int nByte;                              /* How much extra memory needed */
49628
49629     resolveP2Values(p, &nArg);
49630     p->usesStmtJournal = (u8)usesStmtJournal;
49631     if( isExplain && nMem<10 ){
49632       nMem = 10;
49633     }
49634     memset(zCsr, 0, zEnd-zCsr);
49635     zCsr += (zCsr - (u8*)0)&7;
49636     assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
49637
49638     /* Memory for registers, parameters, cursor, etc, is allocated in two
49639     ** passes.  On the first pass, we try to reuse unused space at the 
49640     ** end of the opcode array.  If we are unable to satisfy all memory
49641     ** requirements by reusing the opcode array tail, then the second
49642     ** pass will fill in the rest using a fresh allocation.  
49643     **
49644     ** This two-pass approach that reuses as much memory as possible from
49645     ** the leftover space at the end of the opcode array can significantly
49646     ** reduce the amount of memory held by a prepared statement.
49647     */
49648     do {
49649       nByte = 0;
49650       p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
49651       p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
49652       p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
49653       p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
49654       p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
49655                             &zCsr, zEnd, &nByte);
49656       if( nByte ){
49657         p->pFree = sqlite3DbMallocZero(db, nByte);
49658       }
49659       zCsr = p->pFree;
49660       zEnd = &zCsr[nByte];
49661     }while( nByte && !db->mallocFailed );
49662
49663     p->nCursor = (u16)nCursor;
49664     if( p->aVar ){
49665       p->nVar = (ynVar)nVar;
49666       for(n=0; n<nVar; n++){
49667         p->aVar[n].flags = MEM_Null;
49668         p->aVar[n].db = db;
49669       }
49670     }
49671     if( p->aMem ){
49672       p->aMem--;                      /* aMem[] goes from 1..nMem */
49673       p->nMem = nMem;                 /*       not from 0..nMem-1 */
49674       for(n=1; n<=nMem; n++){
49675         p->aMem[n].flags = MEM_Null;
49676         p->aMem[n].db = db;
49677       }
49678     }
49679   }
49680 #ifdef SQLITE_DEBUG
49681   for(n=1; n<p->nMem; n++){
49682     assert( p->aMem[n].db==db );
49683   }
49684 #endif
49685
49686   p->pc = -1;
49687   p->rc = SQLITE_OK;
49688   p->errorAction = OE_Abort;
49689   p->explain |= isExplain;
49690   p->magic = VDBE_MAGIC_RUN;
49691   p->nChange = 0;
49692   p->cacheCtr = 1;
49693   p->minWriteFileFormat = 255;
49694   p->iStatement = 0;
49695 #ifdef VDBE_PROFILE
49696   {
49697     int i;
49698     for(i=0; i<p->nOp; i++){
49699       p->aOp[i].cnt = 0;
49700       p->aOp[i].cycles = 0;
49701     }
49702   }
49703 #endif
49704 }
49705
49706 /*
49707 ** Close a VDBE cursor and release all the resources that cursor 
49708 ** happens to hold.
49709 */
49710 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
49711   if( pCx==0 ){
49712     return;
49713   }
49714   if( pCx->pBt ){
49715     sqlite3BtreeClose(pCx->pBt);
49716     /* The pCx->pCursor will be close automatically, if it exists, by
49717     ** the call above. */
49718   }else if( pCx->pCursor ){
49719     sqlite3BtreeCloseCursor(pCx->pCursor);
49720   }
49721 #ifndef SQLITE_OMIT_VIRTUALTABLE
49722   if( pCx->pVtabCursor ){
49723     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
49724     const sqlite3_module *pModule = pCx->pModule;
49725     p->inVtabMethod = 1;
49726     pModule->xClose(pVtabCursor);
49727     p->inVtabMethod = 0;
49728   }
49729 #endif
49730 }
49731
49732 /*
49733 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
49734 ** is used, for example, when a trigger sub-program is halted to restore
49735 ** control to the main program.
49736 */
49737 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
49738   Vdbe *v = pFrame->v;
49739   v->aOp = pFrame->aOp;
49740   v->nOp = pFrame->nOp;
49741   v->aMem = pFrame->aMem;
49742   v->nMem = pFrame->nMem;
49743   v->apCsr = pFrame->apCsr;
49744   v->nCursor = pFrame->nCursor;
49745   v->db->lastRowid = pFrame->lastRowid;
49746   v->nChange = pFrame->nChange;
49747   return pFrame->pc;
49748 }
49749
49750 /*
49751 ** Close all cursors.
49752 **
49753 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
49754 ** cell array. This is necessary as the memory cell array may contain
49755 ** pointers to VdbeFrame objects, which may in turn contain pointers to
49756 ** open cursors.
49757 */
49758 static void closeAllCursors(Vdbe *p){
49759   if( p->pFrame ){
49760     VdbeFrame *pFrame = p->pFrame;
49761     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
49762     sqlite3VdbeFrameRestore(pFrame);
49763   }
49764   p->pFrame = 0;
49765   p->nFrame = 0;
49766
49767   if( p->apCsr ){
49768     int i;
49769     for(i=0; i<p->nCursor; i++){
49770       VdbeCursor *pC = p->apCsr[i];
49771       if( pC ){
49772         sqlite3VdbeFreeCursor(p, pC);
49773         p->apCsr[i] = 0;
49774       }
49775     }
49776   }
49777   if( p->aMem ){
49778     releaseMemArray(&p->aMem[1], p->nMem);
49779   }
49780 }
49781
49782 /*
49783 ** Clean up the VM after execution.
49784 **
49785 ** This routine will automatically close any cursors, lists, and/or
49786 ** sorters that were left open.  It also deletes the values of
49787 ** variables in the aVar[] array.
49788 */
49789 static void Cleanup(Vdbe *p){
49790   sqlite3 *db = p->db;
49791
49792 #ifdef SQLITE_DEBUG
49793   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
49794   ** Vdbe.aMem[] arrays have already been cleaned up.  */
49795   int i;
49796   for(i=0; i<p->nCursor; i++) assert( p->apCsr==0 || p->apCsr[i]==0 );
49797   for(i=1; i<=p->nMem; i++) assert( p->aMem==0 || p->aMem[i].flags==MEM_Null );
49798 #endif
49799
49800   sqlite3DbFree(db, p->zErrMsg);
49801   p->zErrMsg = 0;
49802   p->pResultSet = 0;
49803 }
49804
49805 /*
49806 ** Set the number of result columns that will be returned by this SQL
49807 ** statement. This is now set at compile time, rather than during
49808 ** execution of the vdbe program so that sqlite3_column_count() can
49809 ** be called on an SQL statement before sqlite3_step().
49810 */
49811 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
49812   Mem *pColName;
49813   int n;
49814   sqlite3 *db = p->db;
49815
49816   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
49817   sqlite3DbFree(db, p->aColName);
49818   n = nResColumn*COLNAME_N;
49819   p->nResColumn = (u16)nResColumn;
49820   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
49821   if( p->aColName==0 ) return;
49822   while( n-- > 0 ){
49823     pColName->flags = MEM_Null;
49824     pColName->db = p->db;
49825     pColName++;
49826   }
49827 }
49828
49829 /*
49830 ** Set the name of the idx'th column to be returned by the SQL statement.
49831 ** zName must be a pointer to a nul terminated string.
49832 **
49833 ** This call must be made after a call to sqlite3VdbeSetNumCols().
49834 **
49835 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
49836 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
49837 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
49838 */
49839 SQLITE_PRIVATE int sqlite3VdbeSetColName(
49840   Vdbe *p,                         /* Vdbe being configured */
49841   int idx,                         /* Index of column zName applies to */
49842   int var,                         /* One of the COLNAME_* constants */
49843   const char *zName,               /* Pointer to buffer containing name */
49844   void (*xDel)(void*)              /* Memory management strategy for zName */
49845 ){
49846   int rc;
49847   Mem *pColName;
49848   assert( idx<p->nResColumn );
49849   assert( var<COLNAME_N );
49850   if( p->db->mallocFailed ){
49851     assert( !zName || xDel!=SQLITE_DYNAMIC );
49852     return SQLITE_NOMEM;
49853   }
49854   assert( p->aColName!=0 );
49855   pColName = &(p->aColName[idx+var*p->nResColumn]);
49856   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
49857   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
49858   return rc;
49859 }
49860
49861 /*
49862 ** A read or write transaction may or may not be active on database handle
49863 ** db. If a transaction is active, commit it. If there is a
49864 ** write-transaction spanning more than one database file, this routine
49865 ** takes care of the master journal trickery.
49866 */
49867 static int vdbeCommit(sqlite3 *db, Vdbe *p){
49868   int i;
49869   int nTrans = 0;  /* Number of databases with an active write-transaction */
49870   int rc = SQLITE_OK;
49871   int needXcommit = 0;
49872
49873 #ifdef SQLITE_OMIT_VIRTUALTABLE
49874   /* With this option, sqlite3VtabSync() is defined to be simply 
49875   ** SQLITE_OK so p is not used. 
49876   */
49877   UNUSED_PARAMETER(p);
49878 #endif
49879
49880   /* Before doing anything else, call the xSync() callback for any
49881   ** virtual module tables written in this transaction. This has to
49882   ** be done before determining whether a master journal file is 
49883   ** required, as an xSync() callback may add an attached database
49884   ** to the transaction.
49885   */
49886   rc = sqlite3VtabSync(db, &p->zErrMsg);
49887   if( rc!=SQLITE_OK ){
49888     return rc;
49889   }
49890
49891   /* This loop determines (a) if the commit hook should be invoked and
49892   ** (b) how many database files have open write transactions, not 
49893   ** including the temp database. (b) is important because if more than 
49894   ** one database file has an open write transaction, a master journal
49895   ** file is required for an atomic commit.
49896   */ 
49897   for(i=0; i<db->nDb; i++){ 
49898     Btree *pBt = db->aDb[i].pBt;
49899     if( sqlite3BtreeIsInTrans(pBt) ){
49900       needXcommit = 1;
49901       if( i!=1 ) nTrans++;
49902     }
49903   }
49904
49905   /* If there are any write-transactions at all, invoke the commit hook */
49906   if( needXcommit && db->xCommitCallback ){
49907     rc = db->xCommitCallback(db->pCommitArg);
49908     if( rc ){
49909       return SQLITE_CONSTRAINT;
49910     }
49911   }
49912
49913   /* The simple case - no more than one database file (not counting the
49914   ** TEMP database) has a transaction active.   There is no need for the
49915   ** master-journal.
49916   **
49917   ** If the return value of sqlite3BtreeGetFilename() is a zero length
49918   ** string, it means the main database is :memory: or a temp file.  In 
49919   ** that case we do not support atomic multi-file commits, so use the 
49920   ** simple case then too.
49921   */
49922   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
49923    || nTrans<=1
49924   ){
49925     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
49926       Btree *pBt = db->aDb[i].pBt;
49927       if( pBt ){
49928         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
49929       }
49930     }
49931
49932     /* Do the commit only if all databases successfully complete phase 1. 
49933     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
49934     ** IO error while deleting or truncating a journal file. It is unlikely,
49935     ** but could happen. In this case abandon processing and return the error.
49936     */
49937     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
49938       Btree *pBt = db->aDb[i].pBt;
49939       if( pBt ){
49940         rc = sqlite3BtreeCommitPhaseTwo(pBt);
49941       }
49942     }
49943     if( rc==SQLITE_OK ){
49944       sqlite3VtabCommit(db);
49945     }
49946   }
49947
49948   /* The complex case - There is a multi-file write-transaction active.
49949   ** This requires a master journal file to ensure the transaction is
49950   ** committed atomicly.
49951   */
49952 #ifndef SQLITE_OMIT_DISKIO
49953   else{
49954     sqlite3_vfs *pVfs = db->pVfs;
49955     int needSync = 0;
49956     char *zMaster = 0;   /* File-name for the master journal */
49957     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
49958     sqlite3_file *pMaster = 0;
49959     i64 offset = 0;
49960     int res;
49961
49962     /* Select a master journal file name */
49963     do {
49964       u32 iRandom;
49965       sqlite3DbFree(db, zMaster);
49966       sqlite3_randomness(sizeof(iRandom), &iRandom);
49967       zMaster = sqlite3MPrintf(db, "%s-mj%08X", zMainFile, iRandom&0x7fffffff);
49968       if( !zMaster ){
49969         return SQLITE_NOMEM;
49970       }
49971       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
49972     }while( rc==SQLITE_OK && res );
49973     if( rc==SQLITE_OK ){
49974       /* Open the master journal. */
49975       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
49976           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
49977           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
49978       );
49979     }
49980     if( rc!=SQLITE_OK ){
49981       sqlite3DbFree(db, zMaster);
49982       return rc;
49983     }
49984  
49985     /* Write the name of each database file in the transaction into the new
49986     ** master journal file. If an error occurs at this point close
49987     ** and delete the master journal file. All the individual journal files
49988     ** still have 'null' as the master journal pointer, so they will roll
49989     ** back independently if a failure occurs.
49990     */
49991     for(i=0; i<db->nDb; i++){
49992       Btree *pBt = db->aDb[i].pBt;
49993       if( sqlite3BtreeIsInTrans(pBt) ){
49994         char const *zFile = sqlite3BtreeGetJournalname(pBt);
49995         if( zFile==0 || zFile[0]==0 ){
49996           continue;  /* Ignore TEMP and :memory: databases */
49997         }
49998         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
49999           needSync = 1;
50000         }
50001         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
50002         offset += sqlite3Strlen30(zFile)+1;
50003         if( rc!=SQLITE_OK ){
50004           sqlite3OsCloseFree(pMaster);
50005           sqlite3OsDelete(pVfs, zMaster, 0);
50006           sqlite3DbFree(db, zMaster);
50007           return rc;
50008         }
50009       }
50010     }
50011
50012     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
50013     ** flag is set this is not required.
50014     */
50015     if( needSync 
50016      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
50017      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
50018     ){
50019       sqlite3OsCloseFree(pMaster);
50020       sqlite3OsDelete(pVfs, zMaster, 0);
50021       sqlite3DbFree(db, zMaster);
50022       return rc;
50023     }
50024
50025     /* Sync all the db files involved in the transaction. The same call
50026     ** sets the master journal pointer in each individual journal. If
50027     ** an error occurs here, do not delete the master journal file.
50028     **
50029     ** If the error occurs during the first call to
50030     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
50031     ** master journal file will be orphaned. But we cannot delete it,
50032     ** in case the master journal file name was written into the journal
50033     ** file before the failure occurred.
50034     */
50035     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
50036       Btree *pBt = db->aDb[i].pBt;
50037       if( pBt ){
50038         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
50039       }
50040     }
50041     sqlite3OsCloseFree(pMaster);
50042     if( rc!=SQLITE_OK ){
50043       sqlite3DbFree(db, zMaster);
50044       return rc;
50045     }
50046
50047     /* Delete the master journal file. This commits the transaction. After
50048     ** doing this the directory is synced again before any individual
50049     ** transaction files are deleted.
50050     */
50051     rc = sqlite3OsDelete(pVfs, zMaster, 1);
50052     sqlite3DbFree(db, zMaster);
50053     zMaster = 0;
50054     if( rc ){
50055       return rc;
50056     }
50057
50058     /* All files and directories have already been synced, so the following
50059     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
50060     ** deleting or truncating journals. If something goes wrong while
50061     ** this is happening we don't really care. The integrity of the
50062     ** transaction is already guaranteed, but some stray 'cold' journals
50063     ** may be lying around. Returning an error code won't help matters.
50064     */
50065     disable_simulated_io_errors();
50066     sqlite3BeginBenignMalloc();
50067     for(i=0; i<db->nDb; i++){ 
50068       Btree *pBt = db->aDb[i].pBt;
50069       if( pBt ){
50070         sqlite3BtreeCommitPhaseTwo(pBt);
50071       }
50072     }
50073     sqlite3EndBenignMalloc();
50074     enable_simulated_io_errors();
50075
50076     sqlite3VtabCommit(db);
50077   }
50078 #endif
50079
50080   return rc;
50081 }
50082
50083 /* 
50084 ** This routine checks that the sqlite3.activeVdbeCnt count variable
50085 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
50086 ** currently active. An assertion fails if the two counts do not match.
50087 ** This is an internal self-check only - it is not an essential processing
50088 ** step.
50089 **
50090 ** This is a no-op if NDEBUG is defined.
50091 */
50092 #ifndef NDEBUG
50093 static void checkActiveVdbeCnt(sqlite3 *db){
50094   Vdbe *p;
50095   int cnt = 0;
50096   int nWrite = 0;
50097   p = db->pVdbe;
50098   while( p ){
50099     if( p->magic==VDBE_MAGIC_RUN && p->pc>=0 ){
50100       cnt++;
50101       if( p->readOnly==0 ) nWrite++;
50102     }
50103     p = p->pNext;
50104   }
50105   assert( cnt==db->activeVdbeCnt );
50106   assert( nWrite==db->writeVdbeCnt );
50107 }
50108 #else
50109 #define checkActiveVdbeCnt(x)
50110 #endif
50111
50112 /*
50113 ** For every Btree that in database connection db which 
50114 ** has been modified, "trip" or invalidate each cursor in
50115 ** that Btree might have been modified so that the cursor
50116 ** can never be used again.  This happens when a rollback
50117 *** occurs.  We have to trip all the other cursors, even
50118 ** cursor from other VMs in different database connections,
50119 ** so that none of them try to use the data at which they
50120 ** were pointing and which now may have been changed due
50121 ** to the rollback.
50122 **
50123 ** Remember that a rollback can delete tables complete and
50124 ** reorder rootpages.  So it is not sufficient just to save
50125 ** the state of the cursor.  We have to invalidate the cursor
50126 ** so that it is never used again.
50127 */
50128 static void invalidateCursorsOnModifiedBtrees(sqlite3 *db){
50129   int i;
50130   for(i=0; i<db->nDb; i++){
50131     Btree *p = db->aDb[i].pBt;
50132     if( p && sqlite3BtreeIsInTrans(p) ){
50133       sqlite3BtreeTripAllCursors(p, SQLITE_ABORT);
50134     }
50135   }
50136 }
50137
50138 /*
50139 ** If the Vdbe passed as the first argument opened a statement-transaction,
50140 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
50141 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
50142 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
50143 ** statement transaction is commtted.
50144 **
50145 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
50146 ** Otherwise SQLITE_OK.
50147 */
50148 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
50149   sqlite3 *const db = p->db;
50150   int rc = SQLITE_OK;
50151
50152   /* If p->iStatement is greater than zero, then this Vdbe opened a 
50153   ** statement transaction that should be closed here. The only exception
50154   ** is that an IO error may have occured, causing an emergency rollback.
50155   ** In this case (db->nStatement==0), and there is nothing to do.
50156   */
50157   if( db->nStatement && p->iStatement ){
50158     int i;
50159     const int iSavepoint = p->iStatement-1;
50160
50161     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
50162     assert( db->nStatement>0 );
50163     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
50164
50165     for(i=0; i<db->nDb; i++){ 
50166       int rc2 = SQLITE_OK;
50167       Btree *pBt = db->aDb[i].pBt;
50168       if( pBt ){
50169         if( eOp==SAVEPOINT_ROLLBACK ){
50170           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
50171         }
50172         if( rc2==SQLITE_OK ){
50173           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
50174         }
50175         if( rc==SQLITE_OK ){
50176           rc = rc2;
50177         }
50178       }
50179     }
50180     db->nStatement--;
50181     p->iStatement = 0;
50182
50183     /* If the statement transaction is being rolled back, also restore the 
50184     ** database handles deferred constraint counter to the value it had when 
50185     ** the statement transaction was opened.  */
50186     if( eOp==SAVEPOINT_ROLLBACK ){
50187       db->nDeferredCons = p->nStmtDefCons;
50188     }
50189   }
50190   return rc;
50191 }
50192
50193 /*
50194 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
50195 ** this routine obtains the mutex associated with each BtShared structure
50196 ** that may be accessed by the VM passed as an argument. In doing so it
50197 ** sets the BtShared.db member of each of the BtShared structures, ensuring
50198 ** that the correct busy-handler callback is invoked if required.
50199 **
50200 ** If SQLite is not threadsafe but does support shared-cache mode, then
50201 ** sqlite3BtreeEnterAll() is invoked to set the BtShared.db variables
50202 ** of all of BtShared structures accessible via the database handle 
50203 ** associated with the VM. Of course only a subset of these structures
50204 ** will be accessed by the VM, and we could use Vdbe.btreeMask to figure
50205 ** that subset out, but there is no advantage to doing so.
50206 **
50207 ** If SQLite is not threadsafe and does not support shared-cache mode, this
50208 ** function is a no-op.
50209 */
50210 #ifndef SQLITE_OMIT_SHARED_CACHE
50211 SQLITE_PRIVATE void sqlite3VdbeMutexArrayEnter(Vdbe *p){
50212 #if SQLITE_THREADSAFE
50213   sqlite3BtreeMutexArrayEnter(&p->aMutex);
50214 #else
50215   sqlite3BtreeEnterAll(p->db);
50216 #endif
50217 }
50218 #endif
50219
50220 /*
50221 ** This function is called when a transaction opened by the database 
50222 ** handle associated with the VM passed as an argument is about to be 
50223 ** committed. If there are outstanding deferred foreign key constraint
50224 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
50225 **
50226 ** If there are outstanding FK violations and this function returns 
50227 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT and write
50228 ** an error message to it. Then return SQLITE_ERROR.
50229 */
50230 #ifndef SQLITE_OMIT_FOREIGN_KEY
50231 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
50232   sqlite3 *db = p->db;
50233   if( (deferred && db->nDeferredCons>0) || (!deferred && p->nFkConstraint>0) ){
50234     p->rc = SQLITE_CONSTRAINT;
50235     p->errorAction = OE_Abort;
50236     sqlite3SetString(&p->zErrMsg, db, "foreign key constraint failed");
50237     return SQLITE_ERROR;
50238   }
50239   return SQLITE_OK;
50240 }
50241 #endif
50242
50243 /*
50244 ** This routine is called the when a VDBE tries to halt.  If the VDBE
50245 ** has made changes and is in autocommit mode, then commit those
50246 ** changes.  If a rollback is needed, then do the rollback.
50247 **
50248 ** This routine is the only way to move the state of a VM from
50249 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
50250 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
50251 **
50252 ** Return an error code.  If the commit could not complete because of
50253 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
50254 ** means the close did not happen and needs to be repeated.
50255 */
50256 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
50257   int rc;                         /* Used to store transient return codes */
50258   sqlite3 *db = p->db;
50259
50260   /* This function contains the logic that determines if a statement or
50261   ** transaction will be committed or rolled back as a result of the
50262   ** execution of this virtual machine. 
50263   **
50264   ** If any of the following errors occur:
50265   **
50266   **     SQLITE_NOMEM
50267   **     SQLITE_IOERR
50268   **     SQLITE_FULL
50269   **     SQLITE_INTERRUPT
50270   **
50271   ** Then the internal cache might have been left in an inconsistent
50272   ** state.  We need to rollback the statement transaction, if there is
50273   ** one, or the complete transaction if there is no statement transaction.
50274   */
50275
50276   if( p->db->mallocFailed ){
50277     p->rc = SQLITE_NOMEM;
50278   }
50279   closeAllCursors(p);
50280   if( p->magic!=VDBE_MAGIC_RUN ){
50281     return SQLITE_OK;
50282   }
50283   checkActiveVdbeCnt(db);
50284
50285   /* No commit or rollback needed if the program never started */
50286   if( p->pc>=0 ){
50287     int mrc;   /* Primary error code from p->rc */
50288     int eStatementOp = 0;
50289     int isSpecialError;            /* Set to true if a 'special' error */
50290
50291     /* Lock all btrees used by the statement */
50292     sqlite3VdbeMutexArrayEnter(p);
50293
50294     /* Check for one of the special errors */
50295     mrc = p->rc & 0xff;
50296     assert( p->rc!=SQLITE_IOERR_BLOCKED );  /* This error no longer exists */
50297     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
50298                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
50299     if( isSpecialError ){
50300       /* If the query was read-only, we need do no rollback at all. Otherwise,
50301       ** proceed with the special handling.
50302       */
50303       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
50304         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
50305           eStatementOp = SAVEPOINT_ROLLBACK;
50306         }else{
50307           /* We are forced to roll back the active transaction. Before doing
50308           ** so, abort any other statements this handle currently has active.
50309           */
50310           invalidateCursorsOnModifiedBtrees(db);
50311           sqlite3RollbackAll(db);
50312           sqlite3CloseSavepoints(db);
50313           db->autoCommit = 1;
50314         }
50315       }
50316     }
50317
50318     /* Check for immediate foreign key violations. */
50319     if( p->rc==SQLITE_OK ){
50320       sqlite3VdbeCheckFk(p, 0);
50321     }
50322   
50323     /* If the auto-commit flag is set and this is the only active writer 
50324     ** VM, then we do either a commit or rollback of the current transaction. 
50325     **
50326     ** Note: This block also runs if one of the special errors handled 
50327     ** above has occurred. 
50328     */
50329     if( !sqlite3VtabInSync(db) 
50330      && db->autoCommit 
50331      && db->writeVdbeCnt==(p->readOnly==0) 
50332     ){
50333       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
50334         if( sqlite3VdbeCheckFk(p, 1) ){
50335           sqlite3BtreeMutexArrayLeave(&p->aMutex);
50336           return SQLITE_ERROR;
50337         }
50338         /* The auto-commit flag is true, the vdbe program was successful 
50339         ** or hit an 'OR FAIL' constraint and there are no deferred foreign
50340         ** key constraints to hold up the transaction. This means a commit 
50341         ** is required.  */
50342         rc = vdbeCommit(db, p);
50343         if( rc==SQLITE_BUSY ){
50344           sqlite3BtreeMutexArrayLeave(&p->aMutex);
50345           return SQLITE_BUSY;
50346         }else if( rc!=SQLITE_OK ){
50347           p->rc = rc;
50348           sqlite3RollbackAll(db);
50349         }else{
50350           db->nDeferredCons = 0;
50351           sqlite3CommitInternalChanges(db);
50352         }
50353       }else{
50354         sqlite3RollbackAll(db);
50355       }
50356       db->nStatement = 0;
50357     }else if( eStatementOp==0 ){
50358       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
50359         eStatementOp = SAVEPOINT_RELEASE;
50360       }else if( p->errorAction==OE_Abort ){
50361         eStatementOp = SAVEPOINT_ROLLBACK;
50362       }else{
50363         invalidateCursorsOnModifiedBtrees(db);
50364         sqlite3RollbackAll(db);
50365         sqlite3CloseSavepoints(db);
50366         db->autoCommit = 1;
50367       }
50368     }
50369   
50370     /* If eStatementOp is non-zero, then a statement transaction needs to
50371     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
50372     ** do so. If this operation returns an error, and the current statement
50373     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
50374     ** current statement error code.
50375     **
50376     ** Note that sqlite3VdbeCloseStatement() can only fail if eStatementOp
50377     ** is SAVEPOINT_ROLLBACK.  But if p->rc==SQLITE_OK then eStatementOp
50378     ** must be SAVEPOINT_RELEASE.  Hence the NEVER(p->rc==SQLITE_OK) in 
50379     ** the following code.
50380     */
50381     if( eStatementOp ){
50382       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
50383       if( rc && (NEVER(p->rc==SQLITE_OK) || p->rc==SQLITE_CONSTRAINT) ){
50384         p->rc = rc;
50385         sqlite3DbFree(db, p->zErrMsg);
50386         p->zErrMsg = 0;
50387       }
50388     }
50389   
50390     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
50391     ** has been rolled back, update the database connection change-counter. 
50392     */
50393     if( p->changeCntOn ){
50394       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
50395         sqlite3VdbeSetChanges(db, p->nChange);
50396       }else{
50397         sqlite3VdbeSetChanges(db, 0);
50398       }
50399       p->nChange = 0;
50400     }
50401   
50402     /* Rollback or commit any schema changes that occurred. */
50403     if( p->rc!=SQLITE_OK && db->flags&SQLITE_InternChanges ){
50404       sqlite3ResetInternalSchema(db, 0);
50405       db->flags = (db->flags | SQLITE_InternChanges);
50406     }
50407
50408     /* Release the locks */
50409     sqlite3BtreeMutexArrayLeave(&p->aMutex);
50410   }
50411
50412   /* We have successfully halted and closed the VM.  Record this fact. */
50413   if( p->pc>=0 ){
50414     db->activeVdbeCnt--;
50415     if( !p->readOnly ){
50416       db->writeVdbeCnt--;
50417     }
50418     assert( db->activeVdbeCnt>=db->writeVdbeCnt );
50419   }
50420   p->magic = VDBE_MAGIC_HALT;
50421   checkActiveVdbeCnt(db);
50422   if( p->db->mallocFailed ){
50423     p->rc = SQLITE_NOMEM;
50424   }
50425
50426   /* If the auto-commit flag is set to true, then any locks that were held
50427   ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
50428   ** to invoke any required unlock-notify callbacks.
50429   */
50430   if( db->autoCommit ){
50431     sqlite3ConnectionUnlocked(db);
50432   }
50433
50434   assert( db->activeVdbeCnt>0 || db->autoCommit==0 || db->nStatement==0 );
50435   return SQLITE_OK;
50436 }
50437
50438
50439 /*
50440 ** Each VDBE holds the result of the most recent sqlite3_step() call
50441 ** in p->rc.  This routine sets that result back to SQLITE_OK.
50442 */
50443 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
50444   p->rc = SQLITE_OK;
50445 }
50446
50447 /*
50448 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
50449 ** Write any error messages into *pzErrMsg.  Return the result code.
50450 **
50451 ** After this routine is run, the VDBE should be ready to be executed
50452 ** again.
50453 **
50454 ** To look at it another way, this routine resets the state of the
50455 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
50456 ** VDBE_MAGIC_INIT.
50457 */
50458 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
50459   sqlite3 *db;
50460   db = p->db;
50461
50462   /* If the VM did not run to completion or if it encountered an
50463   ** error, then it might not have been halted properly.  So halt
50464   ** it now.
50465   */
50466   sqlite3VdbeHalt(p);
50467
50468   /* If the VDBE has be run even partially, then transfer the error code
50469   ** and error message from the VDBE into the main database structure.  But
50470   ** if the VDBE has just been set to run but has not actually executed any
50471   ** instructions yet, leave the main database error information unchanged.
50472   */
50473   if( p->pc>=0 ){
50474     if( p->zErrMsg ){
50475       sqlite3BeginBenignMalloc();
50476       sqlite3ValueSetStr(db->pErr,-1,p->zErrMsg,SQLITE_UTF8,SQLITE_TRANSIENT);
50477       sqlite3EndBenignMalloc();
50478       db->errCode = p->rc;
50479       sqlite3DbFree(db, p->zErrMsg);
50480       p->zErrMsg = 0;
50481     }else if( p->rc ){
50482       sqlite3Error(db, p->rc, 0);
50483     }else{
50484       sqlite3Error(db, SQLITE_OK, 0);
50485     }
50486     if( p->runOnlyOnce ) p->expired = 1;
50487   }else if( p->rc && p->expired ){
50488     /* The expired flag was set on the VDBE before the first call
50489     ** to sqlite3_step(). For consistency (since sqlite3_step() was
50490     ** called), set the database error in this case as well.
50491     */
50492     sqlite3Error(db, p->rc, 0);
50493     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
50494     sqlite3DbFree(db, p->zErrMsg);
50495     p->zErrMsg = 0;
50496   }
50497
50498   /* Reclaim all memory used by the VDBE
50499   */
50500   Cleanup(p);
50501
50502   /* Save profiling information from this VDBE run.
50503   */
50504 #ifdef VDBE_PROFILE
50505   {
50506     FILE *out = fopen("vdbe_profile.out", "a");
50507     if( out ){
50508       int i;
50509       fprintf(out, "---- ");
50510       for(i=0; i<p->nOp; i++){
50511         fprintf(out, "%02x", p->aOp[i].opcode);
50512       }
50513       fprintf(out, "\n");
50514       for(i=0; i<p->nOp; i++){
50515         fprintf(out, "%6d %10lld %8lld ",
50516            p->aOp[i].cnt,
50517            p->aOp[i].cycles,
50518            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
50519         );
50520         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
50521       }
50522       fclose(out);
50523     }
50524   }
50525 #endif
50526   p->magic = VDBE_MAGIC_INIT;
50527   return p->rc & db->errMask;
50528 }
50529  
50530 /*
50531 ** Clean up and delete a VDBE after execution.  Return an integer which is
50532 ** the result code.  Write any error message text into *pzErrMsg.
50533 */
50534 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
50535   int rc = SQLITE_OK;
50536   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
50537     rc = sqlite3VdbeReset(p);
50538     assert( (rc & p->db->errMask)==rc );
50539   }
50540   sqlite3VdbeDelete(p);
50541   return rc;
50542 }
50543
50544 /*
50545 ** Call the destructor for each auxdata entry in pVdbeFunc for which
50546 ** the corresponding bit in mask is clear.  Auxdata entries beyond 31
50547 ** are always destroyed.  To destroy all auxdata entries, call this
50548 ** routine with mask==0.
50549 */
50550 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(VdbeFunc *pVdbeFunc, int mask){
50551   int i;
50552   for(i=0; i<pVdbeFunc->nAux; i++){
50553     struct AuxData *pAux = &pVdbeFunc->apAux[i];
50554     if( (i>31 || !(mask&(((u32)1)<<i))) && pAux->pAux ){
50555       if( pAux->xDelete ){
50556         pAux->xDelete(pAux->pAux);
50557       }
50558       pAux->pAux = 0;
50559     }
50560   }
50561 }
50562
50563 /*
50564 ** Delete an entire VDBE.
50565 */
50566 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
50567   sqlite3 *db;
50568
50569   if( NEVER(p==0) ) return;
50570   db = p->db;
50571   if( p->pPrev ){
50572     p->pPrev->pNext = p->pNext;
50573   }else{
50574     assert( db->pVdbe==p );
50575     db->pVdbe = p->pNext;
50576   }
50577   if( p->pNext ){
50578     p->pNext->pPrev = p->pPrev;
50579   }
50580   releaseMemArray(p->aVar, p->nVar);
50581   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
50582   vdbeFreeOpArray(db, p->aOp, p->nOp);
50583   sqlite3DbFree(db, p->aLabel);
50584   sqlite3DbFree(db, p->aColName);
50585   sqlite3DbFree(db, p->zSql);
50586   p->magic = VDBE_MAGIC_DEAD;
50587   sqlite3DbFree(db, p->pFree);
50588   p->db = 0;
50589   sqlite3DbFree(db, p);
50590 }
50591
50592 /*
50593 ** Make sure the cursor p is ready to read or write the row to which it
50594 ** was last positioned.  Return an error code if an OOM fault or I/O error
50595 ** prevents us from positioning the cursor to its correct position.
50596 **
50597 ** If a MoveTo operation is pending on the given cursor, then do that
50598 ** MoveTo now.  If no move is pending, check to see if the row has been
50599 ** deleted out from under the cursor and if it has, mark the row as
50600 ** a NULL row.
50601 **
50602 ** If the cursor is already pointing to the correct row and that row has
50603 ** not been deleted out from under the cursor, then this routine is a no-op.
50604 */
50605 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
50606   if( p->deferredMoveto ){
50607     int res, rc;
50608 #ifdef SQLITE_TEST
50609     extern int sqlite3_search_count;
50610 #endif
50611     assert( p->isTable );
50612     rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
50613     if( rc ) return rc;
50614     p->lastRowid = p->movetoTarget;
50615     p->rowidIsValid = ALWAYS(res==0) ?1:0;
50616     if( NEVER(res<0) ){
50617       rc = sqlite3BtreeNext(p->pCursor, &res);
50618       if( rc ) return rc;
50619     }
50620 #ifdef SQLITE_TEST
50621     sqlite3_search_count++;
50622 #endif
50623     p->deferredMoveto = 0;
50624     p->cacheStatus = CACHE_STALE;
50625   }else if( ALWAYS(p->pCursor) ){
50626     int hasMoved;
50627     int rc = sqlite3BtreeCursorHasMoved(p->pCursor, &hasMoved);
50628     if( rc ) return rc;
50629     if( hasMoved ){
50630       p->cacheStatus = CACHE_STALE;
50631       p->nullRow = 1;
50632     }
50633   }
50634   return SQLITE_OK;
50635 }
50636
50637 /*
50638 ** The following functions:
50639 **
50640 ** sqlite3VdbeSerialType()
50641 ** sqlite3VdbeSerialTypeLen()
50642 ** sqlite3VdbeSerialLen()
50643 ** sqlite3VdbeSerialPut()
50644 ** sqlite3VdbeSerialGet()
50645 **
50646 ** encapsulate the code that serializes values for storage in SQLite
50647 ** data and index records. Each serialized value consists of a
50648 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
50649 ** integer, stored as a varint.
50650 **
50651 ** In an SQLite index record, the serial type is stored directly before
50652 ** the blob of data that it corresponds to. In a table record, all serial
50653 ** types are stored at the start of the record, and the blobs of data at
50654 ** the end. Hence these functions allow the caller to handle the
50655 ** serial-type and data blob seperately.
50656 **
50657 ** The following table describes the various storage classes for data:
50658 **
50659 **   serial type        bytes of data      type
50660 **   --------------     ---------------    ---------------
50661 **      0                     0            NULL
50662 **      1                     1            signed integer
50663 **      2                     2            signed integer
50664 **      3                     3            signed integer
50665 **      4                     4            signed integer
50666 **      5                     6            signed integer
50667 **      6                     8            signed integer
50668 **      7                     8            IEEE float
50669 **      8                     0            Integer constant 0
50670 **      9                     0            Integer constant 1
50671 **     10,11                               reserved for expansion
50672 **    N>=12 and even       (N-12)/2        BLOB
50673 **    N>=13 and odd        (N-13)/2        text
50674 **
50675 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
50676 ** of SQLite will not understand those serial types.
50677 */
50678
50679 /*
50680 ** Return the serial-type for the value stored in pMem.
50681 */
50682 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
50683   int flags = pMem->flags;
50684   int n;
50685
50686   if( flags&MEM_Null ){
50687     return 0;
50688   }
50689   if( flags&MEM_Int ){
50690     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
50691 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
50692     i64 i = pMem->u.i;
50693     u64 u;
50694     if( file_format>=4 && (i&1)==i ){
50695       return 8+(u32)i;
50696     }
50697     u = i<0 ? -i : i;
50698     if( u<=127 ) return 1;
50699     if( u<=32767 ) return 2;
50700     if( u<=8388607 ) return 3;
50701     if( u<=2147483647 ) return 4;
50702     if( u<=MAX_6BYTE ) return 5;
50703     return 6;
50704   }
50705   if( flags&MEM_Real ){
50706     return 7;
50707   }
50708   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
50709   n = pMem->n;
50710   if( flags & MEM_Zero ){
50711     n += pMem->u.nZero;
50712   }
50713   assert( n>=0 );
50714   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
50715 }
50716
50717 /*
50718 ** Return the length of the data corresponding to the supplied serial-type.
50719 */
50720 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
50721   if( serial_type>=12 ){
50722     return (serial_type-12)/2;
50723   }else{
50724     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
50725     return aSize[serial_type];
50726   }
50727 }
50728
50729 /*
50730 ** If we are on an architecture with mixed-endian floating 
50731 ** points (ex: ARM7) then swap the lower 4 bytes with the 
50732 ** upper 4 bytes.  Return the result.
50733 **
50734 ** For most architectures, this is a no-op.
50735 **
50736 ** (later):  It is reported to me that the mixed-endian problem
50737 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
50738 ** that early versions of GCC stored the two words of a 64-bit
50739 ** float in the wrong order.  And that error has been propagated
50740 ** ever since.  The blame is not necessarily with GCC, though.
50741 ** GCC might have just copying the problem from a prior compiler.
50742 ** I am also told that newer versions of GCC that follow a different
50743 ** ABI get the byte order right.
50744 **
50745 ** Developers using SQLite on an ARM7 should compile and run their
50746 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
50747 ** enabled, some asserts below will ensure that the byte order of
50748 ** floating point values is correct.
50749 **
50750 ** (2007-08-30)  Frank van Vugt has studied this problem closely
50751 ** and has send his findings to the SQLite developers.  Frank
50752 ** writes that some Linux kernels offer floating point hardware
50753 ** emulation that uses only 32-bit mantissas instead of a full 
50754 ** 48-bits as required by the IEEE standard.  (This is the
50755 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
50756 ** byte swapping becomes very complicated.  To avoid problems,
50757 ** the necessary byte swapping is carried out using a 64-bit integer
50758 ** rather than a 64-bit float.  Frank assures us that the code here
50759 ** works for him.  We, the developers, have no way to independently
50760 ** verify this, but Frank seems to know what he is talking about
50761 ** so we trust him.
50762 */
50763 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
50764 static u64 floatSwap(u64 in){
50765   union {
50766     u64 r;
50767     u32 i[2];
50768   } u;
50769   u32 t;
50770
50771   u.r = in;
50772   t = u.i[0];
50773   u.i[0] = u.i[1];
50774   u.i[1] = t;
50775   return u.r;
50776 }
50777 # define swapMixedEndianFloat(X)  X = floatSwap(X)
50778 #else
50779 # define swapMixedEndianFloat(X)
50780 #endif
50781
50782 /*
50783 ** Write the serialized data blob for the value stored in pMem into 
50784 ** buf. It is assumed that the caller has allocated sufficient space.
50785 ** Return the number of bytes written.
50786 **
50787 ** nBuf is the amount of space left in buf[].  nBuf must always be
50788 ** large enough to hold the entire field.  Except, if the field is
50789 ** a blob with a zero-filled tail, then buf[] might be just the right
50790 ** size to hold everything except for the zero-filled tail.  If buf[]
50791 ** is only big enough to hold the non-zero prefix, then only write that
50792 ** prefix into buf[].  But if buf[] is large enough to hold both the
50793 ** prefix and the tail then write the prefix and set the tail to all
50794 ** zeros.
50795 **
50796 ** Return the number of bytes actually written into buf[].  The number
50797 ** of bytes in the zero-filled tail is included in the return value only
50798 ** if those bytes were zeroed in buf[].
50799 */ 
50800 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, int nBuf, Mem *pMem, int file_format){
50801   u32 serial_type = sqlite3VdbeSerialType(pMem, file_format);
50802   u32 len;
50803
50804   /* Integer and Real */
50805   if( serial_type<=7 && serial_type>0 ){
50806     u64 v;
50807     u32 i;
50808     if( serial_type==7 ){
50809       assert( sizeof(v)==sizeof(pMem->r) );
50810       memcpy(&v, &pMem->r, sizeof(v));
50811       swapMixedEndianFloat(v);
50812     }else{
50813       v = pMem->u.i;
50814     }
50815     len = i = sqlite3VdbeSerialTypeLen(serial_type);
50816     assert( len<=(u32)nBuf );
50817     while( i-- ){
50818       buf[i] = (u8)(v&0xFF);
50819       v >>= 8;
50820     }
50821     return len;
50822   }
50823
50824   /* String or blob */
50825   if( serial_type>=12 ){
50826     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
50827              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
50828     assert( pMem->n<=nBuf );
50829     len = pMem->n;
50830     memcpy(buf, pMem->z, len);
50831     if( pMem->flags & MEM_Zero ){
50832       len += pMem->u.nZero;
50833       assert( nBuf>=0 );
50834       if( len > (u32)nBuf ){
50835         len = (u32)nBuf;
50836       }
50837       memset(&buf[pMem->n], 0, len-pMem->n);
50838     }
50839     return len;
50840   }
50841
50842   /* NULL or constants 0 or 1 */
50843   return 0;
50844 }
50845
50846 /*
50847 ** Deserialize the data blob pointed to by buf as serial type serial_type
50848 ** and store the result in pMem.  Return the number of bytes read.
50849 */ 
50850 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
50851   const unsigned char *buf,     /* Buffer to deserialize from */
50852   u32 serial_type,              /* Serial type to deserialize */
50853   Mem *pMem                     /* Memory cell to write value into */
50854 ){
50855   switch( serial_type ){
50856     case 10:   /* Reserved for future use */
50857     case 11:   /* Reserved for future use */
50858     case 0: {  /* NULL */
50859       pMem->flags = MEM_Null;
50860       break;
50861     }
50862     case 1: { /* 1-byte signed integer */
50863       pMem->u.i = (signed char)buf[0];
50864       pMem->flags = MEM_Int;
50865       return 1;
50866     }
50867     case 2: { /* 2-byte signed integer */
50868       pMem->u.i = (((signed char)buf[0])<<8) | buf[1];
50869       pMem->flags = MEM_Int;
50870       return 2;
50871     }
50872     case 3: { /* 3-byte signed integer */
50873       pMem->u.i = (((signed char)buf[0])<<16) | (buf[1]<<8) | buf[2];
50874       pMem->flags = MEM_Int;
50875       return 3;
50876     }
50877     case 4: { /* 4-byte signed integer */
50878       pMem->u.i = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
50879       pMem->flags = MEM_Int;
50880       return 4;
50881     }
50882     case 5: { /* 6-byte signed integer */
50883       u64 x = (((signed char)buf[0])<<8) | buf[1];
50884       u32 y = (buf[2]<<24) | (buf[3]<<16) | (buf[4]<<8) | buf[5];
50885       x = (x<<32) | y;
50886       pMem->u.i = *(i64*)&x;
50887       pMem->flags = MEM_Int;
50888       return 6;
50889     }
50890     case 6:   /* 8-byte signed integer */
50891     case 7: { /* IEEE floating point */
50892       u64 x;
50893       u32 y;
50894 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
50895       /* Verify that integers and floating point values use the same
50896       ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
50897       ** defined that 64-bit floating point values really are mixed
50898       ** endian.
50899       */
50900       static const u64 t1 = ((u64)0x3ff00000)<<32;
50901       static const double r1 = 1.0;
50902       u64 t2 = t1;
50903       swapMixedEndianFloat(t2);
50904       assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
50905 #endif
50906
50907       x = (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
50908       y = (buf[4]<<24) | (buf[5]<<16) | (buf[6]<<8) | buf[7];
50909       x = (x<<32) | y;
50910       if( serial_type==6 ){
50911         pMem->u.i = *(i64*)&x;
50912         pMem->flags = MEM_Int;
50913       }else{
50914         assert( sizeof(x)==8 && sizeof(pMem->r)==8 );
50915         swapMixedEndianFloat(x);
50916         memcpy(&pMem->r, &x, sizeof(x));
50917         pMem->flags = sqlite3IsNaN(pMem->r) ? MEM_Null : MEM_Real;
50918       }
50919       return 8;
50920     }
50921     case 8:    /* Integer 0 */
50922     case 9: {  /* Integer 1 */
50923       pMem->u.i = serial_type-8;
50924       pMem->flags = MEM_Int;
50925       return 0;
50926     }
50927     default: {
50928       u32 len = (serial_type-12)/2;
50929       pMem->z = (char *)buf;
50930       pMem->n = len;
50931       pMem->xDel = 0;
50932       if( serial_type&0x01 ){
50933         pMem->flags = MEM_Str | MEM_Ephem;
50934       }else{
50935         pMem->flags = MEM_Blob | MEM_Ephem;
50936       }
50937       return len;
50938     }
50939   }
50940   return 0;
50941 }
50942
50943
50944 /*
50945 ** Given the nKey-byte encoding of a record in pKey[], parse the
50946 ** record into a UnpackedRecord structure.  Return a pointer to
50947 ** that structure.
50948 **
50949 ** The calling function might provide szSpace bytes of memory
50950 ** space at pSpace.  This space can be used to hold the returned
50951 ** VDbeParsedRecord structure if it is large enough.  If it is
50952 ** not big enough, space is obtained from sqlite3_malloc().
50953 **
50954 ** The returned structure should be closed by a call to
50955 ** sqlite3VdbeDeleteUnpackedRecord().
50956 */ 
50957 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeRecordUnpack(
50958   KeyInfo *pKeyInfo,     /* Information about the record format */
50959   int nKey,              /* Size of the binary record */
50960   const void *pKey,      /* The binary record */
50961   char *pSpace,          /* Unaligned space available to hold the object */
50962   int szSpace            /* Size of pSpace[] in bytes */
50963 ){
50964   const unsigned char *aKey = (const unsigned char *)pKey;
50965   UnpackedRecord *p;  /* The unpacked record that we will return */
50966   int nByte;          /* Memory space needed to hold p, in bytes */
50967   int d;
50968   u32 idx;
50969   u16 u;              /* Unsigned loop counter */
50970   u32 szHdr;
50971   Mem *pMem;
50972   int nOff;           /* Increase pSpace by this much to 8-byte align it */
50973   
50974   /*
50975   ** We want to shift the pointer pSpace up such that it is 8-byte aligned.
50976   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift 
50977   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
50978   */
50979   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
50980   pSpace += nOff;
50981   szSpace -= nOff;
50982   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
50983   if( nByte>szSpace ){
50984     p = sqlite3DbMallocRaw(pKeyInfo->db, nByte);
50985     if( p==0 ) return 0;
50986     p->flags = UNPACKED_NEED_FREE | UNPACKED_NEED_DESTROY;
50987   }else{
50988     p = (UnpackedRecord*)pSpace;
50989     p->flags = UNPACKED_NEED_DESTROY;
50990   }
50991   p->pKeyInfo = pKeyInfo;
50992   p->nField = pKeyInfo->nField + 1;
50993   p->aMem = pMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
50994   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
50995   idx = getVarint32(aKey, szHdr);
50996   d = szHdr;
50997   u = 0;
50998   while( idx<szHdr && u<p->nField && d<=nKey ){
50999     u32 serial_type;
51000
51001     idx += getVarint32(&aKey[idx], serial_type);
51002     pMem->enc = pKeyInfo->enc;
51003     pMem->db = pKeyInfo->db;
51004     pMem->flags = 0;
51005     pMem->zMalloc = 0;
51006     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
51007     pMem++;
51008     u++;
51009   }
51010   assert( u<=pKeyInfo->nField + 1 );
51011   p->nField = u;
51012   return (void*)p;
51013 }
51014
51015 /*
51016 ** This routine destroys a UnpackedRecord object.
51017 */
51018 SQLITE_PRIVATE void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord *p){
51019   int i;
51020   Mem *pMem;
51021
51022   assert( p!=0 );
51023   assert( p->flags & UNPACKED_NEED_DESTROY );
51024   for(i=0, pMem=p->aMem; i<p->nField; i++, pMem++){
51025     /* The unpacked record is always constructed by the
51026     ** sqlite3VdbeUnpackRecord() function above, which makes all
51027     ** strings and blobs static.  And none of the elements are
51028     ** ever transformed, so there is never anything to delete.
51029     */
51030     if( NEVER(pMem->zMalloc) ) sqlite3VdbeMemRelease(pMem);
51031   }
51032   if( p->flags & UNPACKED_NEED_FREE ){
51033     sqlite3DbFree(p->pKeyInfo->db, p);
51034   }
51035 }
51036
51037 /*
51038 ** This function compares the two table rows or index records
51039 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
51040 ** or positive integer if key1 is less than, equal to or 
51041 ** greater than key2.  The {nKey1, pKey1} key must be a blob
51042 ** created by th OP_MakeRecord opcode of the VDBE.  The pPKey2
51043 ** key must be a parsed key such as obtained from
51044 ** sqlite3VdbeParseRecord.
51045 **
51046 ** Key1 and Key2 do not have to contain the same number of fields.
51047 ** The key with fewer fields is usually compares less than the 
51048 ** longer key.  However if the UNPACKED_INCRKEY flags in pPKey2 is set
51049 ** and the common prefixes are equal, then key1 is less than key2.
51050 ** Or if the UNPACKED_MATCH_PREFIX flag is set and the prefixes are
51051 ** equal, then the keys are considered to be equal and
51052 ** the parts beyond the common prefix are ignored.
51053 **
51054 ** If the UNPACKED_IGNORE_ROWID flag is set, then the last byte of
51055 ** the header of pKey1 is ignored.  It is assumed that pKey1 is
51056 ** an index key, and thus ends with a rowid value.  The last byte
51057 ** of the header will therefore be the serial type of the rowid:
51058 ** one of 1, 2, 3, 4, 5, 6, 8, or 9 - the integer serial types.
51059 ** The serial type of the final rowid will always be a single byte.
51060 ** By ignoring this last byte of the header, we force the comparison
51061 ** to ignore the rowid at the end of key1.
51062 */
51063 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
51064   int nKey1, const void *pKey1, /* Left key */
51065   UnpackedRecord *pPKey2        /* Right key */
51066 ){
51067   int d1;            /* Offset into aKey[] of next data element */
51068   u32 idx1;          /* Offset into aKey[] of next header element */
51069   u32 szHdr1;        /* Number of bytes in header */
51070   int i = 0;
51071   int nField;
51072   int rc = 0;
51073   const unsigned char *aKey1 = (const unsigned char *)pKey1;
51074   KeyInfo *pKeyInfo;
51075   Mem mem1;
51076
51077   pKeyInfo = pPKey2->pKeyInfo;
51078   mem1.enc = pKeyInfo->enc;
51079   mem1.db = pKeyInfo->db;
51080   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
51081   VVA_ONLY( mem1.zMalloc = 0; ) /* Only needed by assert() statements */
51082
51083   /* Compilers may complain that mem1.u.i is potentially uninitialized.
51084   ** We could initialize it, as shown here, to silence those complaints.
51085   ** But in fact, mem1.u.i will never actually be used initialized, and doing 
51086   ** the unnecessary initialization has a measurable negative performance
51087   ** impact, since this routine is a very high runner.  And so, we choose
51088   ** to ignore the compiler warnings and leave this variable uninitialized.
51089   */
51090   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
51091   
51092   idx1 = getVarint32(aKey1, szHdr1);
51093   d1 = szHdr1;
51094   if( pPKey2->flags & UNPACKED_IGNORE_ROWID ){
51095     szHdr1--;
51096   }
51097   nField = pKeyInfo->nField;
51098   while( idx1<szHdr1 && i<pPKey2->nField ){
51099     u32 serial_type1;
51100
51101     /* Read the serial types for the next element in each key. */
51102     idx1 += getVarint32( aKey1+idx1, serial_type1 );
51103     if( d1>=nKey1 && sqlite3VdbeSerialTypeLen(serial_type1)>0 ) break;
51104
51105     /* Extract the values to be compared.
51106     */
51107     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
51108
51109     /* Do the comparison
51110     */
51111     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i],
51112                            i<nField ? pKeyInfo->aColl[i] : 0);
51113     if( rc!=0 ){
51114       assert( mem1.zMalloc==0 );  /* See comment below */
51115
51116       /* Invert the result if we are using DESC sort order. */
51117       if( pKeyInfo->aSortOrder && i<nField && pKeyInfo->aSortOrder[i] ){
51118         rc = -rc;
51119       }
51120     
51121       /* If the PREFIX_SEARCH flag is set and all fields except the final
51122       ** rowid field were equal, then clear the PREFIX_SEARCH flag and set 
51123       ** pPKey2->rowid to the value of the rowid field in (pKey1, nKey1).
51124       ** This is used by the OP_IsUnique opcode.
51125       */
51126       if( (pPKey2->flags & UNPACKED_PREFIX_SEARCH) && i==(pPKey2->nField-1) ){
51127         assert( idx1==szHdr1 && rc );
51128         assert( mem1.flags & MEM_Int );
51129         pPKey2->flags &= ~UNPACKED_PREFIX_SEARCH;
51130         pPKey2->rowid = mem1.u.i;
51131       }
51132     
51133       return rc;
51134     }
51135     i++;
51136   }
51137
51138   /* No memory allocation is ever used on mem1.  Prove this using
51139   ** the following assert().  If the assert() fails, it indicates a
51140   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
51141   */
51142   assert( mem1.zMalloc==0 );
51143
51144   /* rc==0 here means that one of the keys ran out of fields and
51145   ** all the fields up to that point were equal. If the UNPACKED_INCRKEY
51146   ** flag is set, then break the tie by treating key2 as larger.
51147   ** If the UPACKED_PREFIX_MATCH flag is set, then keys with common prefixes
51148   ** are considered to be equal.  Otherwise, the longer key is the 
51149   ** larger.  As it happens, the pPKey2 will always be the longer
51150   ** if there is a difference.
51151   */
51152   assert( rc==0 );
51153   if( pPKey2->flags & UNPACKED_INCRKEY ){
51154     rc = -1;
51155   }else if( pPKey2->flags & UNPACKED_PREFIX_MATCH ){
51156     /* Leave rc==0 */
51157   }else if( idx1<szHdr1 ){
51158     rc = 1;
51159   }
51160   return rc;
51161 }
51162  
51163
51164 /*
51165 ** pCur points at an index entry created using the OP_MakeRecord opcode.
51166 ** Read the rowid (the last field in the record) and store it in *rowid.
51167 ** Return SQLITE_OK if everything works, or an error code otherwise.
51168 **
51169 ** pCur might be pointing to text obtained from a corrupt database file.
51170 ** So the content cannot be trusted.  Do appropriate checks on the content.
51171 */
51172 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
51173   i64 nCellKey = 0;
51174   int rc;
51175   u32 szHdr;        /* Size of the header */
51176   u32 typeRowid;    /* Serial type of the rowid */
51177   u32 lenRowid;     /* Size of the rowid */
51178   Mem m, v;
51179
51180   UNUSED_PARAMETER(db);
51181
51182   /* Get the size of the index entry.  Only indices entries of less
51183   ** than 2GiB are support - anything large must be database corruption.
51184   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
51185   ** this code can safely assume that nCellKey is 32-bits  
51186   */
51187   assert( sqlite3BtreeCursorIsValid(pCur) );
51188   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
51189   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
51190   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
51191
51192   /* Read in the complete content of the index entry */
51193   memset(&m, 0, sizeof(m));
51194   rc = sqlite3VdbeMemFromBtree(pCur, 0, (int)nCellKey, 1, &m);
51195   if( rc ){
51196     return rc;
51197   }
51198
51199   /* The index entry must begin with a header size */
51200   (void)getVarint32((u8*)m.z, szHdr);
51201   testcase( szHdr==3 );
51202   testcase( szHdr==m.n );
51203   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
51204     goto idx_rowid_corruption;
51205   }
51206
51207   /* The last field of the index should be an integer - the ROWID.
51208   ** Verify that the last entry really is an integer. */
51209   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
51210   testcase( typeRowid==1 );
51211   testcase( typeRowid==2 );
51212   testcase( typeRowid==3 );
51213   testcase( typeRowid==4 );
51214   testcase( typeRowid==5 );
51215   testcase( typeRowid==6 );
51216   testcase( typeRowid==8 );
51217   testcase( typeRowid==9 );
51218   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
51219     goto idx_rowid_corruption;
51220   }
51221   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
51222   testcase( (u32)m.n==szHdr+lenRowid );
51223   if( unlikely((u32)m.n<szHdr+lenRowid) ){
51224     goto idx_rowid_corruption;
51225   }
51226
51227   /* Fetch the integer off the end of the index record */
51228   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
51229   *rowid = v.u.i;
51230   sqlite3VdbeMemRelease(&m);
51231   return SQLITE_OK;
51232
51233   /* Jump here if database corruption is detected after m has been
51234   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
51235 idx_rowid_corruption:
51236   testcase( m.zMalloc!=0 );
51237   sqlite3VdbeMemRelease(&m);
51238   return SQLITE_CORRUPT_BKPT;
51239 }
51240
51241 /*
51242 ** Compare the key of the index entry that cursor pC is pointing to against
51243 ** the key string in pUnpacked.  Write into *pRes a number
51244 ** that is negative, zero, or positive if pC is less than, equal to,
51245 ** or greater than pUnpacked.  Return SQLITE_OK on success.
51246 **
51247 ** pUnpacked is either created without a rowid or is truncated so that it
51248 ** omits the rowid at the end.  The rowid at the end of the index entry
51249 ** is ignored as well.  Hence, this routine only compares the prefixes 
51250 ** of the keys prior to the final rowid, not the entire key.
51251 */
51252 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
51253   VdbeCursor *pC,             /* The cursor to compare against */
51254   UnpackedRecord *pUnpacked,  /* Unpacked version of key to compare against */
51255   int *res                    /* Write the comparison result here */
51256 ){
51257   i64 nCellKey = 0;
51258   int rc;
51259   BtCursor *pCur = pC->pCursor;
51260   Mem m;
51261
51262   assert( sqlite3BtreeCursorIsValid(pCur) );
51263   rc = sqlite3BtreeKeySize(pCur, &nCellKey);
51264   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
51265   /* nCellKey will always be between 0 and 0xffffffff because of the say
51266   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
51267   if( nCellKey<=0 || nCellKey>0x7fffffff ){
51268     *res = 0;
51269     return SQLITE_CORRUPT_BKPT;
51270   }
51271   memset(&m, 0, sizeof(m));
51272   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (int)nCellKey, 1, &m);
51273   if( rc ){
51274     return rc;
51275   }
51276   assert( pUnpacked->flags & UNPACKED_IGNORE_ROWID );
51277   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
51278   sqlite3VdbeMemRelease(&m);
51279   return SQLITE_OK;
51280 }
51281
51282 /*
51283 ** This routine sets the value to be returned by subsequent calls to
51284 ** sqlite3_changes() on the database handle 'db'. 
51285 */
51286 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
51287   assert( sqlite3_mutex_held(db->mutex) );
51288   db->nChange = nChange;
51289   db->nTotalChange += nChange;
51290 }
51291
51292 /*
51293 ** Set a flag in the vdbe to update the change counter when it is finalised
51294 ** or reset.
51295 */
51296 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
51297   v->changeCntOn = 1;
51298 }
51299
51300 /*
51301 ** Mark every prepared statement associated with a database connection
51302 ** as expired.
51303 **
51304 ** An expired statement means that recompilation of the statement is
51305 ** recommend.  Statements expire when things happen that make their
51306 ** programs obsolete.  Removing user-defined functions or collating
51307 ** sequences, or changing an authorization function are the types of
51308 ** things that make prepared statements obsolete.
51309 */
51310 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
51311   Vdbe *p;
51312   for(p = db->pVdbe; p; p=p->pNext){
51313     p->expired = 1;
51314   }
51315 }
51316
51317 /*
51318 ** Return the database associated with the Vdbe.
51319 */
51320 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
51321   return v->db;
51322 }
51323
51324 /*
51325 ** Return a pointer to an sqlite3_value structure containing the value bound
51326 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
51327 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
51328 ** constants) to the value before returning it.
51329 **
51330 ** The returned value must be freed by the caller using sqlite3ValueFree().
51331 */
51332 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetValue(Vdbe *v, int iVar, u8 aff){
51333   assert( iVar>0 );
51334   if( v ){
51335     Mem *pMem = &v->aVar[iVar-1];
51336     if( 0==(pMem->flags & MEM_Null) ){
51337       sqlite3_value *pRet = sqlite3ValueNew(v->db);
51338       if( pRet ){
51339         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
51340         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
51341         sqlite3VdbeMemStoreType((Mem *)pRet);
51342       }
51343       return pRet;
51344     }
51345   }
51346   return 0;
51347 }
51348
51349 /*
51350 ** Configure SQL variable iVar so that binding a new value to it signals
51351 ** to sqlite3_reoptimize() that re-preparing the statement may result
51352 ** in a better query plan.
51353 */
51354 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
51355   assert( iVar>0 );
51356   if( iVar>32 ){
51357     v->expmask = 0xffffffff;
51358   }else{
51359     v->expmask |= ((u32)1 << (iVar-1));
51360   }
51361 }
51362
51363 /************** End of vdbeaux.c *********************************************/
51364 /************** Begin file vdbeapi.c *****************************************/
51365 /*
51366 ** 2004 May 26
51367 **
51368 ** The author disclaims copyright to this source code.  In place of
51369 ** a legal notice, here is a blessing:
51370 **
51371 **    May you do good and not evil.
51372 **    May you find forgiveness for yourself and forgive others.
51373 **    May you share freely, never taking more than you give.
51374 **
51375 *************************************************************************
51376 **
51377 ** This file contains code use to implement APIs that are part of the
51378 ** VDBE.
51379 */
51380
51381 #ifndef SQLITE_OMIT_DEPRECATED
51382 /*
51383 ** Return TRUE (non-zero) of the statement supplied as an argument needs
51384 ** to be recompiled.  A statement needs to be recompiled whenever the
51385 ** execution environment changes in a way that would alter the program
51386 ** that sqlite3_prepare() generates.  For example, if new functions or
51387 ** collating sequences are registered or if an authorizer function is
51388 ** added or changed.
51389 */
51390 SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
51391   Vdbe *p = (Vdbe*)pStmt;
51392   return p==0 || p->expired;
51393 }
51394 #endif
51395
51396 /*
51397 ** Check on a Vdbe to make sure it has not been finalized.  Log
51398 ** an error and return true if it has been finalized (or is otherwise
51399 ** invalid).  Return false if it is ok.
51400 */
51401 static int vdbeSafety(Vdbe *p){
51402   if( p->db==0 ){
51403     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
51404     return 1;
51405   }else{
51406     return 0;
51407   }
51408 }
51409 static int vdbeSafetyNotNull(Vdbe *p){
51410   if( p==0 ){
51411     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
51412     return 1;
51413   }else{
51414     return vdbeSafety(p);
51415   }
51416 }
51417
51418 /*
51419 ** The following routine destroys a virtual machine that is created by
51420 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
51421 ** success/failure code that describes the result of executing the virtual
51422 ** machine.
51423 **
51424 ** This routine sets the error code and string returned by
51425 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
51426 */
51427 SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
51428   int rc;
51429   if( pStmt==0 ){
51430     rc = SQLITE_OK;
51431   }else{
51432     Vdbe *v = (Vdbe*)pStmt;
51433     sqlite3 *db = v->db;
51434 #if SQLITE_THREADSAFE
51435     sqlite3_mutex *mutex;
51436 #endif
51437     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
51438 #if SQLITE_THREADSAFE
51439     mutex = v->db->mutex;
51440 #endif
51441     sqlite3_mutex_enter(mutex);
51442     rc = sqlite3VdbeFinalize(v);
51443     rc = sqlite3ApiExit(db, rc);
51444     sqlite3_mutex_leave(mutex);
51445   }
51446   return rc;
51447 }
51448
51449 /*
51450 ** Terminate the current execution of an SQL statement and reset it
51451 ** back to its starting state so that it can be reused. A success code from
51452 ** the prior execution is returned.
51453 **
51454 ** This routine sets the error code and string returned by
51455 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
51456 */
51457 SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
51458   int rc;
51459   if( pStmt==0 ){
51460     rc = SQLITE_OK;
51461   }else{
51462     Vdbe *v = (Vdbe*)pStmt;
51463     sqlite3_mutex_enter(v->db->mutex);
51464     rc = sqlite3VdbeReset(v);
51465     sqlite3VdbeMakeReady(v, -1, 0, 0, 0, 0, 0);
51466     assert( (rc & (v->db->errMask))==rc );
51467     rc = sqlite3ApiExit(v->db, rc);
51468     sqlite3_mutex_leave(v->db->mutex);
51469   }
51470   return rc;
51471 }
51472
51473 /*
51474 ** Set all the parameters in the compiled SQL statement to NULL.
51475 */
51476 SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
51477   int i;
51478   int rc = SQLITE_OK;
51479   Vdbe *p = (Vdbe*)pStmt;
51480 #if SQLITE_THREADSAFE
51481   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
51482 #endif
51483   sqlite3_mutex_enter(mutex);
51484   for(i=0; i<p->nVar; i++){
51485     sqlite3VdbeMemRelease(&p->aVar[i]);
51486     p->aVar[i].flags = MEM_Null;
51487   }
51488   if( p->isPrepareV2 && p->expmask ){
51489     p->expired = 1;
51490   }
51491   sqlite3_mutex_leave(mutex);
51492   return rc;
51493 }
51494
51495
51496 /**************************** sqlite3_value_  *******************************
51497 ** The following routines extract information from a Mem or sqlite3_value
51498 ** structure.
51499 */
51500 SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
51501   Mem *p = (Mem*)pVal;
51502   if( p->flags & (MEM_Blob|MEM_Str) ){
51503     sqlite3VdbeMemExpandBlob(p);
51504     p->flags &= ~MEM_Str;
51505     p->flags |= MEM_Blob;
51506     return p->z;
51507   }else{
51508     return sqlite3_value_text(pVal);
51509   }
51510 }
51511 SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
51512   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
51513 }
51514 SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
51515   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
51516 }
51517 SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
51518   return sqlite3VdbeRealValue((Mem*)pVal);
51519 }
51520 SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
51521   return (int)sqlite3VdbeIntValue((Mem*)pVal);
51522 }
51523 SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
51524   return sqlite3VdbeIntValue((Mem*)pVal);
51525 }
51526 SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
51527   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
51528 }
51529 #ifndef SQLITE_OMIT_UTF16
51530 SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
51531   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
51532 }
51533 SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
51534   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
51535 }
51536 SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
51537   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
51538 }
51539 #endif /* SQLITE_OMIT_UTF16 */
51540 SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
51541   return pVal->type;
51542 }
51543
51544 /**************************** sqlite3_result_  *******************************
51545 ** The following routines are used by user-defined functions to specify
51546 ** the function result.
51547 **
51548 ** The setStrOrError() funtion calls sqlite3VdbeMemSetStr() to store the
51549 ** result as a string or blob but if the string or blob is too large, it
51550 ** then sets the error code to SQLITE_TOOBIG
51551 */
51552 static void setResultStrOrError(
51553   sqlite3_context *pCtx,  /* Function context */
51554   const char *z,          /* String pointer */
51555   int n,                  /* Bytes in string, or negative */
51556   u8 enc,                 /* Encoding of z.  0 for BLOBs */
51557   void (*xDel)(void*)     /* Destructor function */
51558 ){
51559   if( sqlite3VdbeMemSetStr(&pCtx->s, z, n, enc, xDel)==SQLITE_TOOBIG ){
51560     sqlite3_result_error_toobig(pCtx);
51561   }
51562 }
51563 SQLITE_API void sqlite3_result_blob(
51564   sqlite3_context *pCtx, 
51565   const void *z, 
51566   int n, 
51567   void (*xDel)(void *)
51568 ){
51569   assert( n>=0 );
51570   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
51571   setResultStrOrError(pCtx, z, n, 0, xDel);
51572 }
51573 SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
51574   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
51575   sqlite3VdbeMemSetDouble(&pCtx->s, rVal);
51576 }
51577 SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
51578   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
51579   pCtx->isError = SQLITE_ERROR;
51580   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
51581 }
51582 #ifndef SQLITE_OMIT_UTF16
51583 SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
51584   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
51585   pCtx->isError = SQLITE_ERROR;
51586   sqlite3VdbeMemSetStr(&pCtx->s, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
51587 }
51588 #endif
51589 SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
51590   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
51591   sqlite3VdbeMemSetInt64(&pCtx->s, (i64)iVal);
51592 }
51593 SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
51594   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
51595   sqlite3VdbeMemSetInt64(&pCtx->s, iVal);
51596 }
51597 SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
51598   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
51599   sqlite3VdbeMemSetNull(&pCtx->s);
51600 }
51601 SQLITE_API void sqlite3_result_text(
51602   sqlite3_context *pCtx, 
51603   const char *z, 
51604   int n,
51605   void (*xDel)(void *)
51606 ){
51607   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
51608   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
51609 }
51610 #ifndef SQLITE_OMIT_UTF16
51611 SQLITE_API void sqlite3_result_text16(
51612   sqlite3_context *pCtx, 
51613   const void *z, 
51614   int n, 
51615   void (*xDel)(void *)
51616 ){
51617   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
51618   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
51619 }
51620 SQLITE_API void sqlite3_result_text16be(
51621   sqlite3_context *pCtx, 
51622   const void *z, 
51623   int n, 
51624   void (*xDel)(void *)
51625 ){
51626   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
51627   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
51628 }
51629 SQLITE_API void sqlite3_result_text16le(
51630   sqlite3_context *pCtx, 
51631   const void *z, 
51632   int n, 
51633   void (*xDel)(void *)
51634 ){
51635   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
51636   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
51637 }
51638 #endif /* SQLITE_OMIT_UTF16 */
51639 SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
51640   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
51641   sqlite3VdbeMemCopy(&pCtx->s, pValue);
51642 }
51643 SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
51644   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
51645   sqlite3VdbeMemSetZeroBlob(&pCtx->s, n);
51646 }
51647 SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
51648   pCtx->isError = errCode;
51649   if( pCtx->s.flags & MEM_Null ){
51650     sqlite3VdbeMemSetStr(&pCtx->s, sqlite3ErrStr(errCode), -1, 
51651                          SQLITE_UTF8, SQLITE_STATIC);
51652   }
51653 }
51654
51655 /* Force an SQLITE_TOOBIG error. */
51656 SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
51657   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
51658   pCtx->isError = SQLITE_TOOBIG;
51659   sqlite3VdbeMemSetStr(&pCtx->s, "string or blob too big", -1, 
51660                        SQLITE_UTF8, SQLITE_STATIC);
51661 }
51662
51663 /* An SQLITE_NOMEM error. */
51664 SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
51665   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
51666   sqlite3VdbeMemSetNull(&pCtx->s);
51667   pCtx->isError = SQLITE_NOMEM;
51668   pCtx->s.db->mallocFailed = 1;
51669 }
51670
51671 /*
51672 ** Execute the statement pStmt, either until a row of data is ready, the
51673 ** statement is completely executed or an error occurs.
51674 **
51675 ** This routine implements the bulk of the logic behind the sqlite_step()
51676 ** API.  The only thing omitted is the automatic recompile if a 
51677 ** schema change has occurred.  That detail is handled by the
51678 ** outer sqlite3_step() wrapper procedure.
51679 */
51680 static int sqlite3Step(Vdbe *p){
51681   sqlite3 *db;
51682   int rc;
51683
51684   assert(p);
51685   if( p->magic!=VDBE_MAGIC_RUN ){
51686     sqlite3_log(SQLITE_MISUSE, 
51687           "attempt to step a halted statement: [%s]", p->zSql);
51688     return SQLITE_MISUSE_BKPT;
51689   }
51690
51691   /* Check that malloc() has not failed. If it has, return early. */
51692   db = p->db;
51693   if( db->mallocFailed ){
51694     p->rc = SQLITE_NOMEM;
51695     return SQLITE_NOMEM;
51696   }
51697
51698   if( p->pc<=0 && p->expired ){
51699     p->rc = SQLITE_SCHEMA;
51700     rc = SQLITE_ERROR;
51701     goto end_of_step;
51702   }
51703   if( p->pc<0 ){
51704     /* If there are no other statements currently running, then
51705     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
51706     ** from interrupting a statement that has not yet started.
51707     */
51708     if( db->activeVdbeCnt==0 ){
51709       db->u1.isInterrupted = 0;
51710     }
51711
51712     assert( db->writeVdbeCnt>0 || db->autoCommit==0 || db->nDeferredCons==0 );
51713
51714 #ifndef SQLITE_OMIT_TRACE
51715     if( db->xProfile && !db->init.busy ){
51716       double rNow;
51717       sqlite3OsCurrentTime(db->pVfs, &rNow);
51718       p->startTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
51719     }
51720 #endif
51721
51722     db->activeVdbeCnt++;
51723     if( p->readOnly==0 ) db->writeVdbeCnt++;
51724     p->pc = 0;
51725   }
51726 #ifndef SQLITE_OMIT_EXPLAIN
51727   if( p->explain ){
51728     rc = sqlite3VdbeList(p);
51729   }else
51730 #endif /* SQLITE_OMIT_EXPLAIN */
51731   {
51732     rc = sqlite3VdbeExec(p);
51733   }
51734
51735 #ifndef SQLITE_OMIT_TRACE
51736   /* Invoke the profile callback if there is one
51737   */
51738   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
51739     double rNow;
51740     u64 elapseTime;
51741
51742     sqlite3OsCurrentTime(db->pVfs, &rNow);
51743     elapseTime = (u64)((rNow - (int)rNow)*3600.0*24.0*1000000000.0);
51744     elapseTime -= p->startTime;
51745     db->xProfile(db->pProfileArg, p->zSql, elapseTime);
51746   }
51747 #endif
51748
51749   db->errCode = rc;
51750   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
51751     p->rc = SQLITE_NOMEM;
51752   }
51753 end_of_step:
51754   /* At this point local variable rc holds the value that should be 
51755   ** returned if this statement was compiled using the legacy 
51756   ** sqlite3_prepare() interface. According to the docs, this can only
51757   ** be one of the values in the first assert() below. Variable p->rc 
51758   ** contains the value that would be returned if sqlite3_finalize() 
51759   ** were called on statement p.
51760   */
51761   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR 
51762        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
51763   );
51764   assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
51765   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
51766     /* If this statement was prepared using sqlite3_prepare_v2(), and an
51767     ** error has occured, then return the error code in p->rc to the
51768     ** caller. Set the error code in the database handle to the same value.
51769     */ 
51770     rc = db->errCode = p->rc;
51771   }
51772   return (rc&db->errMask);
51773 }
51774
51775 /*
51776 ** This is the top-level implementation of sqlite3_step().  Call
51777 ** sqlite3Step() to do most of the work.  If a schema error occurs,
51778 ** call sqlite3Reprepare() and try again.
51779 */
51780 SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
51781   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
51782   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
51783   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
51784   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
51785   sqlite3 *db;             /* The database connection */
51786
51787   if( vdbeSafetyNotNull(v) ){
51788     return SQLITE_MISUSE_BKPT;
51789   }
51790   db = v->db;
51791   sqlite3_mutex_enter(db->mutex);
51792   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
51793          && cnt++ < 5
51794          && (rc2 = rc = sqlite3Reprepare(v))==SQLITE_OK ){
51795     sqlite3_reset(pStmt);
51796     v->expired = 0;
51797   }
51798   if( rc2!=SQLITE_OK && ALWAYS(v->isPrepareV2) && ALWAYS(db->pErr) ){
51799     /* This case occurs after failing to recompile an sql statement. 
51800     ** The error message from the SQL compiler has already been loaded 
51801     ** into the database handle. This block copies the error message 
51802     ** from the database handle into the statement and sets the statement
51803     ** program counter to 0 to ensure that when the statement is 
51804     ** finalized or reset the parser error message is available via
51805     ** sqlite3_errmsg() and sqlite3_errcode().
51806     */
51807     const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
51808     sqlite3DbFree(db, v->zErrMsg);
51809     if( !db->mallocFailed ){
51810       v->zErrMsg = sqlite3DbStrDup(db, zErr);
51811       v->rc = rc2;
51812     } else {
51813       v->zErrMsg = 0;
51814       v->rc = rc = SQLITE_NOMEM;
51815     }
51816   }
51817   rc = sqlite3ApiExit(db, rc);
51818   sqlite3_mutex_leave(db->mutex);
51819   return rc;
51820 }
51821
51822 /*
51823 ** Extract the user data from a sqlite3_context structure and return a
51824 ** pointer to it.
51825 */
51826 SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
51827   assert( p && p->pFunc );
51828   return p->pFunc->pUserData;
51829 }
51830
51831 /*
51832 ** Extract the user data from a sqlite3_context structure and return a
51833 ** pointer to it.
51834 */
51835 SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
51836   assert( p && p->pFunc );
51837   return p->s.db;
51838 }
51839
51840 /*
51841 ** The following is the implementation of an SQL function that always
51842 ** fails with an error message stating that the function is used in the
51843 ** wrong context.  The sqlite3_overload_function() API might construct
51844 ** SQL function that use this routine so that the functions will exist
51845 ** for name resolution but are actually overloaded by the xFindFunction
51846 ** method of virtual tables.
51847 */
51848 SQLITE_PRIVATE void sqlite3InvalidFunction(
51849   sqlite3_context *context,  /* The function calling context */
51850   int NotUsed,               /* Number of arguments to the function */
51851   sqlite3_value **NotUsed2   /* Value of each argument */
51852 ){
51853   const char *zName = context->pFunc->zName;
51854   char *zErr;
51855   UNUSED_PARAMETER2(NotUsed, NotUsed2);
51856   zErr = sqlite3_mprintf(
51857       "unable to use function %s in the requested context", zName);
51858   sqlite3_result_error(context, zErr, -1);
51859   sqlite3_free(zErr);
51860 }
51861
51862 /*
51863 ** Allocate or return the aggregate context for a user function.  A new
51864 ** context is allocated on the first call.  Subsequent calls return the
51865 ** same context that was returned on prior calls.
51866 */
51867 SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
51868   Mem *pMem;
51869   assert( p && p->pFunc && p->pFunc->xStep );
51870   assert( sqlite3_mutex_held(p->s.db->mutex) );
51871   pMem = p->pMem;
51872   testcase( nByte<0 );
51873   if( (pMem->flags & MEM_Agg)==0 ){
51874     if( nByte<=0 ){
51875       sqlite3VdbeMemReleaseExternal(pMem);
51876       pMem->flags = MEM_Null;
51877       pMem->z = 0;
51878     }else{
51879       sqlite3VdbeMemGrow(pMem, nByte, 0);
51880       pMem->flags = MEM_Agg;
51881       pMem->u.pDef = p->pFunc;
51882       if( pMem->z ){
51883         memset(pMem->z, 0, nByte);
51884       }
51885     }
51886   }
51887   return (void*)pMem->z;
51888 }
51889
51890 /*
51891 ** Return the auxilary data pointer, if any, for the iArg'th argument to
51892 ** the user-function defined by pCtx.
51893 */
51894 SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
51895   VdbeFunc *pVdbeFunc;
51896
51897   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
51898   pVdbeFunc = pCtx->pVdbeFunc;
51899   if( !pVdbeFunc || iArg>=pVdbeFunc->nAux || iArg<0 ){
51900     return 0;
51901   }
51902   return pVdbeFunc->apAux[iArg].pAux;
51903 }
51904
51905 /*
51906 ** Set the auxilary data pointer and delete function, for the iArg'th
51907 ** argument to the user-function defined by pCtx. Any previous value is
51908 ** deleted by calling the delete function specified when it was set.
51909 */
51910 SQLITE_API void sqlite3_set_auxdata(
51911   sqlite3_context *pCtx, 
51912   int iArg, 
51913   void *pAux, 
51914   void (*xDelete)(void*)
51915 ){
51916   struct AuxData *pAuxData;
51917   VdbeFunc *pVdbeFunc;
51918   if( iArg<0 ) goto failed;
51919
51920   assert( sqlite3_mutex_held(pCtx->s.db->mutex) );
51921   pVdbeFunc = pCtx->pVdbeFunc;
51922   if( !pVdbeFunc || pVdbeFunc->nAux<=iArg ){
51923     int nAux = (pVdbeFunc ? pVdbeFunc->nAux : 0);
51924     int nMalloc = sizeof(VdbeFunc) + sizeof(struct AuxData)*iArg;
51925     pVdbeFunc = sqlite3DbRealloc(pCtx->s.db, pVdbeFunc, nMalloc);
51926     if( !pVdbeFunc ){
51927       goto failed;
51928     }
51929     pCtx->pVdbeFunc = pVdbeFunc;
51930     memset(&pVdbeFunc->apAux[nAux], 0, sizeof(struct AuxData)*(iArg+1-nAux));
51931     pVdbeFunc->nAux = iArg+1;
51932     pVdbeFunc->pFunc = pCtx->pFunc;
51933   }
51934
51935   pAuxData = &pVdbeFunc->apAux[iArg];
51936   if( pAuxData->pAux && pAuxData->xDelete ){
51937     pAuxData->xDelete(pAuxData->pAux);
51938   }
51939   pAuxData->pAux = pAux;
51940   pAuxData->xDelete = xDelete;
51941   return;
51942
51943 failed:
51944   if( xDelete ){
51945     xDelete(pAux);
51946   }
51947 }
51948
51949 #ifndef SQLITE_OMIT_DEPRECATED
51950 /*
51951 ** Return the number of times the Step function of a aggregate has been 
51952 ** called.
51953 **
51954 ** This function is deprecated.  Do not use it for new code.  It is
51955 ** provide only to avoid breaking legacy code.  New aggregate function
51956 ** implementations should keep their own counts within their aggregate
51957 ** context.
51958 */
51959 SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
51960   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
51961   return p->pMem->n;
51962 }
51963 #endif
51964
51965 /*
51966 ** Return the number of columns in the result set for the statement pStmt.
51967 */
51968 SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
51969   Vdbe *pVm = (Vdbe *)pStmt;
51970   return pVm ? pVm->nResColumn : 0;
51971 }
51972
51973 /*
51974 ** Return the number of values available from the current row of the
51975 ** currently executing statement pStmt.
51976 */
51977 SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
51978   Vdbe *pVm = (Vdbe *)pStmt;
51979   if( pVm==0 || pVm->pResultSet==0 ) return 0;
51980   return pVm->nResColumn;
51981 }
51982
51983
51984 /*
51985 ** Check to see if column iCol of the given statement is valid.  If
51986 ** it is, return a pointer to the Mem for the value of that column.
51987 ** If iCol is not valid, return a pointer to a Mem which has a value
51988 ** of NULL.
51989 */
51990 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
51991   Vdbe *pVm;
51992   int vals;
51993   Mem *pOut;
51994
51995   pVm = (Vdbe *)pStmt;
51996   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
51997     sqlite3_mutex_enter(pVm->db->mutex);
51998     vals = sqlite3_data_count(pStmt);
51999     pOut = &pVm->pResultSet[i];
52000   }else{
52001     /* If the value passed as the second argument is out of range, return
52002     ** a pointer to the following static Mem object which contains the
52003     ** value SQL NULL. Even though the Mem structure contains an element
52004     ** of type i64, on certain architecture (x86) with certain compiler
52005     ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
52006     ** instead of an 8-byte one. This all works fine, except that when
52007     ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
52008     ** that a Mem structure is located on an 8-byte boundary. To prevent
52009     ** this assert() from failing, when building with SQLITE_DEBUG defined
52010     ** using gcc, force nullMem to be 8-byte aligned using the magical
52011     ** __attribute__((aligned(8))) macro.  */
52012     static const Mem nullMem 
52013 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
52014       __attribute__((aligned(8))) 
52015 #endif
52016       = {{0}, (double)0, 0, "", 0, MEM_Null, SQLITE_NULL, 0, 0, 0 };
52017
52018     if( pVm && ALWAYS(pVm->db) ){
52019       sqlite3_mutex_enter(pVm->db->mutex);
52020       sqlite3Error(pVm->db, SQLITE_RANGE, 0);
52021     }
52022     pOut = (Mem*)&nullMem;
52023   }
52024   return pOut;
52025 }
52026
52027 /*
52028 ** This function is called after invoking an sqlite3_value_XXX function on a 
52029 ** column value (i.e. a value returned by evaluating an SQL expression in the
52030 ** select list of a SELECT statement) that may cause a malloc() failure. If 
52031 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
52032 ** code of statement pStmt set to SQLITE_NOMEM.
52033 **
52034 ** Specifically, this is called from within:
52035 **
52036 **     sqlite3_column_int()
52037 **     sqlite3_column_int64()
52038 **     sqlite3_column_text()
52039 **     sqlite3_column_text16()
52040 **     sqlite3_column_real()
52041 **     sqlite3_column_bytes()
52042 **     sqlite3_column_bytes16()
52043 **
52044 ** But not for sqlite3_column_blob(), which never calls malloc().
52045 */
52046 static void columnMallocFailure(sqlite3_stmt *pStmt)
52047 {
52048   /* If malloc() failed during an encoding conversion within an
52049   ** sqlite3_column_XXX API, then set the return code of the statement to
52050   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
52051   ** and _finalize() will return NOMEM.
52052   */
52053   Vdbe *p = (Vdbe *)pStmt;
52054   if( p ){
52055     p->rc = sqlite3ApiExit(p->db, p->rc);
52056     sqlite3_mutex_leave(p->db->mutex);
52057   }
52058 }
52059
52060 /**************************** sqlite3_column_  *******************************
52061 ** The following routines are used to access elements of the current row
52062 ** in the result set.
52063 */
52064 SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
52065   const void *val;
52066   val = sqlite3_value_blob( columnMem(pStmt,i) );
52067   /* Even though there is no encoding conversion, value_blob() might
52068   ** need to call malloc() to expand the result of a zeroblob() 
52069   ** expression. 
52070   */
52071   columnMallocFailure(pStmt);
52072   return val;
52073 }
52074 SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
52075   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
52076   columnMallocFailure(pStmt);
52077   return val;
52078 }
52079 SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
52080   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
52081   columnMallocFailure(pStmt);
52082   return val;
52083 }
52084 SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
52085   double val = sqlite3_value_double( columnMem(pStmt,i) );
52086   columnMallocFailure(pStmt);
52087   return val;
52088 }
52089 SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
52090   int val = sqlite3_value_int( columnMem(pStmt,i) );
52091   columnMallocFailure(pStmt);
52092   return val;
52093 }
52094 SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
52095   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
52096   columnMallocFailure(pStmt);
52097   return val;
52098 }
52099 SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
52100   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
52101   columnMallocFailure(pStmt);
52102   return val;
52103 }
52104 SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
52105   Mem *pOut = columnMem(pStmt, i);
52106   if( pOut->flags&MEM_Static ){
52107     pOut->flags &= ~MEM_Static;
52108     pOut->flags |= MEM_Ephem;
52109   }
52110   columnMallocFailure(pStmt);
52111   return (sqlite3_value *)pOut;
52112 }
52113 #ifndef SQLITE_OMIT_UTF16
52114 SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
52115   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
52116   columnMallocFailure(pStmt);
52117   return val;
52118 }
52119 #endif /* SQLITE_OMIT_UTF16 */
52120 SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
52121   int iType = sqlite3_value_type( columnMem(pStmt,i) );
52122   columnMallocFailure(pStmt);
52123   return iType;
52124 }
52125
52126 /* The following function is experimental and subject to change or
52127 ** removal */
52128 /*int sqlite3_column_numeric_type(sqlite3_stmt *pStmt, int i){
52129 **  return sqlite3_value_numeric_type( columnMem(pStmt,i) );
52130 **}
52131 */
52132
52133 /*
52134 ** Convert the N-th element of pStmt->pColName[] into a string using
52135 ** xFunc() then return that string.  If N is out of range, return 0.
52136 **
52137 ** There are up to 5 names for each column.  useType determines which
52138 ** name is returned.  Here are the names:
52139 **
52140 **    0      The column name as it should be displayed for output
52141 **    1      The datatype name for the column
52142 **    2      The name of the database that the column derives from
52143 **    3      The name of the table that the column derives from
52144 **    4      The name of the table column that the result column derives from
52145 **
52146 ** If the result is not a simple column reference (if it is an expression
52147 ** or a constant) then useTypes 2, 3, and 4 return NULL.
52148 */
52149 static const void *columnName(
52150   sqlite3_stmt *pStmt,
52151   int N,
52152   const void *(*xFunc)(Mem*),
52153   int useType
52154 ){
52155   const void *ret = 0;
52156   Vdbe *p = (Vdbe *)pStmt;
52157   int n;
52158   sqlite3 *db = p->db;
52159   
52160   assert( db!=0 );
52161   n = sqlite3_column_count(pStmt);
52162   if( N<n && N>=0 ){
52163     N += useType*n;
52164     sqlite3_mutex_enter(db->mutex);
52165     assert( db->mallocFailed==0 );
52166     ret = xFunc(&p->aColName[N]);
52167      /* A malloc may have failed inside of the xFunc() call. If this
52168     ** is the case, clear the mallocFailed flag and return NULL.
52169     */
52170     if( db->mallocFailed ){
52171       db->mallocFailed = 0;
52172       ret = 0;
52173     }
52174     sqlite3_mutex_leave(db->mutex);
52175   }
52176   return ret;
52177 }
52178
52179 /*
52180 ** Return the name of the Nth column of the result set returned by SQL
52181 ** statement pStmt.
52182 */
52183 SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
52184   return columnName(
52185       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
52186 }
52187 #ifndef SQLITE_OMIT_UTF16
52188 SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
52189   return columnName(
52190       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
52191 }
52192 #endif
52193
52194 /*
52195 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
52196 ** not define OMIT_DECLTYPE.
52197 */
52198 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
52199 # error "Must not define both SQLITE_OMIT_DECLTYPE \
52200          and SQLITE_ENABLE_COLUMN_METADATA"
52201 #endif
52202
52203 #ifndef SQLITE_OMIT_DECLTYPE
52204 /*
52205 ** Return the column declaration type (if applicable) of the 'i'th column
52206 ** of the result set of SQL statement pStmt.
52207 */
52208 SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
52209   return columnName(
52210       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
52211 }
52212 #ifndef SQLITE_OMIT_UTF16
52213 SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
52214   return columnName(
52215       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
52216 }
52217 #endif /* SQLITE_OMIT_UTF16 */
52218 #endif /* SQLITE_OMIT_DECLTYPE */
52219
52220 #ifdef SQLITE_ENABLE_COLUMN_METADATA
52221 /*
52222 ** Return the name of the database from which a result column derives.
52223 ** NULL is returned if the result column is an expression or constant or
52224 ** anything else which is not an unabiguous reference to a database column.
52225 */
52226 SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
52227   return columnName(
52228       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
52229 }
52230 #ifndef SQLITE_OMIT_UTF16
52231 SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
52232   return columnName(
52233       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
52234 }
52235 #endif /* SQLITE_OMIT_UTF16 */
52236
52237 /*
52238 ** Return the name of the table from which a result column derives.
52239 ** NULL is returned if the result column is an expression or constant or
52240 ** anything else which is not an unabiguous reference to a database column.
52241 */
52242 SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
52243   return columnName(
52244       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
52245 }
52246 #ifndef SQLITE_OMIT_UTF16
52247 SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
52248   return columnName(
52249       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
52250 }
52251 #endif /* SQLITE_OMIT_UTF16 */
52252
52253 /*
52254 ** Return the name of the table column from which a result column derives.
52255 ** NULL is returned if the result column is an expression or constant or
52256 ** anything else which is not an unabiguous reference to a database column.
52257 */
52258 SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
52259   return columnName(
52260       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
52261 }
52262 #ifndef SQLITE_OMIT_UTF16
52263 SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
52264   return columnName(
52265       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
52266 }
52267 #endif /* SQLITE_OMIT_UTF16 */
52268 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
52269
52270
52271 /******************************* sqlite3_bind_  ***************************
52272 ** 
52273 ** Routines used to attach values to wildcards in a compiled SQL statement.
52274 */
52275 /*
52276 ** Unbind the value bound to variable i in virtual machine p. This is the 
52277 ** the same as binding a NULL value to the column. If the "i" parameter is
52278 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
52279 **
52280 ** A successful evaluation of this routine acquires the mutex on p.
52281 ** the mutex is released if any kind of error occurs.
52282 **
52283 ** The error code stored in database p->db is overwritten with the return
52284 ** value in any case.
52285 */
52286 static int vdbeUnbind(Vdbe *p, int i){
52287   Mem *pVar;
52288   if( vdbeSafetyNotNull(p) ){
52289     return SQLITE_MISUSE_BKPT;
52290   }
52291   sqlite3_mutex_enter(p->db->mutex);
52292   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
52293     sqlite3Error(p->db, SQLITE_MISUSE, 0);
52294     sqlite3_mutex_leave(p->db->mutex);
52295     sqlite3_log(SQLITE_MISUSE, 
52296         "bind on a busy prepared statement: [%s]", p->zSql);
52297     return SQLITE_MISUSE_BKPT;
52298   }
52299   if( i<1 || i>p->nVar ){
52300     sqlite3Error(p->db, SQLITE_RANGE, 0);
52301     sqlite3_mutex_leave(p->db->mutex);
52302     return SQLITE_RANGE;
52303   }
52304   i--;
52305   pVar = &p->aVar[i];
52306   sqlite3VdbeMemRelease(pVar);
52307   pVar->flags = MEM_Null;
52308   sqlite3Error(p->db, SQLITE_OK, 0);
52309
52310   /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
52311   ** binding a new value to this variable invalidates the current query plan.
52312   */
52313   if( p->isPrepareV2 &&
52314      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
52315   ){
52316     p->expired = 1;
52317   }
52318   return SQLITE_OK;
52319 }
52320
52321 /*
52322 ** Bind a text or BLOB value.
52323 */
52324 static int bindText(
52325   sqlite3_stmt *pStmt,   /* The statement to bind against */
52326   int i,                 /* Index of the parameter to bind */
52327   const void *zData,     /* Pointer to the data to be bound */
52328   int nData,             /* Number of bytes of data to be bound */
52329   void (*xDel)(void*),   /* Destructor for the data */
52330   u8 encoding            /* Encoding for the data */
52331 ){
52332   Vdbe *p = (Vdbe *)pStmt;
52333   Mem *pVar;
52334   int rc;
52335
52336   rc = vdbeUnbind(p, i);
52337   if( rc==SQLITE_OK ){
52338     if( zData!=0 ){
52339       pVar = &p->aVar[i-1];
52340       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
52341       if( rc==SQLITE_OK && encoding!=0 ){
52342         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
52343       }
52344       sqlite3Error(p->db, rc, 0);
52345       rc = sqlite3ApiExit(p->db, rc);
52346     }
52347     sqlite3_mutex_leave(p->db->mutex);
52348   }
52349   return rc;
52350 }
52351
52352
52353 /*
52354 ** Bind a blob value to an SQL statement variable.
52355 */
52356 SQLITE_API int sqlite3_bind_blob(
52357   sqlite3_stmt *pStmt, 
52358   int i, 
52359   const void *zData, 
52360   int nData, 
52361   void (*xDel)(void*)
52362 ){
52363   return bindText(pStmt, i, zData, nData, xDel, 0);
52364 }
52365 SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
52366   int rc;
52367   Vdbe *p = (Vdbe *)pStmt;
52368   rc = vdbeUnbind(p, i);
52369   if( rc==SQLITE_OK ){
52370     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
52371     sqlite3_mutex_leave(p->db->mutex);
52372   }
52373   return rc;
52374 }
52375 SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
52376   return sqlite3_bind_int64(p, i, (i64)iValue);
52377 }
52378 SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
52379   int rc;
52380   Vdbe *p = (Vdbe *)pStmt;
52381   rc = vdbeUnbind(p, i);
52382   if( rc==SQLITE_OK ){
52383     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
52384     sqlite3_mutex_leave(p->db->mutex);
52385   }
52386   return rc;
52387 }
52388 SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
52389   int rc;
52390   Vdbe *p = (Vdbe*)pStmt;
52391   rc = vdbeUnbind(p, i);
52392   if( rc==SQLITE_OK ){
52393     sqlite3_mutex_leave(p->db->mutex);
52394   }
52395   return rc;
52396 }
52397 SQLITE_API int sqlite3_bind_text( 
52398   sqlite3_stmt *pStmt, 
52399   int i, 
52400   const char *zData, 
52401   int nData, 
52402   void (*xDel)(void*)
52403 ){
52404   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
52405 }
52406 #ifndef SQLITE_OMIT_UTF16
52407 SQLITE_API int sqlite3_bind_text16(
52408   sqlite3_stmt *pStmt, 
52409   int i, 
52410   const void *zData, 
52411   int nData, 
52412   void (*xDel)(void*)
52413 ){
52414   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
52415 }
52416 #endif /* SQLITE_OMIT_UTF16 */
52417 SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
52418   int rc;
52419   switch( pValue->type ){
52420     case SQLITE_INTEGER: {
52421       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
52422       break;
52423     }
52424     case SQLITE_FLOAT: {
52425       rc = sqlite3_bind_double(pStmt, i, pValue->r);
52426       break;
52427     }
52428     case SQLITE_BLOB: {
52429       if( pValue->flags & MEM_Zero ){
52430         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
52431       }else{
52432         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
52433       }
52434       break;
52435     }
52436     case SQLITE_TEXT: {
52437       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
52438                               pValue->enc);
52439       break;
52440     }
52441     default: {
52442       rc = sqlite3_bind_null(pStmt, i);
52443       break;
52444     }
52445   }
52446   return rc;
52447 }
52448 SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
52449   int rc;
52450   Vdbe *p = (Vdbe *)pStmt;
52451   rc = vdbeUnbind(p, i);
52452   if( rc==SQLITE_OK ){
52453     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
52454     sqlite3_mutex_leave(p->db->mutex);
52455   }
52456   return rc;
52457 }
52458
52459 /*
52460 ** Return the number of wildcards that can be potentially bound to.
52461 ** This routine is added to support DBD::SQLite.  
52462 */
52463 SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
52464   Vdbe *p = (Vdbe*)pStmt;
52465   return p ? p->nVar : 0;
52466 }
52467
52468 /*
52469 ** Create a mapping from variable numbers to variable names
52470 ** in the Vdbe.azVar[] array, if such a mapping does not already
52471 ** exist.
52472 */
52473 static void createVarMap(Vdbe *p){
52474   if( !p->okVar ){
52475     int j;
52476     Op *pOp;
52477     sqlite3_mutex_enter(p->db->mutex);
52478     /* The race condition here is harmless.  If two threads call this
52479     ** routine on the same Vdbe at the same time, they both might end
52480     ** up initializing the Vdbe.azVar[] array.  That is a little extra
52481     ** work but it results in the same answer.
52482     */
52483     for(j=0, pOp=p->aOp; j<p->nOp; j++, pOp++){
52484       if( pOp->opcode==OP_Variable ){
52485         assert( pOp->p1>0 && pOp->p1<=p->nVar );
52486         p->azVar[pOp->p1-1] = pOp->p4.z;
52487       }
52488     }
52489     p->okVar = 1;
52490     sqlite3_mutex_leave(p->db->mutex);
52491   }
52492 }
52493
52494 /*
52495 ** Return the name of a wildcard parameter.  Return NULL if the index
52496 ** is out of range or if the wildcard is unnamed.
52497 **
52498 ** The result is always UTF-8.
52499 */
52500 SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
52501   Vdbe *p = (Vdbe*)pStmt;
52502   if( p==0 || i<1 || i>p->nVar ){
52503     return 0;
52504   }
52505   createVarMap(p);
52506   return p->azVar[i-1];
52507 }
52508
52509 /*
52510 ** Given a wildcard parameter name, return the index of the variable
52511 ** with that name.  If there is no variable with the given name,
52512 ** return 0.
52513 */
52514 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
52515   int i;
52516   if( p==0 ){
52517     return 0;
52518   }
52519   createVarMap(p); 
52520   if( zName ){
52521     for(i=0; i<p->nVar; i++){
52522       const char *z = p->azVar[i];
52523       if( z && memcmp(z,zName,nName)==0 && z[nName]==0 ){
52524         return i+1;
52525       }
52526     }
52527   }
52528   return 0;
52529 }
52530 SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
52531   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
52532 }
52533
52534 /*
52535 ** Transfer all bindings from the first statement over to the second.
52536 */
52537 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
52538   Vdbe *pFrom = (Vdbe*)pFromStmt;
52539   Vdbe *pTo = (Vdbe*)pToStmt;
52540   int i;
52541   assert( pTo->db==pFrom->db );
52542   assert( pTo->nVar==pFrom->nVar );
52543   sqlite3_mutex_enter(pTo->db->mutex);
52544   for(i=0; i<pFrom->nVar; i++){
52545     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
52546   }
52547   sqlite3_mutex_leave(pTo->db->mutex);
52548   return SQLITE_OK;
52549 }
52550
52551 #ifndef SQLITE_OMIT_DEPRECATED
52552 /*
52553 ** Deprecated external interface.  Internal/core SQLite code
52554 ** should call sqlite3TransferBindings.
52555 **
52556 ** Is is misuse to call this routine with statements from different
52557 ** database connections.  But as this is a deprecated interface, we
52558 ** will not bother to check for that condition.
52559 **
52560 ** If the two statements contain a different number of bindings, then
52561 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
52562 ** SQLITE_OK is returned.
52563 */
52564 SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
52565   Vdbe *pFrom = (Vdbe*)pFromStmt;
52566   Vdbe *pTo = (Vdbe*)pToStmt;
52567   if( pFrom->nVar!=pTo->nVar ){
52568     return SQLITE_ERROR;
52569   }
52570   if( pTo->isPrepareV2 && pTo->expmask ){
52571     pTo->expired = 1;
52572   }
52573   if( pFrom->isPrepareV2 && pFrom->expmask ){
52574     pFrom->expired = 1;
52575   }
52576   return sqlite3TransferBindings(pFromStmt, pToStmt);
52577 }
52578 #endif
52579
52580 /*
52581 ** Return the sqlite3* database handle to which the prepared statement given
52582 ** in the argument belongs.  This is the same database handle that was
52583 ** the first argument to the sqlite3_prepare() that was used to create
52584 ** the statement in the first place.
52585 */
52586 SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
52587   return pStmt ? ((Vdbe*)pStmt)->db : 0;
52588 }
52589
52590 /*
52591 ** Return a pointer to the next prepared statement after pStmt associated
52592 ** with database connection pDb.  If pStmt is NULL, return the first
52593 ** prepared statement for the database connection.  Return NULL if there
52594 ** are no more.
52595 */
52596 SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
52597   sqlite3_stmt *pNext;
52598   sqlite3_mutex_enter(pDb->mutex);
52599   if( pStmt==0 ){
52600     pNext = (sqlite3_stmt*)pDb->pVdbe;
52601   }else{
52602     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
52603   }
52604   sqlite3_mutex_leave(pDb->mutex);
52605   return pNext;
52606 }
52607
52608 /*
52609 ** Return the value of a status counter for a prepared statement
52610 */
52611 SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
52612   Vdbe *pVdbe = (Vdbe*)pStmt;
52613   int v = pVdbe->aCounter[op-1];
52614   if( resetFlag ) pVdbe->aCounter[op-1] = 0;
52615   return v;
52616 }
52617
52618 /************** End of vdbeapi.c *********************************************/
52619 /************** Begin file vdbetrace.c ***************************************/
52620 /*
52621 ** 2009 November 25
52622 **
52623 ** The author disclaims copyright to this source code.  In place of
52624 ** a legal notice, here is a blessing:
52625 **
52626 **    May you do good and not evil.
52627 **    May you find forgiveness for yourself and forgive others.
52628 **    May you share freely, never taking more than you give.
52629 **
52630 *************************************************************************
52631 **
52632 ** This file contains code used to insert the values of host parameters
52633 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
52634 */
52635
52636 #ifndef SQLITE_OMIT_TRACE
52637
52638 /*
52639 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
52640 ** bytes in this text up to but excluding the first character in
52641 ** a host parameter.  If the text contains no host parameters, return
52642 ** the total number of bytes in the text.
52643 */
52644 static int findNextHostParameter(const char *zSql, int *pnToken){
52645   int tokenType;
52646   int nTotal = 0;
52647   int n;
52648
52649   *pnToken = 0;
52650   while( zSql[0] ){
52651     n = sqlite3GetToken((u8*)zSql, &tokenType);
52652     assert( n>0 && tokenType!=TK_ILLEGAL );
52653     if( tokenType==TK_VARIABLE ){
52654       *pnToken = n;
52655       break;
52656     }
52657     nTotal += n;
52658     zSql += n;
52659   }
52660   return nTotal;
52661 }
52662
52663 /*
52664 ** Return a pointer to a string in memory obtained form sqlite3DbMalloc() which
52665 ** holds a copy of zRawSql but with host parameters expanded to their
52666 ** current bindings.
52667 **
52668 ** The calling function is responsible for making sure the memory returned
52669 ** is eventually freed.
52670 **
52671 ** ALGORITHM:  Scan the input string looking for host parameters in any of
52672 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
52673 ** string literals, quoted identifier names, and comments.  For text forms,
52674 ** the host parameter index is found by scanning the perpared
52675 ** statement for the corresponding OP_Variable opcode.  Once the host
52676 ** parameter index is known, locate the value in p->aVar[].  Then render
52677 ** the value as a literal in place of the host parameter name.
52678 */
52679 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
52680   Vdbe *p,                 /* The prepared statement being evaluated */
52681   const char *zRawSql      /* Raw text of the SQL statement */
52682 ){
52683   sqlite3 *db;             /* The database connection */
52684   int idx = 0;             /* Index of a host parameter */
52685   int nextIndex = 1;       /* Index of next ? host parameter */
52686   int n;                   /* Length of a token prefix */
52687   int nToken;              /* Length of the parameter token */
52688   int i;                   /* Loop counter */
52689   Mem *pVar;               /* Value of a host parameter */
52690   StrAccum out;            /* Accumulate the output here */
52691   char zBase[100];         /* Initial working space */
52692
52693   db = p->db;
52694   sqlite3StrAccumInit(&out, zBase, sizeof(zBase), 
52695                       db->aLimit[SQLITE_LIMIT_LENGTH]);
52696   out.db = db;
52697   while( zRawSql[0] ){
52698     n = findNextHostParameter(zRawSql, &nToken);
52699     assert( n>0 );
52700     sqlite3StrAccumAppend(&out, zRawSql, n);
52701     zRawSql += n;
52702     assert( zRawSql[0] || nToken==0 );
52703     if( nToken==0 ) break;
52704     if( zRawSql[0]=='?' ){
52705       if( nToken>1 ){
52706         assert( sqlite3Isdigit(zRawSql[1]) );
52707         sqlite3GetInt32(&zRawSql[1], &idx);
52708       }else{
52709         idx = nextIndex;
52710       }
52711     }else{
52712       assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
52713       testcase( zRawSql[0]==':' );
52714       testcase( zRawSql[0]=='$' );
52715       testcase( zRawSql[0]=='@' );
52716       idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
52717       assert( idx>0 );
52718     }
52719     zRawSql += nToken;
52720     nextIndex = idx + 1;
52721     assert( idx>0 && idx<=p->nVar );
52722     pVar = &p->aVar[idx-1];
52723     if( pVar->flags & MEM_Null ){
52724       sqlite3StrAccumAppend(&out, "NULL", 4);
52725     }else if( pVar->flags & MEM_Int ){
52726       sqlite3XPrintf(&out, "%lld", pVar->u.i);
52727     }else if( pVar->flags & MEM_Real ){
52728       sqlite3XPrintf(&out, "%!.15g", pVar->r);
52729     }else if( pVar->flags & MEM_Str ){
52730 #ifndef SQLITE_OMIT_UTF16
52731       u8 enc = ENC(db);
52732       if( enc!=SQLITE_UTF8 ){
52733         Mem utf8;
52734         memset(&utf8, 0, sizeof(utf8));
52735         utf8.db = db;
52736         sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
52737         sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
52738         sqlite3XPrintf(&out, "'%.*q'", utf8.n, utf8.z);
52739         sqlite3VdbeMemRelease(&utf8);
52740       }else
52741 #endif
52742       {
52743         sqlite3XPrintf(&out, "'%.*q'", pVar->n, pVar->z);
52744       }
52745     }else if( pVar->flags & MEM_Zero ){
52746       sqlite3XPrintf(&out, "zeroblob(%d)", pVar->u.nZero);
52747     }else{
52748       assert( pVar->flags & MEM_Blob );
52749       sqlite3StrAccumAppend(&out, "x'", 2);
52750       for(i=0; i<pVar->n; i++){
52751         sqlite3XPrintf(&out, "%02x", pVar->z[i]&0xff);
52752       }
52753       sqlite3StrAccumAppend(&out, "'", 1);
52754     }
52755   }
52756   return sqlite3StrAccumFinish(&out);
52757 }
52758
52759 #endif /* #ifndef SQLITE_OMIT_TRACE */
52760
52761 /************** End of vdbetrace.c *******************************************/
52762 /************** Begin file vdbe.c ********************************************/
52763 /*
52764 ** 2001 September 15
52765 **
52766 ** The author disclaims copyright to this source code.  In place of
52767 ** a legal notice, here is a blessing:
52768 **
52769 **    May you do good and not evil.
52770 **    May you find forgiveness for yourself and forgive others.
52771 **    May you share freely, never taking more than you give.
52772 **
52773 *************************************************************************
52774 ** The code in this file implements execution method of the 
52775 ** Virtual Database Engine (VDBE).  A separate file ("vdbeaux.c")
52776 ** handles housekeeping details such as creating and deleting
52777 ** VDBE instances.  This file is solely interested in executing
52778 ** the VDBE program.
52779 **
52780 ** In the external interface, an "sqlite3_stmt*" is an opaque pointer
52781 ** to a VDBE.
52782 **
52783 ** The SQL parser generates a program which is then executed by
52784 ** the VDBE to do the work of the SQL statement.  VDBE programs are 
52785 ** similar in form to assembly language.  The program consists of
52786 ** a linear sequence of operations.  Each operation has an opcode 
52787 ** and 5 operands.  Operands P1, P2, and P3 are integers.  Operand P4 
52788 ** is a null-terminated string.  Operand P5 is an unsigned character.
52789 ** Few opcodes use all 5 operands.
52790 **
52791 ** Computation results are stored on a set of registers numbered beginning
52792 ** with 1 and going up to Vdbe.nMem.  Each register can store
52793 ** either an integer, a null-terminated string, a floating point
52794 ** number, or the SQL "NULL" value.  An implicit conversion from one
52795 ** type to the other occurs as necessary.
52796 ** 
52797 ** Most of the code in this file is taken up by the sqlite3VdbeExec()
52798 ** function which does the work of interpreting a VDBE program.
52799 ** But other routines are also provided to help in building up
52800 ** a program instruction by instruction.
52801 **
52802 ** Various scripts scan this source file in order to generate HTML
52803 ** documentation, headers files, or other derived files.  The formatting
52804 ** of the code in this file is, therefore, important.  See other comments
52805 ** in this file for details.  If in doubt, do not deviate from existing
52806 ** commenting and indentation practices when changing or adding code.
52807 */
52808
52809 /*
52810 ** The following global variable is incremented every time a cursor
52811 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
52812 ** procedures use this information to make sure that indices are
52813 ** working correctly.  This variable has no function other than to
52814 ** help verify the correct operation of the library.
52815 */
52816 #ifdef SQLITE_TEST
52817 SQLITE_API int sqlite3_search_count = 0;
52818 #endif
52819
52820 /*
52821 ** When this global variable is positive, it gets decremented once before
52822 ** each instruction in the VDBE.  When reaches zero, the u1.isInterrupted
52823 ** field of the sqlite3 structure is set in order to simulate and interrupt.
52824 **
52825 ** This facility is used for testing purposes only.  It does not function
52826 ** in an ordinary build.
52827 */
52828 #ifdef SQLITE_TEST
52829 SQLITE_API int sqlite3_interrupt_count = 0;
52830 #endif
52831
52832 /*
52833 ** The next global variable is incremented each type the OP_Sort opcode
52834 ** is executed.  The test procedures use this information to make sure that
52835 ** sorting is occurring or not occurring at appropriate times.   This variable
52836 ** has no function other than to help verify the correct operation of the
52837 ** library.
52838 */
52839 #ifdef SQLITE_TEST
52840 SQLITE_API int sqlite3_sort_count = 0;
52841 #endif
52842
52843 /*
52844 ** The next global variable records the size of the largest MEM_Blob
52845 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
52846 ** use this information to make sure that the zero-blob functionality
52847 ** is working correctly.   This variable has no function other than to
52848 ** help verify the correct operation of the library.
52849 */
52850 #ifdef SQLITE_TEST
52851 SQLITE_API int sqlite3_max_blobsize = 0;
52852 static void updateMaxBlobsize(Mem *p){
52853   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
52854     sqlite3_max_blobsize = p->n;
52855   }
52856 }
52857 #endif
52858
52859 /*
52860 ** The next global variable is incremented each type the OP_Found opcode
52861 ** is executed. This is used to test whether or not the foreign key
52862 ** operation implemented using OP_FkIsZero is working. This variable
52863 ** has no function other than to help verify the correct operation of the
52864 ** library.
52865 */
52866 #ifdef SQLITE_TEST
52867 SQLITE_API int sqlite3_found_count = 0;
52868 #endif
52869
52870 /*
52871 ** Test a register to see if it exceeds the current maximum blob size.
52872 ** If it does, record the new maximum blob size.
52873 */
52874 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
52875 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
52876 #else
52877 # define UPDATE_MAX_BLOBSIZE(P)
52878 #endif
52879
52880 /*
52881 ** Convert the given register into a string if it isn't one
52882 ** already. Return non-zero if a malloc() fails.
52883 */
52884 #define Stringify(P, enc) \
52885    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc)) \
52886      { goto no_mem; }
52887
52888 /*
52889 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
52890 ** a pointer to a dynamically allocated string where some other entity
52891 ** is responsible for deallocating that string.  Because the register
52892 ** does not control the string, it might be deleted without the register
52893 ** knowing it.
52894 **
52895 ** This routine converts an ephemeral string into a dynamically allocated
52896 ** string that the register itself controls.  In other words, it
52897 ** converts an MEM_Ephem string into an MEM_Dyn string.
52898 */
52899 #define Deephemeralize(P) \
52900    if( ((P)->flags&MEM_Ephem)!=0 \
52901        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
52902
52903 /*
52904 ** Call sqlite3VdbeMemExpandBlob() on the supplied value (type Mem*)
52905 ** P if required.
52906 */
52907 #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
52908
52909 /*
52910 ** Argument pMem points at a register that will be passed to a
52911 ** user-defined function or returned to the user as the result of a query.
52912 ** This routine sets the pMem->type variable used by the sqlite3_value_*() 
52913 ** routines.
52914 */
52915 SQLITE_PRIVATE void sqlite3VdbeMemStoreType(Mem *pMem){
52916   int flags = pMem->flags;
52917   if( flags & MEM_Null ){
52918     pMem->type = SQLITE_NULL;
52919   }
52920   else if( flags & MEM_Int ){
52921     pMem->type = SQLITE_INTEGER;
52922   }
52923   else if( flags & MEM_Real ){
52924     pMem->type = SQLITE_FLOAT;
52925   }
52926   else if( flags & MEM_Str ){
52927     pMem->type = SQLITE_TEXT;
52928   }else{
52929     pMem->type = SQLITE_BLOB;
52930   }
52931 }
52932
52933 /*
52934 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
52935 ** if we run out of memory.
52936 */
52937 static VdbeCursor *allocateCursor(
52938   Vdbe *p,              /* The virtual machine */
52939   int iCur,             /* Index of the new VdbeCursor */
52940   int nField,           /* Number of fields in the table or index */
52941   int iDb,              /* When database the cursor belongs to, or -1 */
52942   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
52943 ){
52944   /* Find the memory cell that will be used to store the blob of memory
52945   ** required for this VdbeCursor structure. It is convenient to use a 
52946   ** vdbe memory cell to manage the memory allocation required for a
52947   ** VdbeCursor structure for the following reasons:
52948   **
52949   **   * Sometimes cursor numbers are used for a couple of different
52950   **     purposes in a vdbe program. The different uses might require
52951   **     different sized allocations. Memory cells provide growable
52952   **     allocations.
52953   **
52954   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
52955   **     be freed lazily via the sqlite3_release_memory() API. This
52956   **     minimizes the number of malloc calls made by the system.
52957   **
52958   ** Memory cells for cursors are allocated at the top of the address
52959   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
52960   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
52961   */
52962   Mem *pMem = &p->aMem[p->nMem-iCur];
52963
52964   int nByte;
52965   VdbeCursor *pCx = 0;
52966   nByte = 
52967       ROUND8(sizeof(VdbeCursor)) + 
52968       (isBtreeCursor?sqlite3BtreeCursorSize():0) + 
52969       2*nField*sizeof(u32);
52970
52971   assert( iCur<p->nCursor );
52972   if( p->apCsr[iCur] ){
52973     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
52974     p->apCsr[iCur] = 0;
52975   }
52976   if( SQLITE_OK==sqlite3VdbeMemGrow(pMem, nByte, 0) ){
52977     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
52978     memset(pCx, 0, sizeof(VdbeCursor));
52979     pCx->iDb = iDb;
52980     pCx->nField = nField;
52981     if( nField ){
52982       pCx->aType = (u32 *)&pMem->z[ROUND8(sizeof(VdbeCursor))];
52983     }
52984     if( isBtreeCursor ){
52985       pCx->pCursor = (BtCursor*)
52986           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*nField*sizeof(u32)];
52987       sqlite3BtreeCursorZero(pCx->pCursor);
52988     }
52989   }
52990   return pCx;
52991 }
52992
52993 /*
52994 ** Try to convert a value into a numeric representation if we can
52995 ** do so without loss of information.  In other words, if the string
52996 ** looks like a number, convert it into a number.  If it does not
52997 ** look like a number, leave it alone.
52998 */
52999 static void applyNumericAffinity(Mem *pRec){
53000   if( (pRec->flags & (MEM_Real|MEM_Int))==0 ){
53001     int realnum;
53002     u8 enc = pRec->enc;
53003     sqlite3VdbeMemNulTerminate(pRec);
53004     if( (pRec->flags&MEM_Str) && sqlite3IsNumber(pRec->z, &realnum, enc) ){
53005       i64 value;
53006       char *zUtf8 = pRec->z;
53007 #ifndef SQLITE_OMIT_UTF16
53008       if( enc!=SQLITE_UTF8 ){
53009         assert( pRec->db );
53010         zUtf8 = sqlite3Utf16to8(pRec->db, pRec->z, pRec->n, enc);
53011         if( !zUtf8 ) return;
53012       }
53013 #endif
53014       if( !realnum && sqlite3Atoi64(zUtf8, &value) ){
53015         pRec->u.i = value;
53016         MemSetTypeFlag(pRec, MEM_Int);
53017       }else{
53018         sqlite3AtoF(zUtf8, &pRec->r);
53019         MemSetTypeFlag(pRec, MEM_Real);
53020       }
53021 #ifndef SQLITE_OMIT_UTF16
53022       if( enc!=SQLITE_UTF8 ){
53023         sqlite3DbFree(pRec->db, zUtf8);
53024       }
53025 #endif
53026     }
53027   }
53028 }
53029
53030 /*
53031 ** Processing is determine by the affinity parameter:
53032 **
53033 ** SQLITE_AFF_INTEGER:
53034 ** SQLITE_AFF_REAL:
53035 ** SQLITE_AFF_NUMERIC:
53036 **    Try to convert pRec to an integer representation or a 
53037 **    floating-point representation if an integer representation
53038 **    is not possible.  Note that the integer representation is
53039 **    always preferred, even if the affinity is REAL, because
53040 **    an integer representation is more space efficient on disk.
53041 **
53042 ** SQLITE_AFF_TEXT:
53043 **    Convert pRec to a text representation.
53044 **
53045 ** SQLITE_AFF_NONE:
53046 **    No-op.  pRec is unchanged.
53047 */
53048 static void applyAffinity(
53049   Mem *pRec,          /* The value to apply affinity to */
53050   char affinity,      /* The affinity to be applied */
53051   u8 enc              /* Use this text encoding */
53052 ){
53053   if( affinity==SQLITE_AFF_TEXT ){
53054     /* Only attempt the conversion to TEXT if there is an integer or real
53055     ** representation (blob and NULL do not get converted) but no string
53056     ** representation.
53057     */
53058     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
53059       sqlite3VdbeMemStringify(pRec, enc);
53060     }
53061     pRec->flags &= ~(MEM_Real|MEM_Int);
53062   }else if( affinity!=SQLITE_AFF_NONE ){
53063     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
53064              || affinity==SQLITE_AFF_NUMERIC );
53065     applyNumericAffinity(pRec);
53066     if( pRec->flags & MEM_Real ){
53067       sqlite3VdbeIntegerAffinity(pRec);
53068     }
53069   }
53070 }
53071
53072 /*
53073 ** Try to convert the type of a function argument or a result column
53074 ** into a numeric representation.  Use either INTEGER or REAL whichever
53075 ** is appropriate.  But only do the conversion if it is possible without
53076 ** loss of information and return the revised type of the argument.
53077 **
53078 ** This is an EXPERIMENTAL api and is subject to change or removal.
53079 */
53080 SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
53081   Mem *pMem = (Mem*)pVal;
53082   applyNumericAffinity(pMem);
53083   sqlite3VdbeMemStoreType(pMem);
53084   return pMem->type;
53085 }
53086
53087 /*
53088 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
53089 ** not the internal Mem* type.
53090 */
53091 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
53092   sqlite3_value *pVal, 
53093   u8 affinity, 
53094   u8 enc
53095 ){
53096   applyAffinity((Mem *)pVal, affinity, enc);
53097 }
53098
53099 #ifdef SQLITE_DEBUG
53100 /*
53101 ** Write a nice string representation of the contents of cell pMem
53102 ** into buffer zBuf, length nBuf.
53103 */
53104 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
53105   char *zCsr = zBuf;
53106   int f = pMem->flags;
53107
53108   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
53109
53110   if( f&MEM_Blob ){
53111     int i;
53112     char c;
53113     if( f & MEM_Dyn ){
53114       c = 'z';
53115       assert( (f & (MEM_Static|MEM_Ephem))==0 );
53116     }else if( f & MEM_Static ){
53117       c = 't';
53118       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
53119     }else if( f & MEM_Ephem ){
53120       c = 'e';
53121       assert( (f & (MEM_Static|MEM_Dyn))==0 );
53122     }else{
53123       c = 's';
53124     }
53125
53126     sqlite3_snprintf(100, zCsr, "%c", c);
53127     zCsr += sqlite3Strlen30(zCsr);
53128     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
53129     zCsr += sqlite3Strlen30(zCsr);
53130     for(i=0; i<16 && i<pMem->n; i++){
53131       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
53132       zCsr += sqlite3Strlen30(zCsr);
53133     }
53134     for(i=0; i<16 && i<pMem->n; i++){
53135       char z = pMem->z[i];
53136       if( z<32 || z>126 ) *zCsr++ = '.';
53137       else *zCsr++ = z;
53138     }
53139
53140     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
53141     zCsr += sqlite3Strlen30(zCsr);
53142     if( f & MEM_Zero ){
53143       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
53144       zCsr += sqlite3Strlen30(zCsr);
53145     }
53146     *zCsr = '\0';
53147   }else if( f & MEM_Str ){
53148     int j, k;
53149     zBuf[0] = ' ';
53150     if( f & MEM_Dyn ){
53151       zBuf[1] = 'z';
53152       assert( (f & (MEM_Static|MEM_Ephem))==0 );
53153     }else if( f & MEM_Static ){
53154       zBuf[1] = 't';
53155       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
53156     }else if( f & MEM_Ephem ){
53157       zBuf[1] = 'e';
53158       assert( (f & (MEM_Static|MEM_Dyn))==0 );
53159     }else{
53160       zBuf[1] = 's';
53161     }
53162     k = 2;
53163     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
53164     k += sqlite3Strlen30(&zBuf[k]);
53165     zBuf[k++] = '[';
53166     for(j=0; j<15 && j<pMem->n; j++){
53167       u8 c = pMem->z[j];
53168       if( c>=0x20 && c<0x7f ){
53169         zBuf[k++] = c;
53170       }else{
53171         zBuf[k++] = '.';
53172       }
53173     }
53174     zBuf[k++] = ']';
53175     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
53176     k += sqlite3Strlen30(&zBuf[k]);
53177     zBuf[k++] = 0;
53178   }
53179 }
53180 #endif
53181
53182 #ifdef SQLITE_DEBUG
53183 /*
53184 ** Print the value of a register for tracing purposes:
53185 */
53186 static void memTracePrint(FILE *out, Mem *p){
53187   if( p->flags & MEM_Null ){
53188     fprintf(out, " NULL");
53189   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
53190     fprintf(out, " si:%lld", p->u.i);
53191   }else if( p->flags & MEM_Int ){
53192     fprintf(out, " i:%lld", p->u.i);
53193 #ifndef SQLITE_OMIT_FLOATING_POINT
53194   }else if( p->flags & MEM_Real ){
53195     fprintf(out, " r:%g", p->r);
53196 #endif
53197   }else if( p->flags & MEM_RowSet ){
53198     fprintf(out, " (rowset)");
53199   }else{
53200     char zBuf[200];
53201     sqlite3VdbeMemPrettyPrint(p, zBuf);
53202     fprintf(out, " ");
53203     fprintf(out, "%s", zBuf);
53204   }
53205 }
53206 static void registerTrace(FILE *out, int iReg, Mem *p){
53207   fprintf(out, "REG[%d] = ", iReg);
53208   memTracePrint(out, p);
53209   fprintf(out, "\n");
53210 }
53211 #endif
53212
53213 #ifdef SQLITE_DEBUG
53214 #  define REGISTER_TRACE(R,M) if(p->trace)registerTrace(p->trace,R,M)
53215 #else
53216 #  define REGISTER_TRACE(R,M)
53217 #endif
53218
53219
53220 #ifdef VDBE_PROFILE
53221
53222 /* 
53223 ** hwtime.h contains inline assembler code for implementing 
53224 ** high-performance timing routines.
53225 */
53226 /************** Include hwtime.h in the middle of vdbe.c *********************/
53227 /************** Begin file hwtime.h ******************************************/
53228 /*
53229 ** 2008 May 27
53230 **
53231 ** The author disclaims copyright to this source code.  In place of
53232 ** a legal notice, here is a blessing:
53233 **
53234 **    May you do good and not evil.
53235 **    May you find forgiveness for yourself and forgive others.
53236 **    May you share freely, never taking more than you give.
53237 **
53238 ******************************************************************************
53239 **
53240 ** This file contains inline asm code for retrieving "high-performance"
53241 ** counters for x86 class CPUs.
53242 */
53243 #ifndef _HWTIME_H_
53244 #define _HWTIME_H_
53245
53246 /*
53247 ** The following routine only works on pentium-class (or newer) processors.
53248 ** It uses the RDTSC opcode to read the cycle count value out of the
53249 ** processor and returns that value.  This can be used for high-res
53250 ** profiling.
53251 */
53252 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
53253       (defined(i386) || defined(__i386__) || defined(_M_IX86))
53254
53255   #if defined(__GNUC__)
53256
53257   __inline__ sqlite_uint64 sqlite3Hwtime(void){
53258      unsigned int lo, hi;
53259      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
53260      return (sqlite_uint64)hi << 32 | lo;
53261   }
53262
53263   #elif defined(_MSC_VER)
53264
53265   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
53266      __asm {
53267         rdtsc
53268         ret       ; return value at EDX:EAX
53269      }
53270   }
53271
53272   #endif
53273
53274 #elif (defined(__GNUC__) && defined(__x86_64__))
53275
53276   __inline__ sqlite_uint64 sqlite3Hwtime(void){
53277       unsigned long val;
53278       __asm__ __volatile__ ("rdtsc" : "=A" (val));
53279       return val;
53280   }
53281  
53282 #elif (defined(__GNUC__) && defined(__ppc__))
53283
53284   __inline__ sqlite_uint64 sqlite3Hwtime(void){
53285       unsigned long long retval;
53286       unsigned long junk;
53287       __asm__ __volatile__ ("\n\
53288           1:      mftbu   %1\n\
53289                   mftb    %L0\n\
53290                   mftbu   %0\n\
53291                   cmpw    %0,%1\n\
53292                   bne     1b"
53293                   : "=r" (retval), "=r" (junk));
53294       return retval;
53295   }
53296
53297 #else
53298
53299   #error Need implementation of sqlite3Hwtime() for your platform.
53300
53301   /*
53302   ** To compile without implementing sqlite3Hwtime() for your platform,
53303   ** you can remove the above #error and use the following
53304   ** stub function.  You will lose timing support for many
53305   ** of the debugging and testing utilities, but it should at
53306   ** least compile and run.
53307   */
53308 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
53309
53310 #endif
53311
53312 #endif /* !defined(_HWTIME_H_) */
53313
53314 /************** End of hwtime.h **********************************************/
53315 /************** Continuing where we left off in vdbe.c ***********************/
53316
53317 #endif
53318
53319 /*
53320 ** The CHECK_FOR_INTERRUPT macro defined here looks to see if the
53321 ** sqlite3_interrupt() routine has been called.  If it has been, then
53322 ** processing of the VDBE program is interrupted.
53323 **
53324 ** This macro added to every instruction that does a jump in order to
53325 ** implement a loop.  This test used to be on every single instruction,
53326 ** but that meant we more testing that we needed.  By only testing the
53327 ** flag on jump instructions, we get a (small) speed improvement.
53328 */
53329 #define CHECK_FOR_INTERRUPT \
53330    if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
53331
53332 #ifdef SQLITE_DEBUG
53333 static int fileExists(sqlite3 *db, const char *zFile){
53334   int res = 0;
53335   int rc = SQLITE_OK;
53336 #ifdef SQLITE_TEST
53337   /* If we are currently testing IO errors, then do not call OsAccess() to
53338   ** test for the presence of zFile. This is because any IO error that
53339   ** occurs here will not be reported, causing the test to fail.
53340   */
53341   extern int sqlite3_io_error_pending;
53342   if( sqlite3_io_error_pending<=0 )
53343 #endif
53344     rc = sqlite3OsAccess(db->pVfs, zFile, SQLITE_ACCESS_EXISTS, &res);
53345   return (res && rc==SQLITE_OK);
53346 }
53347 #endif
53348
53349 #ifndef NDEBUG
53350 /*
53351 ** This function is only called from within an assert() expression. It
53352 ** checks that the sqlite3.nTransaction variable is correctly set to
53353 ** the number of non-transaction savepoints currently in the 
53354 ** linked list starting at sqlite3.pSavepoint.
53355 ** 
53356 ** Usage:
53357 **
53358 **     assert( checkSavepointCount(db) );
53359 */
53360 static int checkSavepointCount(sqlite3 *db){
53361   int n = 0;
53362   Savepoint *p;
53363   for(p=db->pSavepoint; p; p=p->pNext) n++;
53364   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
53365   return 1;
53366 }
53367 #endif
53368
53369 /*
53370 ** Execute as much of a VDBE program as we can then return.
53371 **
53372 ** sqlite3VdbeMakeReady() must be called before this routine in order to
53373 ** close the program with a final OP_Halt and to set up the callbacks
53374 ** and the error message pointer.
53375 **
53376 ** Whenever a row or result data is available, this routine will either
53377 ** invoke the result callback (if there is one) or return with
53378 ** SQLITE_ROW.
53379 **
53380 ** If an attempt is made to open a locked database, then this routine
53381 ** will either invoke the busy callback (if there is one) or it will
53382 ** return SQLITE_BUSY.
53383 **
53384 ** If an error occurs, an error message is written to memory obtained
53385 ** from sqlite3_malloc() and p->zErrMsg is made to point to that memory.
53386 ** The error code is stored in p->rc and this routine returns SQLITE_ERROR.
53387 **
53388 ** If the callback ever returns non-zero, then the program exits
53389 ** immediately.  There will be no error message but the p->rc field is
53390 ** set to SQLITE_ABORT and this routine will return SQLITE_ERROR.
53391 **
53392 ** A memory allocation error causes p->rc to be set to SQLITE_NOMEM and this
53393 ** routine to return SQLITE_ERROR.
53394 **
53395 ** Other fatal errors return SQLITE_ERROR.
53396 **
53397 ** After this routine has finished, sqlite3VdbeFinalize() should be
53398 ** used to clean up the mess that was left behind.
53399 */
53400 SQLITE_PRIVATE int sqlite3VdbeExec(
53401   Vdbe *p                    /* The VDBE */
53402 ){
53403   int pc=0;                  /* The program counter */
53404   Op *aOp = p->aOp;          /* Copy of p->aOp */
53405   Op *pOp;                   /* Current operation */
53406   int rc = SQLITE_OK;        /* Value to return */
53407   sqlite3 *db = p->db;       /* The database */
53408   u8 resetSchemaOnFault = 0; /* Reset schema after an error if true */
53409   u8 encoding = ENC(db);     /* The database encoding */
53410 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
53411   int checkProgress;         /* True if progress callbacks are enabled */
53412   int nProgressOps = 0;      /* Opcodes executed since progress callback. */
53413 #endif
53414   Mem *aMem = p->aMem;       /* Copy of p->aMem */
53415   Mem *pIn1 = 0;             /* 1st input operand */
53416   Mem *pIn2 = 0;             /* 2nd input operand */
53417   Mem *pIn3 = 0;             /* 3rd input operand */
53418   Mem *pOut = 0;             /* Output operand */
53419   int iCompare = 0;          /* Result of last OP_Compare operation */
53420   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
53421 #ifdef VDBE_PROFILE
53422   u64 start;                 /* CPU clock count at start of opcode */
53423   int origPc;                /* Program counter at start of opcode */
53424 #endif
53425   /********************************************************************
53426   ** Automatically generated code
53427   **
53428   ** The following union is automatically generated by the
53429   ** vdbe-compress.tcl script.  The purpose of this union is to
53430   ** reduce the amount of stack space required by this function.
53431   ** See comments in the vdbe-compress.tcl script for details.
53432   */
53433   union vdbeExecUnion {
53434     struct OP_Yield_stack_vars {
53435       int pcDest;
53436     } aa;
53437     struct OP_Variable_stack_vars {
53438       int p1;          /* Variable to copy from */
53439       int p2;          /* Register to copy to */
53440       int n;           /* Number of values left to copy */
53441       Mem *pVar;       /* Value being transferred */
53442     } ab;
53443     struct OP_Move_stack_vars {
53444       char *zMalloc;   /* Holding variable for allocated memory */
53445       int n;           /* Number of registers left to copy */
53446       int p1;          /* Register to copy from */
53447       int p2;          /* Register to copy to */
53448     } ac;
53449     struct OP_ResultRow_stack_vars {
53450       Mem *pMem;
53451       int i;
53452     } ad;
53453     struct OP_Concat_stack_vars {
53454       i64 nByte;
53455     } ae;
53456     struct OP_Remainder_stack_vars {
53457       int flags;      /* Combined MEM_* flags from both inputs */
53458       i64 iA;         /* Integer value of left operand */
53459       i64 iB;         /* Integer value of right operand */
53460       double rA;      /* Real value of left operand */
53461       double rB;      /* Real value of right operand */
53462     } af;
53463     struct OP_Function_stack_vars {
53464       int i;
53465       Mem *pArg;
53466       sqlite3_context ctx;
53467       sqlite3_value **apVal;
53468       int n;
53469     } ag;
53470     struct OP_ShiftRight_stack_vars {
53471       i64 a;
53472       i64 b;
53473     } ah;
53474     struct OP_Ge_stack_vars {
53475       int res;            /* Result of the comparison of pIn1 against pIn3 */
53476       char affinity;      /* Affinity to use for comparison */
53477       u16 flags1;         /* Copy of initial value of pIn1->flags */
53478       u16 flags3;         /* Copy of initial value of pIn3->flags */
53479     } ai;
53480     struct OP_Compare_stack_vars {
53481       int n;
53482       int i;
53483       int p1;
53484       int p2;
53485       const KeyInfo *pKeyInfo;
53486       int idx;
53487       CollSeq *pColl;    /* Collating sequence to use on this term */
53488       int bRev;          /* True for DESCENDING sort order */
53489     } aj;
53490     struct OP_Or_stack_vars {
53491       int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
53492       int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
53493     } ak;
53494     struct OP_IfNot_stack_vars {
53495       int c;
53496     } al;
53497     struct OP_Column_stack_vars {
53498       u32 payloadSize;   /* Number of bytes in the record */
53499       i64 payloadSize64; /* Number of bytes in the record */
53500       int p1;            /* P1 value of the opcode */
53501       int p2;            /* column number to retrieve */
53502       VdbeCursor *pC;    /* The VDBE cursor */
53503       char *zRec;        /* Pointer to complete record-data */
53504       BtCursor *pCrsr;   /* The BTree cursor */
53505       u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
53506       u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
53507       int nField;        /* number of fields in the record */
53508       int len;           /* The length of the serialized data for the column */
53509       int i;             /* Loop counter */
53510       char *zData;       /* Part of the record being decoded */
53511       Mem *pDest;        /* Where to write the extracted value */
53512       Mem sMem;          /* For storing the record being decoded */
53513       u8 *zIdx;          /* Index into header */
53514       u8 *zEndHdr;       /* Pointer to first byte after the header */
53515       u32 offset;        /* Offset into the data */
53516       u32 szField;       /* Number of bytes in the content of a field */
53517       int szHdr;         /* Size of the header size field at start of record */
53518       int avail;         /* Number of bytes of available data */
53519       Mem *pReg;         /* PseudoTable input register */
53520     } am;
53521     struct OP_Affinity_stack_vars {
53522       const char *zAffinity;   /* The affinity to be applied */
53523       char cAff;               /* A single character of affinity */
53524     } an;
53525     struct OP_MakeRecord_stack_vars {
53526       u8 *zNewRecord;        /* A buffer to hold the data for the new record */
53527       Mem *pRec;             /* The new record */
53528       u64 nData;             /* Number of bytes of data space */
53529       int nHdr;              /* Number of bytes of header space */
53530       i64 nByte;             /* Data space required for this record */
53531       int nZero;             /* Number of zero bytes at the end of the record */
53532       int nVarint;           /* Number of bytes in a varint */
53533       u32 serial_type;       /* Type field */
53534       Mem *pData0;           /* First field to be combined into the record */
53535       Mem *pLast;            /* Last field of the record */
53536       int nField;            /* Number of fields in the record */
53537       char *zAffinity;       /* The affinity string for the record */
53538       int file_format;       /* File format to use for encoding */
53539       int i;                 /* Space used in zNewRecord[] */
53540       int len;               /* Length of a field */
53541     } ao;
53542     struct OP_Count_stack_vars {
53543       i64 nEntry;
53544       BtCursor *pCrsr;
53545     } ap;
53546     struct OP_Savepoint_stack_vars {
53547       int p1;                         /* Value of P1 operand */
53548       char *zName;                    /* Name of savepoint */
53549       int nName;
53550       Savepoint *pNew;
53551       Savepoint *pSavepoint;
53552       Savepoint *pTmp;
53553       int iSavepoint;
53554       int ii;
53555     } aq;
53556     struct OP_AutoCommit_stack_vars {
53557       int desiredAutoCommit;
53558       int iRollback;
53559       int turnOnAC;
53560     } ar;
53561     struct OP_Transaction_stack_vars {
53562       Btree *pBt;
53563     } as;
53564     struct OP_ReadCookie_stack_vars {
53565       int iMeta;
53566       int iDb;
53567       int iCookie;
53568     } at;
53569     struct OP_SetCookie_stack_vars {
53570       Db *pDb;
53571     } au;
53572     struct OP_VerifyCookie_stack_vars {
53573       int iMeta;
53574       Btree *pBt;
53575     } av;
53576     struct OP_OpenWrite_stack_vars {
53577       int nField;
53578       KeyInfo *pKeyInfo;
53579       int p2;
53580       int iDb;
53581       int wrFlag;
53582       Btree *pX;
53583       VdbeCursor *pCur;
53584       Db *pDb;
53585     } aw;
53586     struct OP_OpenEphemeral_stack_vars {
53587       VdbeCursor *pCx;
53588     } ax;
53589     struct OP_OpenPseudo_stack_vars {
53590       VdbeCursor *pCx;
53591     } ay;
53592     struct OP_SeekGt_stack_vars {
53593       int res;
53594       int oc;
53595       VdbeCursor *pC;
53596       UnpackedRecord r;
53597       int nField;
53598       i64 iKey;      /* The rowid we are to seek to */
53599     } az;
53600     struct OP_Seek_stack_vars {
53601       VdbeCursor *pC;
53602     } ba;
53603     struct OP_Found_stack_vars {
53604       int alreadyExists;
53605       VdbeCursor *pC;
53606       int res;
53607       UnpackedRecord *pIdxKey;
53608       UnpackedRecord r;
53609       char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
53610     } bb;
53611     struct OP_IsUnique_stack_vars {
53612       u16 ii;
53613       VdbeCursor *pCx;
53614       BtCursor *pCrsr;
53615       u16 nField;
53616       Mem *aMx;
53617       UnpackedRecord r;                  /* B-Tree index search key */
53618       i64 R;                             /* Rowid stored in register P3 */
53619     } bc;
53620     struct OP_NotExists_stack_vars {
53621       VdbeCursor *pC;
53622       BtCursor *pCrsr;
53623       int res;
53624       u64 iKey;
53625     } bd;
53626     struct OP_NewRowid_stack_vars {
53627       i64 v;                 /* The new rowid */
53628       VdbeCursor *pC;        /* Cursor of table to get the new rowid */
53629       int res;               /* Result of an sqlite3BtreeLast() */
53630       int cnt;               /* Counter to limit the number of searches */
53631       Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
53632       VdbeFrame *pFrame;     /* Root frame of VDBE */
53633     } be;
53634     struct OP_InsertInt_stack_vars {
53635       Mem *pData;       /* MEM cell holding data for the record to be inserted */
53636       Mem *pKey;        /* MEM cell holding key  for the record */
53637       i64 iKey;         /* The integer ROWID or key for the record to be inserted */
53638       VdbeCursor *pC;   /* Cursor to table into which insert is written */
53639       int nZero;        /* Number of zero-bytes to append */
53640       int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
53641       const char *zDb;  /* database name - used by the update hook */
53642       const char *zTbl; /* Table name - used by the opdate hook */
53643       int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
53644     } bf;
53645     struct OP_Delete_stack_vars {
53646       i64 iKey;
53647       VdbeCursor *pC;
53648     } bg;
53649     struct OP_RowData_stack_vars {
53650       VdbeCursor *pC;
53651       BtCursor *pCrsr;
53652       u32 n;
53653       i64 n64;
53654     } bh;
53655     struct OP_Rowid_stack_vars {
53656       VdbeCursor *pC;
53657       i64 v;
53658       sqlite3_vtab *pVtab;
53659       const sqlite3_module *pModule;
53660     } bi;
53661     struct OP_NullRow_stack_vars {
53662       VdbeCursor *pC;
53663     } bj;
53664     struct OP_Last_stack_vars {
53665       VdbeCursor *pC;
53666       BtCursor *pCrsr;
53667       int res;
53668     } bk;
53669     struct OP_Rewind_stack_vars {
53670       VdbeCursor *pC;
53671       BtCursor *pCrsr;
53672       int res;
53673     } bl;
53674     struct OP_Next_stack_vars {
53675       VdbeCursor *pC;
53676       BtCursor *pCrsr;
53677       int res;
53678     } bm;
53679     struct OP_IdxInsert_stack_vars {
53680       VdbeCursor *pC;
53681       BtCursor *pCrsr;
53682       int nKey;
53683       const char *zKey;
53684     } bn;
53685     struct OP_IdxDelete_stack_vars {
53686       VdbeCursor *pC;
53687       BtCursor *pCrsr;
53688       int res;
53689       UnpackedRecord r;
53690     } bo;
53691     struct OP_IdxRowid_stack_vars {
53692       BtCursor *pCrsr;
53693       VdbeCursor *pC;
53694       i64 rowid;
53695     } bp;
53696     struct OP_IdxGE_stack_vars {
53697       VdbeCursor *pC;
53698       int res;
53699       UnpackedRecord r;
53700     } bq;
53701     struct OP_Destroy_stack_vars {
53702       int iMoved;
53703       int iCnt;
53704       Vdbe *pVdbe;
53705       int iDb;
53706     } br;
53707     struct OP_Clear_stack_vars {
53708       int nChange;
53709     } bs;
53710     struct OP_CreateTable_stack_vars {
53711       int pgno;
53712       int flags;
53713       Db *pDb;
53714     } bt;
53715     struct OP_ParseSchema_stack_vars {
53716       int iDb;
53717       const char *zMaster;
53718       char *zSql;
53719       InitData initData;
53720     } bu;
53721     struct OP_IntegrityCk_stack_vars {
53722       int nRoot;      /* Number of tables to check.  (Number of root pages.) */
53723       int *aRoot;     /* Array of rootpage numbers for tables to be checked */
53724       int j;          /* Loop counter */
53725       int nErr;       /* Number of errors reported */
53726       char *z;        /* Text of the error report */
53727       Mem *pnErr;     /* Register keeping track of errors remaining */
53728     } bv;
53729     struct OP_RowSetRead_stack_vars {
53730       i64 val;
53731     } bw;
53732     struct OP_RowSetTest_stack_vars {
53733       int iSet;
53734       int exists;
53735     } bx;
53736     struct OP_Program_stack_vars {
53737       int nMem;               /* Number of memory registers for sub-program */
53738       int nByte;              /* Bytes of runtime space required for sub-program */
53739       Mem *pRt;               /* Register to allocate runtime space */
53740       Mem *pMem;              /* Used to iterate through memory cells */
53741       Mem *pEnd;              /* Last memory cell in new array */
53742       VdbeFrame *pFrame;      /* New vdbe frame to execute in */
53743       SubProgram *pProgram;   /* Sub-program to execute */
53744       void *t;                /* Token identifying trigger */
53745     } by;
53746     struct OP_Param_stack_vars {
53747       VdbeFrame *pFrame;
53748       Mem *pIn;
53749     } bz;
53750     struct OP_MemMax_stack_vars {
53751       Mem *pIn1;
53752       VdbeFrame *pFrame;
53753     } ca;
53754     struct OP_AggStep_stack_vars {
53755       int n;
53756       int i;
53757       Mem *pMem;
53758       Mem *pRec;
53759       sqlite3_context ctx;
53760       sqlite3_value **apVal;
53761     } cb;
53762     struct OP_AggFinal_stack_vars {
53763       Mem *pMem;
53764     } cc;
53765     struct OP_IncrVacuum_stack_vars {
53766       Btree *pBt;
53767     } cd;
53768     struct OP_VBegin_stack_vars {
53769       VTable *pVTab;
53770     } ce;
53771     struct OP_VOpen_stack_vars {
53772       VdbeCursor *pCur;
53773       sqlite3_vtab_cursor *pVtabCursor;
53774       sqlite3_vtab *pVtab;
53775       sqlite3_module *pModule;
53776     } cf;
53777     struct OP_VFilter_stack_vars {
53778       int nArg;
53779       int iQuery;
53780       const sqlite3_module *pModule;
53781       Mem *pQuery;
53782       Mem *pArgc;
53783       sqlite3_vtab_cursor *pVtabCursor;
53784       sqlite3_vtab *pVtab;
53785       VdbeCursor *pCur;
53786       int res;
53787       int i;
53788       Mem **apArg;
53789     } cg;
53790     struct OP_VColumn_stack_vars {
53791       sqlite3_vtab *pVtab;
53792       const sqlite3_module *pModule;
53793       Mem *pDest;
53794       sqlite3_context sContext;
53795     } ch;
53796     struct OP_VNext_stack_vars {
53797       sqlite3_vtab *pVtab;
53798       const sqlite3_module *pModule;
53799       int res;
53800       VdbeCursor *pCur;
53801     } ci;
53802     struct OP_VRename_stack_vars {
53803       sqlite3_vtab *pVtab;
53804       Mem *pName;
53805     } cj;
53806     struct OP_VUpdate_stack_vars {
53807       sqlite3_vtab *pVtab;
53808       sqlite3_module *pModule;
53809       int nArg;
53810       int i;
53811       sqlite_int64 rowid;
53812       Mem **apArg;
53813       Mem *pX;
53814     } ck;
53815     struct OP_Pagecount_stack_vars {
53816       int p1;
53817       int nPage;
53818       Pager *pPager;
53819     } cl;
53820     struct OP_Trace_stack_vars {
53821       char *zTrace;
53822     } cm;
53823   } u;
53824   /* End automatically generated code
53825   ********************************************************************/
53826
53827   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
53828   sqlite3VdbeMutexArrayEnter(p);
53829   if( p->rc==SQLITE_NOMEM ){
53830     /* This happens if a malloc() inside a call to sqlite3_column_text() or
53831     ** sqlite3_column_text16() failed.  */
53832     goto no_mem;
53833   }
53834   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
53835   p->rc = SQLITE_OK;
53836   assert( p->explain==0 );
53837   p->pResultSet = 0;
53838   db->busyHandler.nBusy = 0;
53839   CHECK_FOR_INTERRUPT;
53840   sqlite3VdbeIOTraceSql(p);
53841 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
53842   checkProgress = db->xProgress!=0;
53843 #endif
53844 #ifdef SQLITE_DEBUG
53845   sqlite3BeginBenignMalloc();
53846   if( p->pc==0 
53847    && ((p->db->flags & SQLITE_VdbeListing) || fileExists(db, "vdbe_explain"))
53848   ){
53849     int i;
53850     printf("VDBE Program Listing:\n");
53851     sqlite3VdbePrintSql(p);
53852     for(i=0; i<p->nOp; i++){
53853       sqlite3VdbePrintOp(stdout, i, &aOp[i]);
53854     }
53855   }
53856   if( fileExists(db, "vdbe_trace") ){
53857     p->trace = stdout;
53858   }
53859   sqlite3EndBenignMalloc();
53860 #endif
53861   for(pc=p->pc; rc==SQLITE_OK; pc++){
53862     assert( pc>=0 && pc<p->nOp );
53863     if( db->mallocFailed ) goto no_mem;
53864 #ifdef VDBE_PROFILE
53865     origPc = pc;
53866     start = sqlite3Hwtime();
53867 #endif
53868     pOp = &aOp[pc];
53869
53870     /* Only allow tracing if SQLITE_DEBUG is defined.
53871     */
53872 #ifdef SQLITE_DEBUG
53873     if( p->trace ){
53874       if( pc==0 ){
53875         printf("VDBE Execution Trace:\n");
53876         sqlite3VdbePrintSql(p);
53877       }
53878       sqlite3VdbePrintOp(p->trace, pc, pOp);
53879     }
53880     if( p->trace==0 && pc==0 ){
53881       sqlite3BeginBenignMalloc();
53882       if( fileExists(db, "vdbe_sqltrace") ){
53883         sqlite3VdbePrintSql(p);
53884       }
53885       sqlite3EndBenignMalloc();
53886     }
53887 #endif
53888       
53889
53890     /* Check to see if we need to simulate an interrupt.  This only happens
53891     ** if we have a special test build.
53892     */
53893 #ifdef SQLITE_TEST
53894     if( sqlite3_interrupt_count>0 ){
53895       sqlite3_interrupt_count--;
53896       if( sqlite3_interrupt_count==0 ){
53897         sqlite3_interrupt(db);
53898       }
53899     }
53900 #endif
53901
53902 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
53903     /* Call the progress callback if it is configured and the required number
53904     ** of VDBE ops have been executed (either since this invocation of
53905     ** sqlite3VdbeExec() or since last time the progress callback was called).
53906     ** If the progress callback returns non-zero, exit the virtual machine with
53907     ** a return code SQLITE_ABORT.
53908     */
53909     if( checkProgress ){
53910       if( db->nProgressOps==nProgressOps ){
53911         int prc;
53912         prc = db->xProgress(db->pProgressArg);
53913         if( prc!=0 ){
53914           rc = SQLITE_INTERRUPT;
53915           goto vdbe_error_halt;
53916         }
53917         nProgressOps = 0;
53918       }
53919       nProgressOps++;
53920     }
53921 #endif
53922
53923     /* On any opcode with the "out2-prerelase" tag, free any
53924     ** external allocations out of mem[p2] and set mem[p2] to be
53925     ** an undefined integer.  Opcodes will either fill in the integer
53926     ** value or convert mem[p2] to a different type.
53927     */
53928     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
53929     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
53930       assert( pOp->p2>0 );
53931       assert( pOp->p2<=p->nMem );
53932       pOut = &aMem[pOp->p2];
53933       sqlite3VdbeMemReleaseExternal(pOut);
53934       pOut->flags = MEM_Int;
53935     }
53936
53937     /* Sanity checking on other operands */
53938 #ifdef SQLITE_DEBUG
53939     if( (pOp->opflags & OPFLG_IN1)!=0 ){
53940       assert( pOp->p1>0 );
53941       assert( pOp->p1<=p->nMem );
53942       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
53943     }
53944     if( (pOp->opflags & OPFLG_IN2)!=0 ){
53945       assert( pOp->p2>0 );
53946       assert( pOp->p2<=p->nMem );
53947       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
53948     }
53949     if( (pOp->opflags & OPFLG_IN3)!=0 ){
53950       assert( pOp->p3>0 );
53951       assert( pOp->p3<=p->nMem );
53952       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
53953     }
53954     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
53955       assert( pOp->p2>0 );
53956       assert( pOp->p2<=p->nMem );
53957     }
53958     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
53959       assert( pOp->p3>0 );
53960       assert( pOp->p3<=p->nMem );
53961     }
53962 #endif
53963   
53964     switch( pOp->opcode ){
53965
53966 /*****************************************************************************
53967 ** What follows is a massive switch statement where each case implements a
53968 ** separate instruction in the virtual machine.  If we follow the usual
53969 ** indentation conventions, each case should be indented by 6 spaces.  But
53970 ** that is a lot of wasted space on the left margin.  So the code within
53971 ** the switch statement will break with convention and be flush-left. Another
53972 ** big comment (similar to this one) will mark the point in the code where
53973 ** we transition back to normal indentation.
53974 **
53975 ** The formatting of each case is important.  The makefile for SQLite
53976 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
53977 ** file looking for lines that begin with "case OP_".  The opcodes.h files
53978 ** will be filled with #defines that give unique integer values to each
53979 ** opcode and the opcodes.c file is filled with an array of strings where
53980 ** each string is the symbolic name for the corresponding opcode.  If the
53981 ** case statement is followed by a comment of the form "/# same as ... #/"
53982 ** that comment is used to determine the particular value of the opcode.
53983 **
53984 ** Other keywords in the comment that follows each case are used to
53985 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
53986 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
53987 ** the mkopcodeh.awk script for additional information.
53988 **
53989 ** Documentation about VDBE opcodes is generated by scanning this file
53990 ** for lines of that contain "Opcode:".  That line and all subsequent
53991 ** comment lines are used in the generation of the opcode.html documentation
53992 ** file.
53993 **
53994 ** SUMMARY:
53995 **
53996 **     Formatting is important to scripts that scan this file.
53997 **     Do not deviate from the formatting style currently in use.
53998 **
53999 *****************************************************************************/
54000
54001 /* Opcode:  Goto * P2 * * *
54002 **
54003 ** An unconditional jump to address P2.
54004 ** The next instruction executed will be 
54005 ** the one at index P2 from the beginning of
54006 ** the program.
54007 */
54008 case OP_Goto: {             /* jump */
54009   CHECK_FOR_INTERRUPT;
54010   pc = pOp->p2 - 1;
54011   break;
54012 }
54013
54014 /* Opcode:  Gosub P1 P2 * * *
54015 **
54016 ** Write the current address onto register P1
54017 ** and then jump to address P2.
54018 */
54019 case OP_Gosub: {            /* jump, in1 */
54020   pIn1 = &aMem[pOp->p1];
54021   assert( (pIn1->flags & MEM_Dyn)==0 );
54022   pIn1->flags = MEM_Int;
54023   pIn1->u.i = pc;
54024   REGISTER_TRACE(pOp->p1, pIn1);
54025   pc = pOp->p2 - 1;
54026   break;
54027 }
54028
54029 /* Opcode:  Return P1 * * * *
54030 **
54031 ** Jump to the next instruction after the address in register P1.
54032 */
54033 case OP_Return: {           /* in1 */
54034   pIn1 = &aMem[pOp->p1];
54035   assert( pIn1->flags & MEM_Int );
54036   pc = (int)pIn1->u.i;
54037   break;
54038 }
54039
54040 /* Opcode:  Yield P1 * * * *
54041 **
54042 ** Swap the program counter with the value in register P1.
54043 */
54044 case OP_Yield: {            /* in1 */
54045 #if 0  /* local variables moved into u.aa */
54046   int pcDest;
54047 #endif /* local variables moved into u.aa */
54048   pIn1 = &aMem[pOp->p1];
54049   assert( (pIn1->flags & MEM_Dyn)==0 );
54050   pIn1->flags = MEM_Int;
54051   u.aa.pcDest = (int)pIn1->u.i;
54052   pIn1->u.i = pc;
54053   REGISTER_TRACE(pOp->p1, pIn1);
54054   pc = u.aa.pcDest;
54055   break;
54056 }
54057
54058 /* Opcode:  HaltIfNull  P1 P2 P3 P4 *
54059 **
54060 ** Check the value in register P3.  If is is NULL then Halt using
54061 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
54062 ** value in register P3 is not NULL, then this routine is a no-op.
54063 */
54064 case OP_HaltIfNull: {      /* in3 */
54065   pIn3 = &aMem[pOp->p3];
54066   if( (pIn3->flags & MEM_Null)==0 ) break;
54067   /* Fall through into OP_Halt */
54068 }
54069
54070 /* Opcode:  Halt P1 P2 * P4 *
54071 **
54072 ** Exit immediately.  All open cursors, etc are closed
54073 ** automatically.
54074 **
54075 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
54076 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
54077 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
54078 ** whether or not to rollback the current transaction.  Do not rollback
54079 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
54080 ** then back out all changes that have occurred during this execution of the
54081 ** VDBE, but do not rollback the transaction. 
54082 **
54083 ** If P4 is not null then it is an error message string.
54084 **
54085 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
54086 ** every program.  So a jump past the last instruction of the program
54087 ** is the same as executing Halt.
54088 */
54089 case OP_Halt: {
54090   if( pOp->p1==SQLITE_OK && p->pFrame ){
54091     /* Halt the sub-program. Return control to the parent frame. */
54092     VdbeFrame *pFrame = p->pFrame;
54093     p->pFrame = pFrame->pParent;
54094     p->nFrame--;
54095     sqlite3VdbeSetChanges(db, p->nChange);
54096     pc = sqlite3VdbeFrameRestore(pFrame);
54097     if( pOp->p2==OE_Ignore ){
54098       /* Instruction pc is the OP_Program that invoked the sub-program 
54099       ** currently being halted. If the p2 instruction of this OP_Halt
54100       ** instruction is set to OE_Ignore, then the sub-program is throwing
54101       ** an IGNORE exception. In this case jump to the address specified
54102       ** as the p2 of the calling OP_Program.  */
54103       pc = p->aOp[pc].p2-1;
54104     }
54105     aOp = p->aOp;
54106     aMem = p->aMem;
54107     break;
54108   }
54109
54110   p->rc = pOp->p1;
54111   p->errorAction = (u8)pOp->p2;
54112   p->pc = pc;
54113   if( pOp->p4.z ){
54114     assert( p->rc!=SQLITE_OK );
54115     sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
54116     testcase( sqlite3GlobalConfig.xLog!=0 );
54117     sqlite3_log(pOp->p1, "abort at %d in [%s]: %s", pc, p->zSql, pOp->p4.z);
54118   }else if( p->rc ){
54119     testcase( sqlite3GlobalConfig.xLog!=0 );
54120     sqlite3_log(pOp->p1, "constraint failed at %d in [%s]", pc, p->zSql);
54121   }
54122   rc = sqlite3VdbeHalt(p);
54123   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
54124   if( rc==SQLITE_BUSY ){
54125     p->rc = rc = SQLITE_BUSY;
54126   }else{
54127     assert( rc==SQLITE_OK || p->rc==SQLITE_CONSTRAINT );
54128     assert( rc==SQLITE_OK || db->nDeferredCons>0 );
54129     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
54130   }
54131   goto vdbe_return;
54132 }
54133
54134 /* Opcode: Integer P1 P2 * * *
54135 **
54136 ** The 32-bit integer value P1 is written into register P2.
54137 */
54138 case OP_Integer: {         /* out2-prerelease */
54139   pOut->u.i = pOp->p1;
54140   break;
54141 }
54142
54143 /* Opcode: Int64 * P2 * P4 *
54144 **
54145 ** P4 is a pointer to a 64-bit integer value.
54146 ** Write that value into register P2.
54147 */
54148 case OP_Int64: {           /* out2-prerelease */
54149   assert( pOp->p4.pI64!=0 );
54150   pOut->u.i = *pOp->p4.pI64;
54151   break;
54152 }
54153
54154 #ifndef SQLITE_OMIT_FLOATING_POINT
54155 /* Opcode: Real * P2 * P4 *
54156 **
54157 ** P4 is a pointer to a 64-bit floating point value.
54158 ** Write that value into register P2.
54159 */
54160 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
54161   pOut->flags = MEM_Real;
54162   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
54163   pOut->r = *pOp->p4.pReal;
54164   break;
54165 }
54166 #endif
54167
54168 /* Opcode: String8 * P2 * P4 *
54169 **
54170 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
54171 ** into an OP_String before it is executed for the first time.
54172 */
54173 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
54174   assert( pOp->p4.z!=0 );
54175   pOp->opcode = OP_String;
54176   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
54177
54178 #ifndef SQLITE_OMIT_UTF16
54179   if( encoding!=SQLITE_UTF8 ){
54180     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
54181     if( rc==SQLITE_TOOBIG ) goto too_big;
54182     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
54183     assert( pOut->zMalloc==pOut->z );
54184     assert( pOut->flags & MEM_Dyn );
54185     pOut->zMalloc = 0;
54186     pOut->flags |= MEM_Static;
54187     pOut->flags &= ~MEM_Dyn;
54188     if( pOp->p4type==P4_DYNAMIC ){
54189       sqlite3DbFree(db, pOp->p4.z);
54190     }
54191     pOp->p4type = P4_DYNAMIC;
54192     pOp->p4.z = pOut->z;
54193     pOp->p1 = pOut->n;
54194   }
54195 #endif
54196   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
54197     goto too_big;
54198   }
54199   /* Fall through to the next case, OP_String */
54200 }
54201   
54202 /* Opcode: String P1 P2 * P4 *
54203 **
54204 ** The string value P4 of length P1 (bytes) is stored in register P2.
54205 */
54206 case OP_String: {          /* out2-prerelease */
54207   assert( pOp->p4.z!=0 );
54208   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
54209   pOut->z = pOp->p4.z;
54210   pOut->n = pOp->p1;
54211   pOut->enc = encoding;
54212   UPDATE_MAX_BLOBSIZE(pOut);
54213   break;
54214 }
54215
54216 /* Opcode: Null * P2 * * *
54217 **
54218 ** Write a NULL into register P2.
54219 */
54220 case OP_Null: {           /* out2-prerelease */
54221   pOut->flags = MEM_Null;
54222   break;
54223 }
54224
54225
54226 /* Opcode: Blob P1 P2 * P4
54227 **
54228 ** P4 points to a blob of data P1 bytes long.  Store this
54229 ** blob in register P2. This instruction is not coded directly
54230 ** by the compiler. Instead, the compiler layer specifies
54231 ** an OP_HexBlob opcode, with the hex string representation of
54232 ** the blob as P4. This opcode is transformed to an OP_Blob
54233 ** the first time it is executed.
54234 */
54235 case OP_Blob: {                /* out2-prerelease */
54236   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
54237   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
54238   pOut->enc = encoding;
54239   UPDATE_MAX_BLOBSIZE(pOut);
54240   break;
54241 }
54242
54243 /* Opcode: Variable P1 P2 P3 P4 *
54244 **
54245 ** Transfer the values of bound parameters P1..P1+P3-1 into registers
54246 ** P2..P2+P3-1.
54247 **
54248 ** If the parameter is named, then its name appears in P4 and P3==1.
54249 ** The P4 value is used by sqlite3_bind_parameter_name().
54250 */
54251 case OP_Variable: {
54252 #if 0  /* local variables moved into u.ab */
54253   int p1;          /* Variable to copy from */
54254   int p2;          /* Register to copy to */
54255   int n;           /* Number of values left to copy */
54256   Mem *pVar;       /* Value being transferred */
54257 #endif /* local variables moved into u.ab */
54258
54259   u.ab.p1 = pOp->p1 - 1;
54260   u.ab.p2 = pOp->p2;
54261   u.ab.n = pOp->p3;
54262   assert( u.ab.p1>=0 && u.ab.p1+u.ab.n<=p->nVar );
54263   assert( u.ab.p2>=1 && u.ab.p2+u.ab.n-1<=p->nMem );
54264   assert( pOp->p4.z==0 || pOp->p3==1 || pOp->p3==0 );
54265
54266   while( u.ab.n-- > 0 ){
54267     u.ab.pVar = &p->aVar[u.ab.p1++];
54268     if( sqlite3VdbeMemTooBig(u.ab.pVar) ){
54269       goto too_big;
54270     }
54271     pOut = &aMem[u.ab.p2++];
54272     sqlite3VdbeMemReleaseExternal(pOut);
54273     pOut->flags = MEM_Null;
54274     sqlite3VdbeMemShallowCopy(pOut, u.ab.pVar, MEM_Static);
54275     UPDATE_MAX_BLOBSIZE(pOut);
54276   }
54277   break;
54278 }
54279
54280 /* Opcode: Move P1 P2 P3 * *
54281 **
54282 ** Move the values in register P1..P1+P3-1 over into
54283 ** registers P2..P2+P3-1.  Registers P1..P1+P1-1 are
54284 ** left holding a NULL.  It is an error for register ranges
54285 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.
54286 */
54287 case OP_Move: {
54288 #if 0  /* local variables moved into u.ac */
54289   char *zMalloc;   /* Holding variable for allocated memory */
54290   int n;           /* Number of registers left to copy */
54291   int p1;          /* Register to copy from */
54292   int p2;          /* Register to copy to */
54293 #endif /* local variables moved into u.ac */
54294
54295   u.ac.n = pOp->p3;
54296   u.ac.p1 = pOp->p1;
54297   u.ac.p2 = pOp->p2;
54298   assert( u.ac.n>0 && u.ac.p1>0 && u.ac.p2>0 );
54299   assert( u.ac.p1+u.ac.n<=u.ac.p2 || u.ac.p2+u.ac.n<=u.ac.p1 );
54300
54301   pIn1 = &aMem[u.ac.p1];
54302   pOut = &aMem[u.ac.p2];
54303   while( u.ac.n-- ){
54304     assert( pOut<=&aMem[p->nMem] );
54305     assert( pIn1<=&aMem[p->nMem] );
54306     u.ac.zMalloc = pOut->zMalloc;
54307     pOut->zMalloc = 0;
54308     sqlite3VdbeMemMove(pOut, pIn1);
54309     pIn1->zMalloc = u.ac.zMalloc;
54310     REGISTER_TRACE(u.ac.p2++, pOut);
54311     pIn1++;
54312     pOut++;
54313   }
54314   break;
54315 }
54316
54317 /* Opcode: Copy P1 P2 * * *
54318 **
54319 ** Make a copy of register P1 into register P2.
54320 **
54321 ** This instruction makes a deep copy of the value.  A duplicate
54322 ** is made of any string or blob constant.  See also OP_SCopy.
54323 */
54324 case OP_Copy: {             /* in1, out2 */
54325   pIn1 = &aMem[pOp->p1];
54326   pOut = &aMem[pOp->p2];
54327   assert( pOut!=pIn1 );
54328   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
54329   Deephemeralize(pOut);
54330   REGISTER_TRACE(pOp->p2, pOut);
54331   break;
54332 }
54333
54334 /* Opcode: SCopy P1 P2 * * *
54335 **
54336 ** Make a shallow copy of register P1 into register P2.
54337 **
54338 ** This instruction makes a shallow copy of the value.  If the value
54339 ** is a string or blob, then the copy is only a pointer to the
54340 ** original and hence if the original changes so will the copy.
54341 ** Worse, if the original is deallocated, the copy becomes invalid.
54342 ** Thus the program must guarantee that the original will not change
54343 ** during the lifetime of the copy.  Use OP_Copy to make a complete
54344 ** copy.
54345 */
54346 case OP_SCopy: {            /* in1, out2 */
54347   pIn1 = &aMem[pOp->p1];
54348   pOut = &aMem[pOp->p2];
54349   assert( pOut!=pIn1 );
54350   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
54351   REGISTER_TRACE(pOp->p2, pOut);
54352   break;
54353 }
54354
54355 /* Opcode: ResultRow P1 P2 * * *
54356 **
54357 ** The registers P1 through P1+P2-1 contain a single row of
54358 ** results. This opcode causes the sqlite3_step() call to terminate
54359 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
54360 ** structure to provide access to the top P1 values as the result
54361 ** row.
54362 */
54363 case OP_ResultRow: {
54364 #if 0  /* local variables moved into u.ad */
54365   Mem *pMem;
54366   int i;
54367 #endif /* local variables moved into u.ad */
54368   assert( p->nResColumn==pOp->p2 );
54369   assert( pOp->p1>0 );
54370   assert( pOp->p1+pOp->p2<=p->nMem+1 );
54371
54372   /* If this statement has violated immediate foreign key constraints, do
54373   ** not return the number of rows modified. And do not RELEASE the statement
54374   ** transaction. It needs to be rolled back.  */
54375   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
54376     assert( db->flags&SQLITE_CountRows );
54377     assert( p->usesStmtJournal );
54378     break;
54379   }
54380
54381   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
54382   ** DML statements invoke this opcode to return the number of rows
54383   ** modified to the user. This is the only way that a VM that
54384   ** opens a statement transaction may invoke this opcode.
54385   **
54386   ** In case this is such a statement, close any statement transaction
54387   ** opened by this VM before returning control to the user. This is to
54388   ** ensure that statement-transactions are always nested, not overlapping.
54389   ** If the open statement-transaction is not closed here, then the user
54390   ** may step another VM that opens its own statement transaction. This
54391   ** may lead to overlapping statement transactions.
54392   **
54393   ** The statement transaction is never a top-level transaction.  Hence
54394   ** the RELEASE call below can never fail.
54395   */
54396   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
54397   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
54398   if( NEVER(rc!=SQLITE_OK) ){
54399     break;
54400   }
54401
54402   /* Invalidate all ephemeral cursor row caches */
54403   p->cacheCtr = (p->cacheCtr + 2)|1;
54404
54405   /* Make sure the results of the current row are \000 terminated
54406   ** and have an assigned type.  The results are de-ephemeralized as
54407   ** as side effect.
54408   */
54409   u.ad.pMem = p->pResultSet = &aMem[pOp->p1];
54410   for(u.ad.i=0; u.ad.i<pOp->p2; u.ad.i++){
54411     sqlite3VdbeMemNulTerminate(&u.ad.pMem[u.ad.i]);
54412     sqlite3VdbeMemStoreType(&u.ad.pMem[u.ad.i]);
54413     REGISTER_TRACE(pOp->p1+u.ad.i, &u.ad.pMem[u.ad.i]);
54414   }
54415   if( db->mallocFailed ) goto no_mem;
54416
54417   /* Return SQLITE_ROW
54418   */
54419   p->pc = pc + 1;
54420   rc = SQLITE_ROW;
54421   goto vdbe_return;
54422 }
54423
54424 /* Opcode: Concat P1 P2 P3 * *
54425 **
54426 ** Add the text in register P1 onto the end of the text in
54427 ** register P2 and store the result in register P3.
54428 ** If either the P1 or P2 text are NULL then store NULL in P3.
54429 **
54430 **   P3 = P2 || P1
54431 **
54432 ** It is illegal for P1 and P3 to be the same register. Sometimes,
54433 ** if P3 is the same register as P2, the implementation is able
54434 ** to avoid a memcpy().
54435 */
54436 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
54437 #if 0  /* local variables moved into u.ae */
54438   i64 nByte;
54439 #endif /* local variables moved into u.ae */
54440
54441   pIn1 = &aMem[pOp->p1];
54442   pIn2 = &aMem[pOp->p2];
54443   pOut = &aMem[pOp->p3];
54444   assert( pIn1!=pOut );
54445   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
54446     sqlite3VdbeMemSetNull(pOut);
54447     break;
54448   }
54449   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
54450   Stringify(pIn1, encoding);
54451   Stringify(pIn2, encoding);
54452   u.ae.nByte = pIn1->n + pIn2->n;
54453   if( u.ae.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
54454     goto too_big;
54455   }
54456   MemSetTypeFlag(pOut, MEM_Str);
54457   if( sqlite3VdbeMemGrow(pOut, (int)u.ae.nByte+2, pOut==pIn2) ){
54458     goto no_mem;
54459   }
54460   if( pOut!=pIn2 ){
54461     memcpy(pOut->z, pIn2->z, pIn2->n);
54462   }
54463   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
54464   pOut->z[u.ae.nByte] = 0;
54465   pOut->z[u.ae.nByte+1] = 0;
54466   pOut->flags |= MEM_Term;
54467   pOut->n = (int)u.ae.nByte;
54468   pOut->enc = encoding;
54469   UPDATE_MAX_BLOBSIZE(pOut);
54470   break;
54471 }
54472
54473 /* Opcode: Add P1 P2 P3 * *
54474 **
54475 ** Add the value in register P1 to the value in register P2
54476 ** and store the result in register P3.
54477 ** If either input is NULL, the result is NULL.
54478 */
54479 /* Opcode: Multiply P1 P2 P3 * *
54480 **
54481 **
54482 ** Multiply the value in register P1 by the value in register P2
54483 ** and store the result in register P3.
54484 ** If either input is NULL, the result is NULL.
54485 */
54486 /* Opcode: Subtract P1 P2 P3 * *
54487 **
54488 ** Subtract the value in register P1 from the value in register P2
54489 ** and store the result in register P3.
54490 ** If either input is NULL, the result is NULL.
54491 */
54492 /* Opcode: Divide P1 P2 P3 * *
54493 **
54494 ** Divide the value in register P1 by the value in register P2
54495 ** and store the result in register P3 (P3=P2/P1). If the value in 
54496 ** register P1 is zero, then the result is NULL. If either input is 
54497 ** NULL, the result is NULL.
54498 */
54499 /* Opcode: Remainder P1 P2 P3 * *
54500 **
54501 ** Compute the remainder after integer division of the value in
54502 ** register P1 by the value in register P2 and store the result in P3. 
54503 ** If the value in register P2 is zero the result is NULL.
54504 ** If either operand is NULL, the result is NULL.
54505 */
54506 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
54507 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
54508 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
54509 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
54510 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
54511 #if 0  /* local variables moved into u.af */
54512   int flags;      /* Combined MEM_* flags from both inputs */
54513   i64 iA;         /* Integer value of left operand */
54514   i64 iB;         /* Integer value of right operand */
54515   double rA;      /* Real value of left operand */
54516   double rB;      /* Real value of right operand */
54517 #endif /* local variables moved into u.af */
54518
54519   pIn1 = &aMem[pOp->p1];
54520   applyNumericAffinity(pIn1);
54521   pIn2 = &aMem[pOp->p2];
54522   applyNumericAffinity(pIn2);
54523   pOut = &aMem[pOp->p3];
54524   u.af.flags = pIn1->flags | pIn2->flags;
54525   if( (u.af.flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
54526   if( (pIn1->flags & pIn2->flags & MEM_Int)==MEM_Int ){
54527     u.af.iA = pIn1->u.i;
54528     u.af.iB = pIn2->u.i;
54529     switch( pOp->opcode ){
54530       case OP_Add:         u.af.iB += u.af.iA;       break;
54531       case OP_Subtract:    u.af.iB -= u.af.iA;       break;
54532       case OP_Multiply:    u.af.iB *= u.af.iA;       break;
54533       case OP_Divide: {
54534         if( u.af.iA==0 ) goto arithmetic_result_is_null;
54535         /* Dividing the largest possible negative 64-bit integer (1<<63) by
54536         ** -1 returns an integer too large to store in a 64-bit data-type. On
54537         ** some architectures, the value overflows to (1<<63). On others,
54538         ** a SIGFPE is issued. The following statement normalizes this
54539         ** behavior so that all architectures behave as if integer
54540         ** overflow occurred.
54541         */
54542         if( u.af.iA==-1 && u.af.iB==SMALLEST_INT64 ) u.af.iA = 1;
54543         u.af.iB /= u.af.iA;
54544         break;
54545       }
54546       default: {
54547         if( u.af.iA==0 ) goto arithmetic_result_is_null;
54548         if( u.af.iA==-1 ) u.af.iA = 1;
54549         u.af.iB %= u.af.iA;
54550         break;
54551       }
54552     }
54553     pOut->u.i = u.af.iB;
54554     MemSetTypeFlag(pOut, MEM_Int);
54555   }else{
54556     u.af.rA = sqlite3VdbeRealValue(pIn1);
54557     u.af.rB = sqlite3VdbeRealValue(pIn2);
54558     switch( pOp->opcode ){
54559       case OP_Add:         u.af.rB += u.af.rA;       break;
54560       case OP_Subtract:    u.af.rB -= u.af.rA;       break;
54561       case OP_Multiply:    u.af.rB *= u.af.rA;       break;
54562       case OP_Divide: {
54563         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
54564         if( u.af.rA==(double)0 ) goto arithmetic_result_is_null;
54565         u.af.rB /= u.af.rA;
54566         break;
54567       }
54568       default: {
54569         u.af.iA = (i64)u.af.rA;
54570         u.af.iB = (i64)u.af.rB;
54571         if( u.af.iA==0 ) goto arithmetic_result_is_null;
54572         if( u.af.iA==-1 ) u.af.iA = 1;
54573         u.af.rB = (double)(u.af.iB % u.af.iA);
54574         break;
54575       }
54576     }
54577 #ifdef SQLITE_OMIT_FLOATING_POINT
54578     pOut->u.i = u.af.rB;
54579     MemSetTypeFlag(pOut, MEM_Int);
54580 #else
54581     if( sqlite3IsNaN(u.af.rB) ){
54582       goto arithmetic_result_is_null;
54583     }
54584     pOut->r = u.af.rB;
54585     MemSetTypeFlag(pOut, MEM_Real);
54586     if( (u.af.flags & MEM_Real)==0 ){
54587       sqlite3VdbeIntegerAffinity(pOut);
54588     }
54589 #endif
54590   }
54591   break;
54592
54593 arithmetic_result_is_null:
54594   sqlite3VdbeMemSetNull(pOut);
54595   break;
54596 }
54597
54598 /* Opcode: CollSeq * * P4
54599 **
54600 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
54601 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
54602 ** be returned. This is used by the built-in min(), max() and nullif()
54603 ** functions.
54604 **
54605 ** The interface used by the implementation of the aforementioned functions
54606 ** to retrieve the collation sequence set by this opcode is not available
54607 ** publicly, only to user functions defined in func.c.
54608 */
54609 case OP_CollSeq: {
54610   assert( pOp->p4type==P4_COLLSEQ );
54611   break;
54612 }
54613
54614 /* Opcode: Function P1 P2 P3 P4 P5
54615 **
54616 ** Invoke a user function (P4 is a pointer to a Function structure that
54617 ** defines the function) with P5 arguments taken from register P2 and
54618 ** successors.  The result of the function is stored in register P3.
54619 ** Register P3 must not be one of the function inputs.
54620 **
54621 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
54622 ** function was determined to be constant at compile time. If the first
54623 ** argument was constant then bit 0 of P1 is set. This is used to determine
54624 ** whether meta data associated with a user function argument using the
54625 ** sqlite3_set_auxdata() API may be safely retained until the next
54626 ** invocation of this opcode.
54627 **
54628 ** See also: AggStep and AggFinal
54629 */
54630 case OP_Function: {
54631 #if 0  /* local variables moved into u.ag */
54632   int i;
54633   Mem *pArg;
54634   sqlite3_context ctx;
54635   sqlite3_value **apVal;
54636   int n;
54637 #endif /* local variables moved into u.ag */
54638
54639   u.ag.n = pOp->p5;
54640   u.ag.apVal = p->apArg;
54641   assert( u.ag.apVal || u.ag.n==0 );
54642
54643   assert( u.ag.n==0 || (pOp->p2>0 && pOp->p2+u.ag.n<=p->nMem+1) );
54644   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+u.ag.n );
54645   u.ag.pArg = &aMem[pOp->p2];
54646   for(u.ag.i=0; u.ag.i<u.ag.n; u.ag.i++, u.ag.pArg++){
54647     u.ag.apVal[u.ag.i] = u.ag.pArg;
54648     sqlite3VdbeMemStoreType(u.ag.pArg);
54649     REGISTER_TRACE(pOp->p2, u.ag.pArg);
54650   }
54651
54652   assert( pOp->p4type==P4_FUNCDEF || pOp->p4type==P4_VDBEFUNC );
54653   if( pOp->p4type==P4_FUNCDEF ){
54654     u.ag.ctx.pFunc = pOp->p4.pFunc;
54655     u.ag.ctx.pVdbeFunc = 0;
54656   }else{
54657     u.ag.ctx.pVdbeFunc = (VdbeFunc*)pOp->p4.pVdbeFunc;
54658     u.ag.ctx.pFunc = u.ag.ctx.pVdbeFunc->pFunc;
54659   }
54660
54661   assert( pOp->p3>0 && pOp->p3<=p->nMem );
54662   pOut = &aMem[pOp->p3];
54663   u.ag.ctx.s.flags = MEM_Null;
54664   u.ag.ctx.s.db = db;
54665   u.ag.ctx.s.xDel = 0;
54666   u.ag.ctx.s.zMalloc = 0;
54667
54668   /* The output cell may already have a buffer allocated. Move
54669   ** the pointer to u.ag.ctx.s so in case the user-function can use
54670   ** the already allocated buffer instead of allocating a new one.
54671   */
54672   sqlite3VdbeMemMove(&u.ag.ctx.s, pOut);
54673   MemSetTypeFlag(&u.ag.ctx.s, MEM_Null);
54674
54675   u.ag.ctx.isError = 0;
54676   if( u.ag.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
54677     assert( pOp>aOp );
54678     assert( pOp[-1].p4type==P4_COLLSEQ );
54679     assert( pOp[-1].opcode==OP_CollSeq );
54680     u.ag.ctx.pColl = pOp[-1].p4.pColl;
54681   }
54682   (*u.ag.ctx.pFunc->xFunc)(&u.ag.ctx, u.ag.n, u.ag.apVal);
54683   if( db->mallocFailed ){
54684     /* Even though a malloc() has failed, the implementation of the
54685     ** user function may have called an sqlite3_result_XXX() function
54686     ** to return a value. The following call releases any resources
54687     ** associated with such a value.
54688     */
54689     sqlite3VdbeMemRelease(&u.ag.ctx.s);
54690     goto no_mem;
54691   }
54692
54693   /* If any auxiliary data functions have been called by this user function,
54694   ** immediately call the destructor for any non-static values.
54695   */
54696   if( u.ag.ctx.pVdbeFunc ){
54697     sqlite3VdbeDeleteAuxData(u.ag.ctx.pVdbeFunc, pOp->p1);
54698     pOp->p4.pVdbeFunc = u.ag.ctx.pVdbeFunc;
54699     pOp->p4type = P4_VDBEFUNC;
54700   }
54701
54702   /* If the function returned an error, throw an exception */
54703   if( u.ag.ctx.isError ){
54704     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.ag.ctx.s));
54705     rc = u.ag.ctx.isError;
54706   }
54707
54708   /* Copy the result of the function into register P3 */
54709   sqlite3VdbeChangeEncoding(&u.ag.ctx.s, encoding);
54710   sqlite3VdbeMemMove(pOut, &u.ag.ctx.s);
54711   if( sqlite3VdbeMemTooBig(pOut) ){
54712     goto too_big;
54713   }
54714   REGISTER_TRACE(pOp->p3, pOut);
54715   UPDATE_MAX_BLOBSIZE(pOut);
54716   break;
54717 }
54718
54719 /* Opcode: BitAnd P1 P2 P3 * *
54720 **
54721 ** Take the bit-wise AND of the values in register P1 and P2 and
54722 ** store the result in register P3.
54723 ** If either input is NULL, the result is NULL.
54724 */
54725 /* Opcode: BitOr P1 P2 P3 * *
54726 **
54727 ** Take the bit-wise OR of the values in register P1 and P2 and
54728 ** store the result in register P3.
54729 ** If either input is NULL, the result is NULL.
54730 */
54731 /* Opcode: ShiftLeft P1 P2 P3 * *
54732 **
54733 ** Shift the integer value in register P2 to the left by the
54734 ** number of bits specified by the integer in regiser P1.
54735 ** Store the result in register P3.
54736 ** If either input is NULL, the result is NULL.
54737 */
54738 /* Opcode: ShiftRight P1 P2 P3 * *
54739 **
54740 ** Shift the integer value in register P2 to the right by the
54741 ** number of bits specified by the integer in register P1.
54742 ** Store the result in register P3.
54743 ** If either input is NULL, the result is NULL.
54744 */
54745 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
54746 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
54747 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
54748 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
54749 #if 0  /* local variables moved into u.ah */
54750   i64 a;
54751   i64 b;
54752 #endif /* local variables moved into u.ah */
54753
54754   pIn1 = &aMem[pOp->p1];
54755   pIn2 = &aMem[pOp->p2];
54756   pOut = &aMem[pOp->p3];
54757   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
54758     sqlite3VdbeMemSetNull(pOut);
54759     break;
54760   }
54761   u.ah.a = sqlite3VdbeIntValue(pIn2);
54762   u.ah.b = sqlite3VdbeIntValue(pIn1);
54763   switch( pOp->opcode ){
54764     case OP_BitAnd:      u.ah.a &= u.ah.b;     break;
54765     case OP_BitOr:       u.ah.a |= u.ah.b;     break;
54766     case OP_ShiftLeft:   u.ah.a <<= u.ah.b;    break;
54767     default:  assert( pOp->opcode==OP_ShiftRight );
54768                          u.ah.a >>= u.ah.b;    break;
54769   }
54770   pOut->u.i = u.ah.a;
54771   MemSetTypeFlag(pOut, MEM_Int);
54772   break;
54773 }
54774
54775 /* Opcode: AddImm  P1 P2 * * *
54776 ** 
54777 ** Add the constant P2 to the value in register P1.
54778 ** The result is always an integer.
54779 **
54780 ** To force any register to be an integer, just add 0.
54781 */
54782 case OP_AddImm: {            /* in1 */
54783   pIn1 = &aMem[pOp->p1];
54784   sqlite3VdbeMemIntegerify(pIn1);
54785   pIn1->u.i += pOp->p2;
54786   break;
54787 }
54788
54789 /* Opcode: MustBeInt P1 P2 * * *
54790 ** 
54791 ** Force the value in register P1 to be an integer.  If the value
54792 ** in P1 is not an integer and cannot be converted into an integer
54793 ** without data loss, then jump immediately to P2, or if P2==0
54794 ** raise an SQLITE_MISMATCH exception.
54795 */
54796 case OP_MustBeInt: {            /* jump, in1 */
54797   pIn1 = &aMem[pOp->p1];
54798   applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
54799   if( (pIn1->flags & MEM_Int)==0 ){
54800     if( pOp->p2==0 ){
54801       rc = SQLITE_MISMATCH;
54802       goto abort_due_to_error;
54803     }else{
54804       pc = pOp->p2 - 1;
54805     }
54806   }else{
54807     MemSetTypeFlag(pIn1, MEM_Int);
54808   }
54809   break;
54810 }
54811
54812 #ifndef SQLITE_OMIT_FLOATING_POINT
54813 /* Opcode: RealAffinity P1 * * * *
54814 **
54815 ** If register P1 holds an integer convert it to a real value.
54816 **
54817 ** This opcode is used when extracting information from a column that
54818 ** has REAL affinity.  Such column values may still be stored as
54819 ** integers, for space efficiency, but after extraction we want them
54820 ** to have only a real value.
54821 */
54822 case OP_RealAffinity: {                  /* in1 */
54823   pIn1 = &aMem[pOp->p1];
54824   if( pIn1->flags & MEM_Int ){
54825     sqlite3VdbeMemRealify(pIn1);
54826   }
54827   break;
54828 }
54829 #endif
54830
54831 #ifndef SQLITE_OMIT_CAST
54832 /* Opcode: ToText P1 * * * *
54833 **
54834 ** Force the value in register P1 to be text.
54835 ** If the value is numeric, convert it to a string using the
54836 ** equivalent of printf().  Blob values are unchanged and
54837 ** are afterwards simply interpreted as text.
54838 **
54839 ** A NULL value is not changed by this routine.  It remains NULL.
54840 */
54841 case OP_ToText: {                  /* same as TK_TO_TEXT, in1 */
54842   pIn1 = &aMem[pOp->p1];
54843   if( pIn1->flags & MEM_Null ) break;
54844   assert( MEM_Str==(MEM_Blob>>3) );
54845   pIn1->flags |= (pIn1->flags&MEM_Blob)>>3;
54846   applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
54847   rc = ExpandBlob(pIn1);
54848   assert( pIn1->flags & MEM_Str || db->mallocFailed );
54849   pIn1->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
54850   UPDATE_MAX_BLOBSIZE(pIn1);
54851   break;
54852 }
54853
54854 /* Opcode: ToBlob P1 * * * *
54855 **
54856 ** Force the value in register P1 to be a BLOB.
54857 ** If the value is numeric, convert it to a string first.
54858 ** Strings are simply reinterpreted as blobs with no change
54859 ** to the underlying data.
54860 **
54861 ** A NULL value is not changed by this routine.  It remains NULL.
54862 */
54863 case OP_ToBlob: {                  /* same as TK_TO_BLOB, in1 */
54864   pIn1 = &aMem[pOp->p1];
54865   if( pIn1->flags & MEM_Null ) break;
54866   if( (pIn1->flags & MEM_Blob)==0 ){
54867     applyAffinity(pIn1, SQLITE_AFF_TEXT, encoding);
54868     assert( pIn1->flags & MEM_Str || db->mallocFailed );
54869     MemSetTypeFlag(pIn1, MEM_Blob);
54870   }else{
54871     pIn1->flags &= ~(MEM_TypeMask&~MEM_Blob);
54872   }
54873   UPDATE_MAX_BLOBSIZE(pIn1);
54874   break;
54875 }
54876
54877 /* Opcode: ToNumeric P1 * * * *
54878 **
54879 ** Force the value in register P1 to be numeric (either an
54880 ** integer or a floating-point number.)
54881 ** If the value is text or blob, try to convert it to an using the
54882 ** equivalent of atoi() or atof() and store 0 if no such conversion 
54883 ** is possible.
54884 **
54885 ** A NULL value is not changed by this routine.  It remains NULL.
54886 */
54887 case OP_ToNumeric: {                  /* same as TK_TO_NUMERIC, in1 */
54888   pIn1 = &aMem[pOp->p1];
54889   if( (pIn1->flags & (MEM_Null|MEM_Int|MEM_Real))==0 ){
54890     sqlite3VdbeMemNumerify(pIn1);
54891   }
54892   break;
54893 }
54894 #endif /* SQLITE_OMIT_CAST */
54895
54896 /* Opcode: ToInt P1 * * * *
54897 **
54898 ** Force the value in register P1 be an integer.  If
54899 ** The value is currently a real number, drop its fractional part.
54900 ** If the value is text or blob, try to convert it to an integer using the
54901 ** equivalent of atoi() and store 0 if no such conversion is possible.
54902 **
54903 ** A NULL value is not changed by this routine.  It remains NULL.
54904 */
54905 case OP_ToInt: {                  /* same as TK_TO_INT, in1 */
54906   pIn1 = &aMem[pOp->p1];
54907   if( (pIn1->flags & MEM_Null)==0 ){
54908     sqlite3VdbeMemIntegerify(pIn1);
54909   }
54910   break;
54911 }
54912
54913 #if !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT)
54914 /* Opcode: ToReal P1 * * * *
54915 **
54916 ** Force the value in register P1 to be a floating point number.
54917 ** If The value is currently an integer, convert it.
54918 ** If the value is text or blob, try to convert it to an integer using the
54919 ** equivalent of atoi() and store 0.0 if no such conversion is possible.
54920 **
54921 ** A NULL value is not changed by this routine.  It remains NULL.
54922 */
54923 case OP_ToReal: {                  /* same as TK_TO_REAL, in1 */
54924   pIn1 = &aMem[pOp->p1];
54925   if( (pIn1->flags & MEM_Null)==0 ){
54926     sqlite3VdbeMemRealify(pIn1);
54927   }
54928   break;
54929 }
54930 #endif /* !defined(SQLITE_OMIT_CAST) && !defined(SQLITE_OMIT_FLOATING_POINT) */
54931
54932 /* Opcode: Lt P1 P2 P3 P4 P5
54933 **
54934 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
54935 ** jump to address P2.  
54936 **
54937 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
54938 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
54939 ** bit is clear then fall thru if either operand is NULL.
54940 **
54941 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
54942 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
54943 ** to coerce both inputs according to this affinity before the
54944 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
54945 ** affinity is used. Note that the affinity conversions are stored
54946 ** back into the input registers P1 and P3.  So this opcode can cause
54947 ** persistent changes to registers P1 and P3.
54948 **
54949 ** Once any conversions have taken place, and neither value is NULL, 
54950 ** the values are compared. If both values are blobs then memcmp() is
54951 ** used to determine the results of the comparison.  If both values
54952 ** are text, then the appropriate collating function specified in
54953 ** P4 is  used to do the comparison.  If P4 is not specified then
54954 ** memcmp() is used to compare text string.  If both values are
54955 ** numeric, then a numeric comparison is used. If the two values
54956 ** are of different types, then numbers are considered less than
54957 ** strings and strings are considered less than blobs.
54958 **
54959 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
54960 ** store a boolean result (either 0, or 1, or NULL) in register P2.
54961 */
54962 /* Opcode: Ne P1 P2 P3 P4 P5
54963 **
54964 ** This works just like the Lt opcode except that the jump is taken if
54965 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
54966 ** additional information.
54967 **
54968 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
54969 ** true or false and is never NULL.  If both operands are NULL then the result
54970 ** of comparison is false.  If either operand is NULL then the result is true.
54971 ** If neither operand is NULL the the result is the same as it would be if
54972 ** the SQLITE_NULLEQ flag were omitted from P5.
54973 */
54974 /* Opcode: Eq P1 P2 P3 P4 P5
54975 **
54976 ** This works just like the Lt opcode except that the jump is taken if
54977 ** the operands in registers P1 and P3 are equal.
54978 ** See the Lt opcode for additional information.
54979 **
54980 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
54981 ** true or false and is never NULL.  If both operands are NULL then the result
54982 ** of comparison is true.  If either operand is NULL then the result is false.
54983 ** If neither operand is NULL the the result is the same as it would be if
54984 ** the SQLITE_NULLEQ flag were omitted from P5.
54985 */
54986 /* Opcode: Le P1 P2 P3 P4 P5
54987 **
54988 ** This works just like the Lt opcode except that the jump is taken if
54989 ** the content of register P3 is less than or equal to the content of
54990 ** register P1.  See the Lt opcode for additional information.
54991 */
54992 /* Opcode: Gt P1 P2 P3 P4 P5
54993 **
54994 ** This works just like the Lt opcode except that the jump is taken if
54995 ** the content of register P3 is greater than the content of
54996 ** register P1.  See the Lt opcode for additional information.
54997 */
54998 /* Opcode: Ge P1 P2 P3 P4 P5
54999 **
55000 ** This works just like the Lt opcode except that the jump is taken if
55001 ** the content of register P3 is greater than or equal to the content of
55002 ** register P1.  See the Lt opcode for additional information.
55003 */
55004 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
55005 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
55006 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
55007 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
55008 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
55009 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
55010 #if 0  /* local variables moved into u.ai */
55011   int res;            /* Result of the comparison of pIn1 against pIn3 */
55012   char affinity;      /* Affinity to use for comparison */
55013   u16 flags1;         /* Copy of initial value of pIn1->flags */
55014   u16 flags3;         /* Copy of initial value of pIn3->flags */
55015 #endif /* local variables moved into u.ai */
55016
55017   pIn1 = &aMem[pOp->p1];
55018   pIn3 = &aMem[pOp->p3];
55019   u.ai.flags1 = pIn1->flags;
55020   u.ai.flags3 = pIn3->flags;
55021   if( (pIn1->flags | pIn3->flags)&MEM_Null ){
55022     /* One or both operands are NULL */
55023     if( pOp->p5 & SQLITE_NULLEQ ){
55024       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
55025       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
55026       ** or not both operands are null.
55027       */
55028       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
55029       u.ai.res = (pIn1->flags & pIn3->flags & MEM_Null)==0;
55030     }else{
55031       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
55032       ** then the result is always NULL.
55033       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
55034       */
55035       if( pOp->p5 & SQLITE_STOREP2 ){
55036         pOut = &aMem[pOp->p2];
55037         MemSetTypeFlag(pOut, MEM_Null);
55038         REGISTER_TRACE(pOp->p2, pOut);
55039       }else if( pOp->p5 & SQLITE_JUMPIFNULL ){
55040         pc = pOp->p2-1;
55041       }
55042       break;
55043     }
55044   }else{
55045     /* Neither operand is NULL.  Do a comparison. */
55046     u.ai.affinity = pOp->p5 & SQLITE_AFF_MASK;
55047     if( u.ai.affinity ){
55048       applyAffinity(pIn1, u.ai.affinity, encoding);
55049       applyAffinity(pIn3, u.ai.affinity, encoding);
55050       if( db->mallocFailed ) goto no_mem;
55051     }
55052
55053     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
55054     ExpandBlob(pIn1);
55055     ExpandBlob(pIn3);
55056     u.ai.res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
55057   }
55058   switch( pOp->opcode ){
55059     case OP_Eq:    u.ai.res = u.ai.res==0;     break;
55060     case OP_Ne:    u.ai.res = u.ai.res!=0;     break;
55061     case OP_Lt:    u.ai.res = u.ai.res<0;      break;
55062     case OP_Le:    u.ai.res = u.ai.res<=0;     break;
55063     case OP_Gt:    u.ai.res = u.ai.res>0;      break;
55064     default:       u.ai.res = u.ai.res>=0;     break;
55065   }
55066
55067   if( pOp->p5 & SQLITE_STOREP2 ){
55068     pOut = &aMem[pOp->p2];
55069     MemSetTypeFlag(pOut, MEM_Int);
55070     pOut->u.i = u.ai.res;
55071     REGISTER_TRACE(pOp->p2, pOut);
55072   }else if( u.ai.res ){
55073     pc = pOp->p2-1;
55074   }
55075
55076   /* Undo any changes made by applyAffinity() to the input registers. */
55077   pIn1->flags = (pIn1->flags&~MEM_TypeMask) | (u.ai.flags1&MEM_TypeMask);
55078   pIn3->flags = (pIn3->flags&~MEM_TypeMask) | (u.ai.flags3&MEM_TypeMask);
55079   break;
55080 }
55081
55082 /* Opcode: Permutation * * * P4 *
55083 **
55084 ** Set the permutation used by the OP_Compare operator to be the array
55085 ** of integers in P4.
55086 **
55087 ** The permutation is only valid until the next OP_Permutation, OP_Compare,
55088 ** OP_Halt, or OP_ResultRow.  Typically the OP_Permutation should occur
55089 ** immediately prior to the OP_Compare.
55090 */
55091 case OP_Permutation: {
55092   assert( pOp->p4type==P4_INTARRAY );
55093   assert( pOp->p4.ai );
55094   aPermute = pOp->p4.ai;
55095   break;
55096 }
55097
55098 /* Opcode: Compare P1 P2 P3 P4 *
55099 **
55100 ** Compare to vectors of registers in reg(P1)..reg(P1+P3-1) (all this
55101 ** one "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
55102 ** the comparison for use by the next OP_Jump instruct.
55103 **
55104 ** P4 is a KeyInfo structure that defines collating sequences and sort
55105 ** orders for the comparison.  The permutation applies to registers
55106 ** only.  The KeyInfo elements are used sequentially.
55107 **
55108 ** The comparison is a sort comparison, so NULLs compare equal,
55109 ** NULLs are less than numbers, numbers are less than strings,
55110 ** and strings are less than blobs.
55111 */
55112 case OP_Compare: {
55113 #if 0  /* local variables moved into u.aj */
55114   int n;
55115   int i;
55116   int p1;
55117   int p2;
55118   const KeyInfo *pKeyInfo;
55119   int idx;
55120   CollSeq *pColl;    /* Collating sequence to use on this term */
55121   int bRev;          /* True for DESCENDING sort order */
55122 #endif /* local variables moved into u.aj */
55123
55124   u.aj.n = pOp->p3;
55125   u.aj.pKeyInfo = pOp->p4.pKeyInfo;
55126   assert( u.aj.n>0 );
55127   assert( u.aj.pKeyInfo!=0 );
55128   u.aj.p1 = pOp->p1;
55129   u.aj.p2 = pOp->p2;
55130 #if SQLITE_DEBUG
55131   if( aPermute ){
55132     int k, mx = 0;
55133     for(k=0; k<u.aj.n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
55134     assert( u.aj.p1>0 && u.aj.p1+mx<=p->nMem+1 );
55135     assert( u.aj.p2>0 && u.aj.p2+mx<=p->nMem+1 );
55136   }else{
55137     assert( u.aj.p1>0 && u.aj.p1+u.aj.n<=p->nMem+1 );
55138     assert( u.aj.p2>0 && u.aj.p2+u.aj.n<=p->nMem+1 );
55139   }
55140 #endif /* SQLITE_DEBUG */
55141   for(u.aj.i=0; u.aj.i<u.aj.n; u.aj.i++){
55142     u.aj.idx = aPermute ? aPermute[u.aj.i] : u.aj.i;
55143     REGISTER_TRACE(u.aj.p1+u.aj.idx, &aMem[u.aj.p1+u.aj.idx]);
55144     REGISTER_TRACE(u.aj.p2+u.aj.idx, &aMem[u.aj.p2+u.aj.idx]);
55145     assert( u.aj.i<u.aj.pKeyInfo->nField );
55146     u.aj.pColl = u.aj.pKeyInfo->aColl[u.aj.i];
55147     u.aj.bRev = u.aj.pKeyInfo->aSortOrder[u.aj.i];
55148     iCompare = sqlite3MemCompare(&aMem[u.aj.p1+u.aj.idx], &aMem[u.aj.p2+u.aj.idx], u.aj.pColl);
55149     if( iCompare ){
55150       if( u.aj.bRev ) iCompare = -iCompare;
55151       break;
55152     }
55153   }
55154   aPermute = 0;
55155   break;
55156 }
55157
55158 /* Opcode: Jump P1 P2 P3 * *
55159 **
55160 ** Jump to the instruction at address P1, P2, or P3 depending on whether
55161 ** in the most recent OP_Compare instruction the P1 vector was less than
55162 ** equal to, or greater than the P2 vector, respectively.
55163 */
55164 case OP_Jump: {             /* jump */
55165   if( iCompare<0 ){
55166     pc = pOp->p1 - 1;
55167   }else if( iCompare==0 ){
55168     pc = pOp->p2 - 1;
55169   }else{
55170     pc = pOp->p3 - 1;
55171   }
55172   break;
55173 }
55174
55175 /* Opcode: And P1 P2 P3 * *
55176 **
55177 ** Take the logical AND of the values in registers P1 and P2 and
55178 ** write the result into register P3.
55179 **
55180 ** If either P1 or P2 is 0 (false) then the result is 0 even if
55181 ** the other input is NULL.  A NULL and true or two NULLs give
55182 ** a NULL output.
55183 */
55184 /* Opcode: Or P1 P2 P3 * *
55185 **
55186 ** Take the logical OR of the values in register P1 and P2 and
55187 ** store the answer in register P3.
55188 **
55189 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
55190 ** even if the other input is NULL.  A NULL and false or two NULLs
55191 ** give a NULL output.
55192 */
55193 case OP_And:              /* same as TK_AND, in1, in2, out3 */
55194 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
55195 #if 0  /* local variables moved into u.ak */
55196   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
55197   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
55198 #endif /* local variables moved into u.ak */
55199
55200   pIn1 = &aMem[pOp->p1];
55201   if( pIn1->flags & MEM_Null ){
55202     u.ak.v1 = 2;
55203   }else{
55204     u.ak.v1 = sqlite3VdbeIntValue(pIn1)!=0;
55205   }
55206   pIn2 = &aMem[pOp->p2];
55207   if( pIn2->flags & MEM_Null ){
55208     u.ak.v2 = 2;
55209   }else{
55210     u.ak.v2 = sqlite3VdbeIntValue(pIn2)!=0;
55211   }
55212   if( pOp->opcode==OP_And ){
55213     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
55214     u.ak.v1 = and_logic[u.ak.v1*3+u.ak.v2];
55215   }else{
55216     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
55217     u.ak.v1 = or_logic[u.ak.v1*3+u.ak.v2];
55218   }
55219   pOut = &aMem[pOp->p3];
55220   if( u.ak.v1==2 ){
55221     MemSetTypeFlag(pOut, MEM_Null);
55222   }else{
55223     pOut->u.i = u.ak.v1;
55224     MemSetTypeFlag(pOut, MEM_Int);
55225   }
55226   break;
55227 }
55228
55229 /* Opcode: Not P1 P2 * * *
55230 **
55231 ** Interpret the value in register P1 as a boolean value.  Store the
55232 ** boolean complement in register P2.  If the value in register P1 is 
55233 ** NULL, then a NULL is stored in P2.
55234 */
55235 case OP_Not: {                /* same as TK_NOT, in1, out2 */
55236   pIn1 = &aMem[pOp->p1];
55237   pOut = &aMem[pOp->p2];
55238   if( pIn1->flags & MEM_Null ){
55239     sqlite3VdbeMemSetNull(pOut);
55240   }else{
55241     sqlite3VdbeMemSetInt64(pOut, !sqlite3VdbeIntValue(pIn1));
55242   }
55243   break;
55244 }
55245
55246 /* Opcode: BitNot P1 P2 * * *
55247 **
55248 ** Interpret the content of register P1 as an integer.  Store the
55249 ** ones-complement of the P1 value into register P2.  If P1 holds
55250 ** a NULL then store a NULL in P2.
55251 */
55252 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
55253   pIn1 = &aMem[pOp->p1];
55254   pOut = &aMem[pOp->p2];
55255   if( pIn1->flags & MEM_Null ){
55256     sqlite3VdbeMemSetNull(pOut);
55257   }else{
55258     sqlite3VdbeMemSetInt64(pOut, ~sqlite3VdbeIntValue(pIn1));
55259   }
55260   break;
55261 }
55262
55263 /* Opcode: If P1 P2 P3 * *
55264 **
55265 ** Jump to P2 if the value in register P1 is true.  The value is
55266 ** is considered true if it is numeric and non-zero.  If the value
55267 ** in P1 is NULL then take the jump if P3 is true.
55268 */
55269 /* Opcode: IfNot P1 P2 P3 * *
55270 **
55271 ** Jump to P2 if the value in register P1 is False.  The value is
55272 ** is considered true if it has a numeric value of zero.  If the value
55273 ** in P1 is NULL then take the jump if P3 is true.
55274 */
55275 case OP_If:                 /* jump, in1 */
55276 case OP_IfNot: {            /* jump, in1 */
55277 #if 0  /* local variables moved into u.al */
55278   int c;
55279 #endif /* local variables moved into u.al */
55280   pIn1 = &aMem[pOp->p1];
55281   if( pIn1->flags & MEM_Null ){
55282     u.al.c = pOp->p3;
55283   }else{
55284 #ifdef SQLITE_OMIT_FLOATING_POINT
55285     u.al.c = sqlite3VdbeIntValue(pIn1)!=0;
55286 #else
55287     u.al.c = sqlite3VdbeRealValue(pIn1)!=0.0;
55288 #endif
55289     if( pOp->opcode==OP_IfNot ) u.al.c = !u.al.c;
55290   }
55291   if( u.al.c ){
55292     pc = pOp->p2-1;
55293   }
55294   break;
55295 }
55296
55297 /* Opcode: IsNull P1 P2 * * *
55298 **
55299 ** Jump to P2 if the value in register P1 is NULL.
55300 */
55301 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
55302   pIn1 = &aMem[pOp->p1];
55303   if( (pIn1->flags & MEM_Null)!=0 ){
55304     pc = pOp->p2 - 1;
55305   }
55306   break;
55307 }
55308
55309 /* Opcode: NotNull P1 P2 * * *
55310 **
55311 ** Jump to P2 if the value in register P1 is not NULL.  
55312 */
55313 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
55314   pIn1 = &aMem[pOp->p1];
55315   if( (pIn1->flags & MEM_Null)==0 ){
55316     pc = pOp->p2 - 1;
55317   }
55318   break;
55319 }
55320
55321 /* Opcode: Column P1 P2 P3 P4 P5
55322 **
55323 ** Interpret the data that cursor P1 points to as a structure built using
55324 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
55325 ** information about the format of the data.)  Extract the P2-th column
55326 ** from this record.  If there are less that (P2+1) 
55327 ** values in the record, extract a NULL.
55328 **
55329 ** The value extracted is stored in register P3.
55330 **
55331 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
55332 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
55333 ** the result.
55334 **
55335 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
55336 ** then the cache of the cursor is reset prior to extracting the column.
55337 ** The first OP_Column against a pseudo-table after the value of the content
55338 ** register has changed should have this bit set.
55339 */
55340 case OP_Column: {
55341 #if 0  /* local variables moved into u.am */
55342   u32 payloadSize;   /* Number of bytes in the record */
55343   i64 payloadSize64; /* Number of bytes in the record */
55344   int p1;            /* P1 value of the opcode */
55345   int p2;            /* column number to retrieve */
55346   VdbeCursor *pC;    /* The VDBE cursor */
55347   char *zRec;        /* Pointer to complete record-data */
55348   BtCursor *pCrsr;   /* The BTree cursor */
55349   u32 *aType;        /* aType[i] holds the numeric type of the i-th column */
55350   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
55351   int nField;        /* number of fields in the record */
55352   int len;           /* The length of the serialized data for the column */
55353   int i;             /* Loop counter */
55354   char *zData;       /* Part of the record being decoded */
55355   Mem *pDest;        /* Where to write the extracted value */
55356   Mem sMem;          /* For storing the record being decoded */
55357   u8 *zIdx;          /* Index into header */
55358   u8 *zEndHdr;       /* Pointer to first byte after the header */
55359   u32 offset;        /* Offset into the data */
55360   u32 szField;       /* Number of bytes in the content of a field */
55361   int szHdr;         /* Size of the header size field at start of record */
55362   int avail;         /* Number of bytes of available data */
55363   Mem *pReg;         /* PseudoTable input register */
55364 #endif /* local variables moved into u.am */
55365
55366
55367   u.am.p1 = pOp->p1;
55368   u.am.p2 = pOp->p2;
55369   u.am.pC = 0;
55370   memset(&u.am.sMem, 0, sizeof(u.am.sMem));
55371   assert( u.am.p1<p->nCursor );
55372   assert( pOp->p3>0 && pOp->p3<=p->nMem );
55373   u.am.pDest = &aMem[pOp->p3];
55374   MemSetTypeFlag(u.am.pDest, MEM_Null);
55375   u.am.zRec = 0;
55376
55377   /* This block sets the variable u.am.payloadSize to be the total number of
55378   ** bytes in the record.
55379   **
55380   ** u.am.zRec is set to be the complete text of the record if it is available.
55381   ** The complete record text is always available for pseudo-tables
55382   ** If the record is stored in a cursor, the complete record text
55383   ** might be available in the  u.am.pC->aRow cache.  Or it might not be.
55384   ** If the data is unavailable,  u.am.zRec is set to NULL.
55385   **
55386   ** We also compute the number of columns in the record.  For cursors,
55387   ** the number of columns is stored in the VdbeCursor.nField element.
55388   */
55389   u.am.pC = p->apCsr[u.am.p1];
55390   assert( u.am.pC!=0 );
55391 #ifndef SQLITE_OMIT_VIRTUALTABLE
55392   assert( u.am.pC->pVtabCursor==0 );
55393 #endif
55394   u.am.pCrsr = u.am.pC->pCursor;
55395   if( u.am.pCrsr!=0 ){
55396     /* The record is stored in a B-Tree */
55397     rc = sqlite3VdbeCursorMoveto(u.am.pC);
55398     if( rc ) goto abort_due_to_error;
55399     if( u.am.pC->nullRow ){
55400       u.am.payloadSize = 0;
55401     }else if( u.am.pC->cacheStatus==p->cacheCtr ){
55402       u.am.payloadSize = u.am.pC->payloadSize;
55403       u.am.zRec = (char*)u.am.pC->aRow;
55404     }else if( u.am.pC->isIndex ){
55405       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
55406       rc = sqlite3BtreeKeySize(u.am.pCrsr, &u.am.payloadSize64);
55407       assert( rc==SQLITE_OK );   /* True because of CursorMoveto() call above */
55408       /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
55409       ** payload size, so it is impossible for u.am.payloadSize64 to be
55410       ** larger than 32 bits. */
55411       assert( (u.am.payloadSize64 & SQLITE_MAX_U32)==(u64)u.am.payloadSize64 );
55412       u.am.payloadSize = (u32)u.am.payloadSize64;
55413     }else{
55414       assert( sqlite3BtreeCursorIsValid(u.am.pCrsr) );
55415       rc = sqlite3BtreeDataSize(u.am.pCrsr, &u.am.payloadSize);
55416       assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
55417     }
55418   }else if( u.am.pC->pseudoTableReg>0 ){
55419     u.am.pReg = &aMem[u.am.pC->pseudoTableReg];
55420     assert( u.am.pReg->flags & MEM_Blob );
55421     u.am.payloadSize = u.am.pReg->n;
55422     u.am.zRec = u.am.pReg->z;
55423     u.am.pC->cacheStatus = (pOp->p5&OPFLAG_CLEARCACHE) ? CACHE_STALE : p->cacheCtr;
55424     assert( u.am.payloadSize==0 || u.am.zRec!=0 );
55425   }else{
55426     /* Consider the row to be NULL */
55427     u.am.payloadSize = 0;
55428   }
55429
55430   /* If u.am.payloadSize is 0, then just store a NULL */
55431   if( u.am.payloadSize==0 ){
55432     assert( u.am.pDest->flags&MEM_Null );
55433     goto op_column_out;
55434   }
55435   assert( db->aLimit[SQLITE_LIMIT_LENGTH]>=0 );
55436   if( u.am.payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
55437     goto too_big;
55438   }
55439
55440   u.am.nField = u.am.pC->nField;
55441   assert( u.am.p2<u.am.nField );
55442
55443   /* Read and parse the table header.  Store the results of the parse
55444   ** into the record header cache fields of the cursor.
55445   */
55446   u.am.aType = u.am.pC->aType;
55447   if( u.am.pC->cacheStatus==p->cacheCtr ){
55448     u.am.aOffset = u.am.pC->aOffset;
55449   }else{
55450     assert(u.am.aType);
55451     u.am.avail = 0;
55452     u.am.pC->aOffset = u.am.aOffset = &u.am.aType[u.am.nField];
55453     u.am.pC->payloadSize = u.am.payloadSize;
55454     u.am.pC->cacheStatus = p->cacheCtr;
55455
55456     /* Figure out how many bytes are in the header */
55457     if( u.am.zRec ){
55458       u.am.zData = u.am.zRec;
55459     }else{
55460       if( u.am.pC->isIndex ){
55461         u.am.zData = (char*)sqlite3BtreeKeyFetch(u.am.pCrsr, &u.am.avail);
55462       }else{
55463         u.am.zData = (char*)sqlite3BtreeDataFetch(u.am.pCrsr, &u.am.avail);
55464       }
55465       /* If KeyFetch()/DataFetch() managed to get the entire payload,
55466       ** save the payload in the u.am.pC->aRow cache.  That will save us from
55467       ** having to make additional calls to fetch the content portion of
55468       ** the record.
55469       */
55470       assert( u.am.avail>=0 );
55471       if( u.am.payloadSize <= (u32)u.am.avail ){
55472         u.am.zRec = u.am.zData;
55473         u.am.pC->aRow = (u8*)u.am.zData;
55474       }else{
55475         u.am.pC->aRow = 0;
55476       }
55477     }
55478     /* The following assert is true in all cases accept when
55479     ** the database file has been corrupted externally.
55480     **    assert( u.am.zRec!=0 || u.am.avail>=u.am.payloadSize || u.am.avail>=9 ); */
55481     u.am.szHdr = getVarint32((u8*)u.am.zData, u.am.offset);
55482
55483     /* Make sure a corrupt database has not given us an oversize header.
55484     ** Do this now to avoid an oversize memory allocation.
55485     **
55486     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
55487     ** types use so much data space that there can only be 4096 and 32 of
55488     ** them, respectively.  So the maximum header length results from a
55489     ** 3-byte type for each of the maximum of 32768 columns plus three
55490     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
55491     */
55492     if( u.am.offset > 98307 ){
55493       rc = SQLITE_CORRUPT_BKPT;
55494       goto op_column_out;
55495     }
55496
55497     /* Compute in u.am.len the number of bytes of data we need to read in order
55498     ** to get u.am.nField type values.  u.am.offset is an upper bound on this.  But
55499     ** u.am.nField might be significantly less than the true number of columns
55500     ** in the table, and in that case, 5*u.am.nField+3 might be smaller than u.am.offset.
55501     ** We want to minimize u.am.len in order to limit the size of the memory
55502     ** allocation, especially if a corrupt database file has caused u.am.offset
55503     ** to be oversized. Offset is limited to 98307 above.  But 98307 might
55504     ** still exceed Robson memory allocation limits on some configurations.
55505     ** On systems that cannot tolerate large memory allocations, u.am.nField*5+3
55506     ** will likely be much smaller since u.am.nField will likely be less than
55507     ** 20 or so.  This insures that Robson memory allocation limits are
55508     ** not exceeded even for corrupt database files.
55509     */
55510     u.am.len = u.am.nField*5 + 3;
55511     if( u.am.len > (int)u.am.offset ) u.am.len = (int)u.am.offset;
55512
55513     /* The KeyFetch() or DataFetch() above are fast and will get the entire
55514     ** record header in most cases.  But they will fail to get the complete
55515     ** record header if the record header does not fit on a single page
55516     ** in the B-Tree.  When that happens, use sqlite3VdbeMemFromBtree() to
55517     ** acquire the complete header text.
55518     */
55519     if( !u.am.zRec && u.am.avail<u.am.len ){
55520       u.am.sMem.flags = 0;
55521       u.am.sMem.db = 0;
55522       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, 0, u.am.len, u.am.pC->isIndex, &u.am.sMem);
55523       if( rc!=SQLITE_OK ){
55524         goto op_column_out;
55525       }
55526       u.am.zData = u.am.sMem.z;
55527     }
55528     u.am.zEndHdr = (u8 *)&u.am.zData[u.am.len];
55529     u.am.zIdx = (u8 *)&u.am.zData[u.am.szHdr];
55530
55531     /* Scan the header and use it to fill in the u.am.aType[] and u.am.aOffset[]
55532     ** arrays.  u.am.aType[u.am.i] will contain the type integer for the u.am.i-th
55533     ** column and u.am.aOffset[u.am.i] will contain the u.am.offset from the beginning
55534     ** of the record to the start of the data for the u.am.i-th column
55535     */
55536     for(u.am.i=0; u.am.i<u.am.nField; u.am.i++){
55537       if( u.am.zIdx<u.am.zEndHdr ){
55538         u.am.aOffset[u.am.i] = u.am.offset;
55539         u.am.zIdx += getVarint32(u.am.zIdx, u.am.aType[u.am.i]);
55540         u.am.szField = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.i]);
55541         u.am.offset += u.am.szField;
55542         if( u.am.offset<u.am.szField ){  /* True if u.am.offset overflows */
55543           u.am.zIdx = &u.am.zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
55544           break;
55545         }
55546       }else{
55547         /* If u.am.i is less that u.am.nField, then there are less fields in this
55548         ** record than SetNumColumns indicated there are columns in the
55549         ** table. Set the u.am.offset for any extra columns not present in
55550         ** the record to 0. This tells code below to store a NULL
55551         ** instead of deserializing a value from the record.
55552         */
55553         u.am.aOffset[u.am.i] = 0;
55554       }
55555     }
55556     sqlite3VdbeMemRelease(&u.am.sMem);
55557     u.am.sMem.flags = MEM_Null;
55558
55559     /* If we have read more header data than was contained in the header,
55560     ** or if the end of the last field appears to be past the end of the
55561     ** record, or if the end of the last field appears to be before the end
55562     ** of the record (when all fields present), then we must be dealing
55563     ** with a corrupt database.
55564     */
55565     if( (u.am.zIdx > u.am.zEndHdr) || (u.am.offset > u.am.payloadSize)
55566          || (u.am.zIdx==u.am.zEndHdr && u.am.offset!=u.am.payloadSize) ){
55567       rc = SQLITE_CORRUPT_BKPT;
55568       goto op_column_out;
55569     }
55570   }
55571
55572   /* Get the column information. If u.am.aOffset[u.am.p2] is non-zero, then
55573   ** deserialize the value from the record. If u.am.aOffset[u.am.p2] is zero,
55574   ** then there are not enough fields in the record to satisfy the
55575   ** request.  In this case, set the value NULL or to P4 if P4 is
55576   ** a pointer to a Mem object.
55577   */
55578   if( u.am.aOffset[u.am.p2] ){
55579     assert( rc==SQLITE_OK );
55580     if( u.am.zRec ){
55581       sqlite3VdbeMemReleaseExternal(u.am.pDest);
55582       sqlite3VdbeSerialGet((u8 *)&u.am.zRec[u.am.aOffset[u.am.p2]], u.am.aType[u.am.p2], u.am.pDest);
55583     }else{
55584       u.am.len = sqlite3VdbeSerialTypeLen(u.am.aType[u.am.p2]);
55585       sqlite3VdbeMemMove(&u.am.sMem, u.am.pDest);
55586       rc = sqlite3VdbeMemFromBtree(u.am.pCrsr, u.am.aOffset[u.am.p2], u.am.len, u.am.pC->isIndex, &u.am.sMem);
55587       if( rc!=SQLITE_OK ){
55588         goto op_column_out;
55589       }
55590       u.am.zData = u.am.sMem.z;
55591       sqlite3VdbeSerialGet((u8*)u.am.zData, u.am.aType[u.am.p2], u.am.pDest);
55592     }
55593     u.am.pDest->enc = encoding;
55594   }else{
55595     if( pOp->p4type==P4_MEM ){
55596       sqlite3VdbeMemShallowCopy(u.am.pDest, pOp->p4.pMem, MEM_Static);
55597     }else{
55598       assert( u.am.pDest->flags&MEM_Null );
55599     }
55600   }
55601
55602   /* If we dynamically allocated space to hold the data (in the
55603   ** sqlite3VdbeMemFromBtree() call above) then transfer control of that
55604   ** dynamically allocated space over to the u.am.pDest structure.
55605   ** This prevents a memory copy.
55606   */
55607   if( u.am.sMem.zMalloc ){
55608     assert( u.am.sMem.z==u.am.sMem.zMalloc );
55609     assert( !(u.am.pDest->flags & MEM_Dyn) );
55610     assert( !(u.am.pDest->flags & (MEM_Blob|MEM_Str)) || u.am.pDest->z==u.am.sMem.z );
55611     u.am.pDest->flags &= ~(MEM_Ephem|MEM_Static);
55612     u.am.pDest->flags |= MEM_Term;
55613     u.am.pDest->z = u.am.sMem.z;
55614     u.am.pDest->zMalloc = u.am.sMem.zMalloc;
55615   }
55616
55617   rc = sqlite3VdbeMemMakeWriteable(u.am.pDest);
55618
55619 op_column_out:
55620   UPDATE_MAX_BLOBSIZE(u.am.pDest);
55621   REGISTER_TRACE(pOp->p3, u.am.pDest);
55622   break;
55623 }
55624
55625 /* Opcode: Affinity P1 P2 * P4 *
55626 **
55627 ** Apply affinities to a range of P2 registers starting with P1.
55628 **
55629 ** P4 is a string that is P2 characters long. The nth character of the
55630 ** string indicates the column affinity that should be used for the nth
55631 ** memory cell in the range.
55632 */
55633 case OP_Affinity: {
55634 #if 0  /* local variables moved into u.an */
55635   const char *zAffinity;   /* The affinity to be applied */
55636   char cAff;               /* A single character of affinity */
55637 #endif /* local variables moved into u.an */
55638
55639   u.an.zAffinity = pOp->p4.z;
55640   assert( u.an.zAffinity!=0 );
55641   assert( u.an.zAffinity[pOp->p2]==0 );
55642   pIn1 = &aMem[pOp->p1];
55643   while( (u.an.cAff = *(u.an.zAffinity++))!=0 ){
55644     assert( pIn1 <= &p->aMem[p->nMem] );
55645     ExpandBlob(pIn1);
55646     applyAffinity(pIn1, u.an.cAff, encoding);
55647     pIn1++;
55648   }
55649   break;
55650 }
55651
55652 /* Opcode: MakeRecord P1 P2 P3 P4 *
55653 **
55654 ** Convert P2 registers beginning with P1 into a single entry
55655 ** suitable for use as a data record in a database table or as a key
55656 ** in an index.  The details of the format are irrelevant as long as
55657 ** the OP_Column opcode can decode the record later.
55658 ** Refer to source code comments for the details of the record
55659 ** format.
55660 **
55661 ** P4 may be a string that is P2 characters long.  The nth character of the
55662 ** string indicates the column affinity that should be used for the nth
55663 ** field of the index key.
55664 **
55665 ** The mapping from character to affinity is given by the SQLITE_AFF_
55666 ** macros defined in sqliteInt.h.
55667 **
55668 ** If P4 is NULL then all index fields have the affinity NONE.
55669 */
55670 case OP_MakeRecord: {
55671 #if 0  /* local variables moved into u.ao */
55672   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
55673   Mem *pRec;             /* The new record */
55674   u64 nData;             /* Number of bytes of data space */
55675   int nHdr;              /* Number of bytes of header space */
55676   i64 nByte;             /* Data space required for this record */
55677   int nZero;             /* Number of zero bytes at the end of the record */
55678   int nVarint;           /* Number of bytes in a varint */
55679   u32 serial_type;       /* Type field */
55680   Mem *pData0;           /* First field to be combined into the record */
55681   Mem *pLast;            /* Last field of the record */
55682   int nField;            /* Number of fields in the record */
55683   char *zAffinity;       /* The affinity string for the record */
55684   int file_format;       /* File format to use for encoding */
55685   int i;                 /* Space used in zNewRecord[] */
55686   int len;               /* Length of a field */
55687 #endif /* local variables moved into u.ao */
55688
55689   /* Assuming the record contains N fields, the record format looks
55690   ** like this:
55691   **
55692   ** ------------------------------------------------------------------------
55693   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
55694   ** ------------------------------------------------------------------------
55695   **
55696   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
55697   ** and so froth.
55698   **
55699   ** Each type field is a varint representing the serial type of the
55700   ** corresponding data element (see sqlite3VdbeSerialType()). The
55701   ** hdr-size field is also a varint which is the offset from the beginning
55702   ** of the record to data0.
55703   */
55704   u.ao.nData = 0;         /* Number of bytes of data space */
55705   u.ao.nHdr = 0;          /* Number of bytes of header space */
55706   u.ao.nByte = 0;         /* Data space required for this record */
55707   u.ao.nZero = 0;         /* Number of zero bytes at the end of the record */
55708   u.ao.nField = pOp->p1;
55709   u.ao.zAffinity = pOp->p4.z;
55710   assert( u.ao.nField>0 && pOp->p2>0 && pOp->p2+u.ao.nField<=p->nMem+1 );
55711   u.ao.pData0 = &aMem[u.ao.nField];
55712   u.ao.nField = pOp->p2;
55713   u.ao.pLast = &u.ao.pData0[u.ao.nField-1];
55714   u.ao.file_format = p->minWriteFileFormat;
55715
55716   /* Loop through the elements that will make up the record to figure
55717   ** out how much space is required for the new record.
55718   */
55719   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
55720     if( u.ao.zAffinity ){
55721       applyAffinity(u.ao.pRec, u.ao.zAffinity[u.ao.pRec-u.ao.pData0], encoding);
55722     }
55723     if( u.ao.pRec->flags&MEM_Zero && u.ao.pRec->n>0 ){
55724       sqlite3VdbeMemExpandBlob(u.ao.pRec);
55725     }
55726     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
55727     u.ao.len = sqlite3VdbeSerialTypeLen(u.ao.serial_type);
55728     u.ao.nData += u.ao.len;
55729     u.ao.nHdr += sqlite3VarintLen(u.ao.serial_type);
55730     if( u.ao.pRec->flags & MEM_Zero ){
55731       /* Only pure zero-filled BLOBs can be input to this Opcode.
55732       ** We do not allow blobs with a prefix and a zero-filled tail. */
55733       u.ao.nZero += u.ao.pRec->u.nZero;
55734     }else if( u.ao.len ){
55735       u.ao.nZero = 0;
55736     }
55737   }
55738
55739   /* Add the initial header varint and total the size */
55740   u.ao.nHdr += u.ao.nVarint = sqlite3VarintLen(u.ao.nHdr);
55741   if( u.ao.nVarint<sqlite3VarintLen(u.ao.nHdr) ){
55742     u.ao.nHdr++;
55743   }
55744   u.ao.nByte = u.ao.nHdr+u.ao.nData-u.ao.nZero;
55745   if( u.ao.nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
55746     goto too_big;
55747   }
55748
55749   /* Make sure the output register has a buffer large enough to store
55750   ** the new record. The output register (pOp->p3) is not allowed to
55751   ** be one of the input registers (because the following call to
55752   ** sqlite3VdbeMemGrow() could clobber the value before it is used).
55753   */
55754   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
55755   pOut = &aMem[pOp->p3];
55756   if( sqlite3VdbeMemGrow(pOut, (int)u.ao.nByte, 0) ){
55757     goto no_mem;
55758   }
55759   u.ao.zNewRecord = (u8 *)pOut->z;
55760
55761   /* Write the record */
55762   u.ao.i = putVarint32(u.ao.zNewRecord, u.ao.nHdr);
55763   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){
55764     u.ao.serial_type = sqlite3VdbeSerialType(u.ao.pRec, u.ao.file_format);
55765     u.ao.i += putVarint32(&u.ao.zNewRecord[u.ao.i], u.ao.serial_type);      /* serial type */
55766   }
55767   for(u.ao.pRec=u.ao.pData0; u.ao.pRec<=u.ao.pLast; u.ao.pRec++){  /* serial data */
55768     u.ao.i += sqlite3VdbeSerialPut(&u.ao.zNewRecord[u.ao.i], (int)(u.ao.nByte-u.ao.i), u.ao.pRec,u.ao.file_format);
55769   }
55770   assert( u.ao.i==u.ao.nByte );
55771
55772   assert( pOp->p3>0 && pOp->p3<=p->nMem );
55773   pOut->n = (int)u.ao.nByte;
55774   pOut->flags = MEM_Blob | MEM_Dyn;
55775   pOut->xDel = 0;
55776   if( u.ao.nZero ){
55777     pOut->u.nZero = u.ao.nZero;
55778     pOut->flags |= MEM_Zero;
55779   }
55780   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
55781   REGISTER_TRACE(pOp->p3, pOut);
55782   UPDATE_MAX_BLOBSIZE(pOut);
55783   break;
55784 }
55785
55786 /* Opcode: Count P1 P2 * * *
55787 **
55788 ** Store the number of entries (an integer value) in the table or index 
55789 ** opened by cursor P1 in register P2
55790 */
55791 #ifndef SQLITE_OMIT_BTREECOUNT
55792 case OP_Count: {         /* out2-prerelease */
55793 #if 0  /* local variables moved into u.ap */
55794   i64 nEntry;
55795   BtCursor *pCrsr;
55796 #endif /* local variables moved into u.ap */
55797
55798   u.ap.pCrsr = p->apCsr[pOp->p1]->pCursor;
55799   if( u.ap.pCrsr ){
55800     rc = sqlite3BtreeCount(u.ap.pCrsr, &u.ap.nEntry);
55801   }else{
55802     u.ap.nEntry = 0;
55803   }
55804   pOut->u.i = u.ap.nEntry;
55805   break;
55806 }
55807 #endif
55808
55809 /* Opcode: Savepoint P1 * * P4 *
55810 **
55811 ** Open, release or rollback the savepoint named by parameter P4, depending
55812 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
55813 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
55814 */
55815 case OP_Savepoint: {
55816 #if 0  /* local variables moved into u.aq */
55817   int p1;                         /* Value of P1 operand */
55818   char *zName;                    /* Name of savepoint */
55819   int nName;
55820   Savepoint *pNew;
55821   Savepoint *pSavepoint;
55822   Savepoint *pTmp;
55823   int iSavepoint;
55824   int ii;
55825 #endif /* local variables moved into u.aq */
55826
55827   u.aq.p1 = pOp->p1;
55828   u.aq.zName = pOp->p4.z;
55829
55830   /* Assert that the u.aq.p1 parameter is valid. Also that if there is no open
55831   ** transaction, then there cannot be any savepoints.
55832   */
55833   assert( db->pSavepoint==0 || db->autoCommit==0 );
55834   assert( u.aq.p1==SAVEPOINT_BEGIN||u.aq.p1==SAVEPOINT_RELEASE||u.aq.p1==SAVEPOINT_ROLLBACK );
55835   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
55836   assert( checkSavepointCount(db) );
55837
55838   if( u.aq.p1==SAVEPOINT_BEGIN ){
55839     if( db->writeVdbeCnt>0 ){
55840       /* A new savepoint cannot be created if there are active write
55841       ** statements (i.e. open read/write incremental blob handles).
55842       */
55843       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
55844         "SQL statements in progress");
55845       rc = SQLITE_BUSY;
55846     }else{
55847       u.aq.nName = sqlite3Strlen30(u.aq.zName);
55848
55849       /* Create a new savepoint structure. */
55850       u.aq.pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+u.aq.nName+1);
55851       if( u.aq.pNew ){
55852         u.aq.pNew->zName = (char *)&u.aq.pNew[1];
55853         memcpy(u.aq.pNew->zName, u.aq.zName, u.aq.nName+1);
55854
55855         /* If there is no open transaction, then mark this as a special
55856         ** "transaction savepoint". */
55857         if( db->autoCommit ){
55858           db->autoCommit = 0;
55859           db->isTransactionSavepoint = 1;
55860         }else{
55861           db->nSavepoint++;
55862         }
55863
55864         /* Link the new savepoint into the database handle's list. */
55865         u.aq.pNew->pNext = db->pSavepoint;
55866         db->pSavepoint = u.aq.pNew;
55867         u.aq.pNew->nDeferredCons = db->nDeferredCons;
55868       }
55869     }
55870   }else{
55871     u.aq.iSavepoint = 0;
55872
55873     /* Find the named savepoint. If there is no such savepoint, then an
55874     ** an error is returned to the user.  */
55875     for(
55876       u.aq.pSavepoint = db->pSavepoint;
55877       u.aq.pSavepoint && sqlite3StrICmp(u.aq.pSavepoint->zName, u.aq.zName);
55878       u.aq.pSavepoint = u.aq.pSavepoint->pNext
55879     ){
55880       u.aq.iSavepoint++;
55881     }
55882     if( !u.aq.pSavepoint ){
55883       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", u.aq.zName);
55884       rc = SQLITE_ERROR;
55885     }else if(
55886         db->writeVdbeCnt>0 || (u.aq.p1==SAVEPOINT_ROLLBACK && db->activeVdbeCnt>1)
55887     ){
55888       /* It is not possible to release (commit) a savepoint if there are
55889       ** active write statements. It is not possible to rollback a savepoint
55890       ** if there are any active statements at all.
55891       */
55892       sqlite3SetString(&p->zErrMsg, db,
55893         "cannot %s savepoint - SQL statements in progress",
55894         (u.aq.p1==SAVEPOINT_ROLLBACK ? "rollback": "release")
55895       );
55896       rc = SQLITE_BUSY;
55897     }else{
55898
55899       /* Determine whether or not this is a transaction savepoint. If so,
55900       ** and this is a RELEASE command, then the current transaction
55901       ** is committed.
55902       */
55903       int isTransaction = u.aq.pSavepoint->pNext==0 && db->isTransactionSavepoint;
55904       if( isTransaction && u.aq.p1==SAVEPOINT_RELEASE ){
55905         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
55906           goto vdbe_return;
55907         }
55908         db->autoCommit = 1;
55909         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
55910           p->pc = pc;
55911           db->autoCommit = 0;
55912           p->rc = rc = SQLITE_BUSY;
55913           goto vdbe_return;
55914         }
55915         db->isTransactionSavepoint = 0;
55916         rc = p->rc;
55917       }else{
55918         u.aq.iSavepoint = db->nSavepoint - u.aq.iSavepoint - 1;
55919         for(u.aq.ii=0; u.aq.ii<db->nDb; u.aq.ii++){
55920           rc = sqlite3BtreeSavepoint(db->aDb[u.aq.ii].pBt, u.aq.p1, u.aq.iSavepoint);
55921           if( rc!=SQLITE_OK ){
55922             goto abort_due_to_error;
55923           }
55924         }
55925         if( u.aq.p1==SAVEPOINT_ROLLBACK && (db->flags&SQLITE_InternChanges)!=0 ){
55926           sqlite3ExpirePreparedStatements(db);
55927           sqlite3ResetInternalSchema(db, 0);
55928         }
55929       }
55930
55931       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
55932       ** savepoints nested inside of the savepoint being operated on. */
55933       while( db->pSavepoint!=u.aq.pSavepoint ){
55934         u.aq.pTmp = db->pSavepoint;
55935         db->pSavepoint = u.aq.pTmp->pNext;
55936         sqlite3DbFree(db, u.aq.pTmp);
55937         db->nSavepoint--;
55938       }
55939
55940       /* If it is a RELEASE, then destroy the savepoint being operated on
55941       ** too. If it is a ROLLBACK TO, then set the number of deferred
55942       ** constraint violations present in the database to the value stored
55943       ** when the savepoint was created.  */
55944       if( u.aq.p1==SAVEPOINT_RELEASE ){
55945         assert( u.aq.pSavepoint==db->pSavepoint );
55946         db->pSavepoint = u.aq.pSavepoint->pNext;
55947         sqlite3DbFree(db, u.aq.pSavepoint);
55948         if( !isTransaction ){
55949           db->nSavepoint--;
55950         }
55951       }else{
55952         db->nDeferredCons = u.aq.pSavepoint->nDeferredCons;
55953       }
55954     }
55955   }
55956
55957   break;
55958 }
55959
55960 /* Opcode: AutoCommit P1 P2 * * *
55961 **
55962 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
55963 ** back any currently active btree transactions. If there are any active
55964 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
55965 ** there are active writing VMs or active VMs that use shared cache.
55966 **
55967 ** This instruction causes the VM to halt.
55968 */
55969 case OP_AutoCommit: {
55970 #if 0  /* local variables moved into u.ar */
55971   int desiredAutoCommit;
55972   int iRollback;
55973   int turnOnAC;
55974 #endif /* local variables moved into u.ar */
55975
55976   u.ar.desiredAutoCommit = pOp->p1;
55977   u.ar.iRollback = pOp->p2;
55978   u.ar.turnOnAC = u.ar.desiredAutoCommit && !db->autoCommit;
55979   assert( u.ar.desiredAutoCommit==1 || u.ar.desiredAutoCommit==0 );
55980   assert( u.ar.desiredAutoCommit==1 || u.ar.iRollback==0 );
55981   assert( db->activeVdbeCnt>0 );  /* At least this one VM is active */
55982
55983   if( u.ar.turnOnAC && u.ar.iRollback && db->activeVdbeCnt>1 ){
55984     /* If this instruction implements a ROLLBACK and other VMs are
55985     ** still running, and a transaction is active, return an error indicating
55986     ** that the other VMs must complete first.
55987     */
55988     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
55989         "SQL statements in progress");
55990     rc = SQLITE_BUSY;
55991   }else if( u.ar.turnOnAC && !u.ar.iRollback && db->writeVdbeCnt>0 ){
55992     /* If this instruction implements a COMMIT and other VMs are writing
55993     ** return an error indicating that the other VMs must complete first.
55994     */
55995     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
55996         "SQL statements in progress");
55997     rc = SQLITE_BUSY;
55998   }else if( u.ar.desiredAutoCommit!=db->autoCommit ){
55999     if( u.ar.iRollback ){
56000       assert( u.ar.desiredAutoCommit==1 );
56001       sqlite3RollbackAll(db);
56002       db->autoCommit = 1;
56003     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
56004       goto vdbe_return;
56005     }else{
56006       db->autoCommit = (u8)u.ar.desiredAutoCommit;
56007       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
56008         p->pc = pc;
56009         db->autoCommit = (u8)(1-u.ar.desiredAutoCommit);
56010         p->rc = rc = SQLITE_BUSY;
56011         goto vdbe_return;
56012       }
56013     }
56014     assert( db->nStatement==0 );
56015     sqlite3CloseSavepoints(db);
56016     if( p->rc==SQLITE_OK ){
56017       rc = SQLITE_DONE;
56018     }else{
56019       rc = SQLITE_ERROR;
56020     }
56021     goto vdbe_return;
56022   }else{
56023     sqlite3SetString(&p->zErrMsg, db,
56024         (!u.ar.desiredAutoCommit)?"cannot start a transaction within a transaction":(
56025         (u.ar.iRollback)?"cannot rollback - no transaction is active":
56026                    "cannot commit - no transaction is active"));
56027
56028     rc = SQLITE_ERROR;
56029   }
56030   break;
56031 }
56032
56033 /* Opcode: Transaction P1 P2 * * *
56034 **
56035 ** Begin a transaction.  The transaction ends when a Commit or Rollback
56036 ** opcode is encountered.  Depending on the ON CONFLICT setting, the
56037 ** transaction might also be rolled back if an error is encountered.
56038 **
56039 ** P1 is the index of the database file on which the transaction is
56040 ** started.  Index 0 is the main database file and index 1 is the
56041 ** file used for temporary tables.  Indices of 2 or more are used for
56042 ** attached databases.
56043 **
56044 ** If P2 is non-zero, then a write-transaction is started.  A RESERVED lock is
56045 ** obtained on the database file when a write-transaction is started.  No
56046 ** other process can start another write transaction while this transaction is
56047 ** underway.  Starting a write transaction also creates a rollback journal. A
56048 ** write transaction must be started before any changes can be made to the
56049 ** database.  If P2 is 2 or greater then an EXCLUSIVE lock is also obtained
56050 ** on the file.
56051 **
56052 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
56053 ** true (this flag is set if the Vdbe may modify more than one row and may
56054 ** throw an ABORT exception), a statement transaction may also be opened.
56055 ** More specifically, a statement transaction is opened iff the database
56056 ** connection is currently not in autocommit mode, or if there are other
56057 ** active statements. A statement transaction allows the affects of this
56058 ** VDBE to be rolled back after an error without having to roll back the
56059 ** entire transaction. If no error is encountered, the statement transaction
56060 ** will automatically commit when the VDBE halts.
56061 **
56062 ** If P2 is zero, then a read-lock is obtained on the database file.
56063 */
56064 case OP_Transaction: {
56065 #if 0  /* local variables moved into u.as */
56066   Btree *pBt;
56067 #endif /* local variables moved into u.as */
56068
56069   assert( pOp->p1>=0 && pOp->p1<db->nDb );
56070   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
56071   u.as.pBt = db->aDb[pOp->p1].pBt;
56072
56073   if( u.as.pBt ){
56074     rc = sqlite3BtreeBeginTrans(u.as.pBt, pOp->p2);
56075     if( rc==SQLITE_BUSY ){
56076       p->pc = pc;
56077       p->rc = rc = SQLITE_BUSY;
56078       goto vdbe_return;
56079     }
56080     if( rc!=SQLITE_OK ){
56081       goto abort_due_to_error;
56082     }
56083
56084     if( pOp->p2 && p->usesStmtJournal
56085      && (db->autoCommit==0 || db->activeVdbeCnt>1)
56086     ){
56087       assert( sqlite3BtreeIsInTrans(u.as.pBt) );
56088       if( p->iStatement==0 ){
56089         assert( db->nStatement>=0 && db->nSavepoint>=0 );
56090         db->nStatement++;
56091         p->iStatement = db->nSavepoint + db->nStatement;
56092       }
56093       rc = sqlite3BtreeBeginStmt(u.as.pBt, p->iStatement);
56094
56095       /* Store the current value of the database handles deferred constraint
56096       ** counter. If the statement transaction needs to be rolled back,
56097       ** the value of this counter needs to be restored too.  */
56098       p->nStmtDefCons = db->nDeferredCons;
56099     }
56100   }
56101   break;
56102 }
56103
56104 /* Opcode: ReadCookie P1 P2 P3 * *
56105 **
56106 ** Read cookie number P3 from database P1 and write it into register P2.
56107 ** P3==1 is the schema version.  P3==2 is the database format.
56108 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
56109 ** the main database file and P1==1 is the database file used to store
56110 ** temporary tables.
56111 **
56112 ** There must be a read-lock on the database (either a transaction
56113 ** must be started or there must be an open cursor) before
56114 ** executing this instruction.
56115 */
56116 case OP_ReadCookie: {               /* out2-prerelease */
56117 #if 0  /* local variables moved into u.at */
56118   int iMeta;
56119   int iDb;
56120   int iCookie;
56121 #endif /* local variables moved into u.at */
56122
56123   u.at.iDb = pOp->p1;
56124   u.at.iCookie = pOp->p3;
56125   assert( pOp->p3<SQLITE_N_BTREE_META );
56126   assert( u.at.iDb>=0 && u.at.iDb<db->nDb );
56127   assert( db->aDb[u.at.iDb].pBt!=0 );
56128   assert( (p->btreeMask & (1<<u.at.iDb))!=0 );
56129
56130   sqlite3BtreeGetMeta(db->aDb[u.at.iDb].pBt, u.at.iCookie, (u32 *)&u.at.iMeta);
56131   pOut->u.i = u.at.iMeta;
56132   break;
56133 }
56134
56135 /* Opcode: SetCookie P1 P2 P3 * *
56136 **
56137 ** Write the content of register P3 (interpreted as an integer)
56138 ** into cookie number P2 of database P1.  P2==1 is the schema version.  
56139 ** P2==2 is the database format. P2==3 is the recommended pager cache 
56140 ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
56141 ** database file used to store temporary tables.
56142 **
56143 ** A transaction must be started before executing this opcode.
56144 */
56145 case OP_SetCookie: {       /* in3 */
56146 #if 0  /* local variables moved into u.au */
56147   Db *pDb;
56148 #endif /* local variables moved into u.au */
56149   assert( pOp->p2<SQLITE_N_BTREE_META );
56150   assert( pOp->p1>=0 && pOp->p1<db->nDb );
56151   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
56152   u.au.pDb = &db->aDb[pOp->p1];
56153   assert( u.au.pDb->pBt!=0 );
56154   pIn3 = &aMem[pOp->p3];
56155   sqlite3VdbeMemIntegerify(pIn3);
56156   /* See note about index shifting on OP_ReadCookie */
56157   rc = sqlite3BtreeUpdateMeta(u.au.pDb->pBt, pOp->p2, (int)pIn3->u.i);
56158   if( pOp->p2==BTREE_SCHEMA_VERSION ){
56159     /* When the schema cookie changes, record the new cookie internally */
56160     u.au.pDb->pSchema->schema_cookie = (int)pIn3->u.i;
56161     db->flags |= SQLITE_InternChanges;
56162   }else if( pOp->p2==BTREE_FILE_FORMAT ){
56163     /* Record changes in the file format */
56164     u.au.pDb->pSchema->file_format = (u8)pIn3->u.i;
56165   }
56166   if( pOp->p1==1 ){
56167     /* Invalidate all prepared statements whenever the TEMP database
56168     ** schema is changed.  Ticket #1644 */
56169     sqlite3ExpirePreparedStatements(db);
56170     p->expired = 0;
56171   }
56172   break;
56173 }
56174
56175 /* Opcode: VerifyCookie P1 P2 *
56176 **
56177 ** Check the value of global database parameter number 0 (the
56178 ** schema version) and make sure it is equal to P2.  
56179 ** P1 is the database number which is 0 for the main database file
56180 ** and 1 for the file holding temporary tables and some higher number
56181 ** for auxiliary databases.
56182 **
56183 ** The cookie changes its value whenever the database schema changes.
56184 ** This operation is used to detect when that the cookie has changed
56185 ** and that the current process needs to reread the schema.
56186 **
56187 ** Either a transaction needs to have been started or an OP_Open needs
56188 ** to be executed (to establish a read lock) before this opcode is
56189 ** invoked.
56190 */
56191 case OP_VerifyCookie: {
56192 #if 0  /* local variables moved into u.av */
56193   int iMeta;
56194   Btree *pBt;
56195 #endif /* local variables moved into u.av */
56196   assert( pOp->p1>=0 && pOp->p1<db->nDb );
56197   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
56198   u.av.pBt = db->aDb[pOp->p1].pBt;
56199   if( u.av.pBt ){
56200     sqlite3BtreeGetMeta(u.av.pBt, BTREE_SCHEMA_VERSION, (u32 *)&u.av.iMeta);
56201   }else{
56202     u.av.iMeta = 0;
56203   }
56204   if( u.av.iMeta!=pOp->p2 ){
56205     sqlite3DbFree(db, p->zErrMsg);
56206     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
56207     /* If the schema-cookie from the database file matches the cookie
56208     ** stored with the in-memory representation of the schema, do
56209     ** not reload the schema from the database file.
56210     **
56211     ** If virtual-tables are in use, this is not just an optimization.
56212     ** Often, v-tables store their data in other SQLite tables, which
56213     ** are queried from within xNext() and other v-table methods using
56214     ** prepared queries. If such a query is out-of-date, we do not want to
56215     ** discard the database schema, as the user code implementing the
56216     ** v-table would have to be ready for the sqlite3_vtab structure itself
56217     ** to be invalidated whenever sqlite3_step() is called from within
56218     ** a v-table method.
56219     */
56220     if( db->aDb[pOp->p1].pSchema->schema_cookie!=u.av.iMeta ){
56221       sqlite3ResetInternalSchema(db, pOp->p1);
56222     }
56223
56224     sqlite3ExpirePreparedStatements(db);
56225     rc = SQLITE_SCHEMA;
56226   }
56227   break;
56228 }
56229
56230 /* Opcode: OpenRead P1 P2 P3 P4 P5
56231 **
56232 ** Open a read-only cursor for the database table whose root page is
56233 ** P2 in a database file.  The database file is determined by P3. 
56234 ** P3==0 means the main database, P3==1 means the database used for 
56235 ** temporary tables, and P3>1 means used the corresponding attached
56236 ** database.  Give the new cursor an identifier of P1.  The P1
56237 ** values need not be contiguous but all P1 values should be small integers.
56238 ** It is an error for P1 to be negative.
56239 **
56240 ** If P5!=0 then use the content of register P2 as the root page, not
56241 ** the value of P2 itself.
56242 **
56243 ** There will be a read lock on the database whenever there is an
56244 ** open cursor.  If the database was unlocked prior to this instruction
56245 ** then a read lock is acquired as part of this instruction.  A read
56246 ** lock allows other processes to read the database but prohibits
56247 ** any other process from modifying the database.  The read lock is
56248 ** released when all cursors are closed.  If this instruction attempts
56249 ** to get a read lock but fails, the script terminates with an
56250 ** SQLITE_BUSY error code.
56251 **
56252 ** The P4 value may be either an integer (P4_INT32) or a pointer to
56253 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
56254 ** structure, then said structure defines the content and collating 
56255 ** sequence of the index being opened. Otherwise, if P4 is an integer 
56256 ** value, it is set to the number of columns in the table.
56257 **
56258 ** See also OpenWrite.
56259 */
56260 /* Opcode: OpenWrite P1 P2 P3 P4 P5
56261 **
56262 ** Open a read/write cursor named P1 on the table or index whose root
56263 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
56264 ** root page.
56265 **
56266 ** The P4 value may be either an integer (P4_INT32) or a pointer to
56267 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
56268 ** structure, then said structure defines the content and collating 
56269 ** sequence of the index being opened. Otherwise, if P4 is an integer 
56270 ** value, it is set to the number of columns in the table, or to the
56271 ** largest index of any column of the table that is actually used.
56272 **
56273 ** This instruction works just like OpenRead except that it opens the cursor
56274 ** in read/write mode.  For a given table, there can be one or more read-only
56275 ** cursors or a single read/write cursor but not both.
56276 **
56277 ** See also OpenRead.
56278 */
56279 case OP_OpenRead:
56280 case OP_OpenWrite: {
56281 #if 0  /* local variables moved into u.aw */
56282   int nField;
56283   KeyInfo *pKeyInfo;
56284   int p2;
56285   int iDb;
56286   int wrFlag;
56287   Btree *pX;
56288   VdbeCursor *pCur;
56289   Db *pDb;
56290 #endif /* local variables moved into u.aw */
56291
56292   if( p->expired ){
56293     rc = SQLITE_ABORT;
56294     break;
56295   }
56296
56297   u.aw.nField = 0;
56298   u.aw.pKeyInfo = 0;
56299   u.aw.p2 = pOp->p2;
56300   u.aw.iDb = pOp->p3;
56301   assert( u.aw.iDb>=0 && u.aw.iDb<db->nDb );
56302   assert( (p->btreeMask & (1<<u.aw.iDb))!=0 );
56303   u.aw.pDb = &db->aDb[u.aw.iDb];
56304   u.aw.pX = u.aw.pDb->pBt;
56305   assert( u.aw.pX!=0 );
56306   if( pOp->opcode==OP_OpenWrite ){
56307     u.aw.wrFlag = 1;
56308     if( u.aw.pDb->pSchema->file_format < p->minWriteFileFormat ){
56309       p->minWriteFileFormat = u.aw.pDb->pSchema->file_format;
56310     }
56311   }else{
56312     u.aw.wrFlag = 0;
56313   }
56314   if( pOp->p5 ){
56315     assert( u.aw.p2>0 );
56316     assert( u.aw.p2<=p->nMem );
56317     pIn2 = &aMem[u.aw.p2];
56318     sqlite3VdbeMemIntegerify(pIn2);
56319     u.aw.p2 = (int)pIn2->u.i;
56320     /* The u.aw.p2 value always comes from a prior OP_CreateTable opcode and
56321     ** that opcode will always set the u.aw.p2 value to 2 or more or else fail.
56322     ** If there were a failure, the prepared statement would have halted
56323     ** before reaching this instruction. */
56324     if( NEVER(u.aw.p2<2) ) {
56325       rc = SQLITE_CORRUPT_BKPT;
56326       goto abort_due_to_error;
56327     }
56328   }
56329   if( pOp->p4type==P4_KEYINFO ){
56330     u.aw.pKeyInfo = pOp->p4.pKeyInfo;
56331     u.aw.pKeyInfo->enc = ENC(p->db);
56332     u.aw.nField = u.aw.pKeyInfo->nField+1;
56333   }else if( pOp->p4type==P4_INT32 ){
56334     u.aw.nField = pOp->p4.i;
56335   }
56336   assert( pOp->p1>=0 );
56337   u.aw.pCur = allocateCursor(p, pOp->p1, u.aw.nField, u.aw.iDb, 1);
56338   if( u.aw.pCur==0 ) goto no_mem;
56339   u.aw.pCur->nullRow = 1;
56340   rc = sqlite3BtreeCursor(u.aw.pX, u.aw.p2, u.aw.wrFlag, u.aw.pKeyInfo, u.aw.pCur->pCursor);
56341   u.aw.pCur->pKeyInfo = u.aw.pKeyInfo;
56342
56343   /* Since it performs no memory allocation or IO, the only values that
56344   ** sqlite3BtreeCursor() may return are SQLITE_EMPTY and SQLITE_OK.
56345   ** SQLITE_EMPTY is only returned when attempting to open the table
56346   ** rooted at page 1 of a zero-byte database.  */
56347   assert( rc==SQLITE_EMPTY || rc==SQLITE_OK );
56348   if( rc==SQLITE_EMPTY ){
56349     u.aw.pCur->pCursor = 0;
56350     rc = SQLITE_OK;
56351   }
56352
56353   /* Set the VdbeCursor.isTable and isIndex variables. Previous versions of
56354   ** SQLite used to check if the root-page flags were sane at this point
56355   ** and report database corruption if they were not, but this check has
56356   ** since moved into the btree layer.  */
56357   u.aw.pCur->isTable = pOp->p4type!=P4_KEYINFO;
56358   u.aw.pCur->isIndex = !u.aw.pCur->isTable;
56359   break;
56360 }
56361
56362 /* Opcode: OpenEphemeral P1 P2 * P4 *
56363 **
56364 ** Open a new cursor P1 to a transient table.
56365 ** The cursor is always opened read/write even if 
56366 ** the main database is read-only.  The transient or virtual
56367 ** table is deleted automatically when the cursor is closed.
56368 **
56369 ** P2 is the number of columns in the virtual table.
56370 ** The cursor points to a BTree table if P4==0 and to a BTree index
56371 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
56372 ** that defines the format of keys in the index.
56373 **
56374 ** This opcode was once called OpenTemp.  But that created
56375 ** confusion because the term "temp table", might refer either
56376 ** to a TEMP table at the SQL level, or to a table opened by
56377 ** this opcode.  Then this opcode was call OpenVirtual.  But
56378 ** that created confusion with the whole virtual-table idea.
56379 */
56380 case OP_OpenEphemeral: {
56381 #if 0  /* local variables moved into u.ax */
56382   VdbeCursor *pCx;
56383 #endif /* local variables moved into u.ax */
56384   static const int openFlags =
56385       SQLITE_OPEN_READWRITE |
56386       SQLITE_OPEN_CREATE |
56387       SQLITE_OPEN_EXCLUSIVE |
56388       SQLITE_OPEN_DELETEONCLOSE |
56389       SQLITE_OPEN_TRANSIENT_DB;
56390
56391   assert( pOp->p1>=0 );
56392   u.ax.pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
56393   if( u.ax.pCx==0 ) goto no_mem;
56394   u.ax.pCx->nullRow = 1;
56395   rc = sqlite3BtreeFactory(db, 0, 1, SQLITE_DEFAULT_TEMP_CACHE_SIZE, openFlags,
56396                            &u.ax.pCx->pBt);
56397   if( rc==SQLITE_OK ){
56398     rc = sqlite3BtreeBeginTrans(u.ax.pCx->pBt, 1);
56399   }
56400   if( rc==SQLITE_OK ){
56401     /* If a transient index is required, create it by calling
56402     ** sqlite3BtreeCreateTable() with the BTREE_ZERODATA flag before
56403     ** opening it. If a transient table is required, just use the
56404     ** automatically created table with root-page 1 (an INTKEY table).
56405     */
56406     if( pOp->p4.pKeyInfo ){
56407       int pgno;
56408       assert( pOp->p4type==P4_KEYINFO );
56409       rc = sqlite3BtreeCreateTable(u.ax.pCx->pBt, &pgno, BTREE_ZERODATA);
56410       if( rc==SQLITE_OK ){
56411         assert( pgno==MASTER_ROOT+1 );
56412         rc = sqlite3BtreeCursor(u.ax.pCx->pBt, pgno, 1,
56413                                 (KeyInfo*)pOp->p4.z, u.ax.pCx->pCursor);
56414         u.ax.pCx->pKeyInfo = pOp->p4.pKeyInfo;
56415         u.ax.pCx->pKeyInfo->enc = ENC(p->db);
56416       }
56417       u.ax.pCx->isTable = 0;
56418     }else{
56419       rc = sqlite3BtreeCursor(u.ax.pCx->pBt, MASTER_ROOT, 1, 0, u.ax.pCx->pCursor);
56420       u.ax.pCx->isTable = 1;
56421     }
56422   }
56423   u.ax.pCx->isIndex = !u.ax.pCx->isTable;
56424   break;
56425 }
56426
56427 /* Opcode: OpenPseudo P1 P2 P3 * *
56428 **
56429 ** Open a new cursor that points to a fake table that contains a single
56430 ** row of data.  The content of that one row in the content of memory
56431 ** register P2.  In other words, cursor P1 becomes an alias for the 
56432 ** MEM_Blob content contained in register P2.
56433 **
56434 ** A pseudo-table created by this opcode is used to hold a single
56435 ** row output from the sorter so that the row can be decomposed into
56436 ** individual columns using the OP_Column opcode.  The OP_Column opcode
56437 ** is the only cursor opcode that works with a pseudo-table.
56438 **
56439 ** P3 is the number of fields in the records that will be stored by
56440 ** the pseudo-table.
56441 */
56442 case OP_OpenPseudo: {
56443 #if 0  /* local variables moved into u.ay */
56444   VdbeCursor *pCx;
56445 #endif /* local variables moved into u.ay */
56446
56447   assert( pOp->p1>=0 );
56448   u.ay.pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
56449   if( u.ay.pCx==0 ) goto no_mem;
56450   u.ay.pCx->nullRow = 1;
56451   u.ay.pCx->pseudoTableReg = pOp->p2;
56452   u.ay.pCx->isTable = 1;
56453   u.ay.pCx->isIndex = 0;
56454   break;
56455 }
56456
56457 /* Opcode: Close P1 * * * *
56458 **
56459 ** Close a cursor previously opened as P1.  If P1 is not
56460 ** currently open, this instruction is a no-op.
56461 */
56462 case OP_Close: {
56463   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56464   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
56465   p->apCsr[pOp->p1] = 0;
56466   break;
56467 }
56468
56469 /* Opcode: SeekGe P1 P2 P3 P4 *
56470 **
56471 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
56472 ** use the value in register P3 as the key.  If cursor P1 refers 
56473 ** to an SQL index, then P3 is the first in an array of P4 registers 
56474 ** that are used as an unpacked index key. 
56475 **
56476 ** Reposition cursor P1 so that  it points to the smallest entry that 
56477 ** is greater than or equal to the key value. If there are no records 
56478 ** greater than or equal to the key and P2 is not zero, then jump to P2.
56479 **
56480 ** See also: Found, NotFound, Distinct, SeekLt, SeekGt, SeekLe
56481 */
56482 /* Opcode: SeekGt P1 P2 P3 P4 *
56483 **
56484 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
56485 ** use the value in register P3 as a key. If cursor P1 refers 
56486 ** to an SQL index, then P3 is the first in an array of P4 registers 
56487 ** that are used as an unpacked index key. 
56488 **
56489 ** Reposition cursor P1 so that  it points to the smallest entry that 
56490 ** is greater than the key value. If there are no records greater than 
56491 ** the key and P2 is not zero, then jump to P2.
56492 **
56493 ** See also: Found, NotFound, Distinct, SeekLt, SeekGe, SeekLe
56494 */
56495 /* Opcode: SeekLt P1 P2 P3 P4 * 
56496 **
56497 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
56498 ** use the value in register P3 as a key. If cursor P1 refers 
56499 ** to an SQL index, then P3 is the first in an array of P4 registers 
56500 ** that are used as an unpacked index key. 
56501 **
56502 ** Reposition cursor P1 so that  it points to the largest entry that 
56503 ** is less than the key value. If there are no records less than 
56504 ** the key and P2 is not zero, then jump to P2.
56505 **
56506 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLe
56507 */
56508 /* Opcode: SeekLe P1 P2 P3 P4 *
56509 **
56510 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
56511 ** use the value in register P3 as a key. If cursor P1 refers 
56512 ** to an SQL index, then P3 is the first in an array of P4 registers 
56513 ** that are used as an unpacked index key. 
56514 **
56515 ** Reposition cursor P1 so that it points to the largest entry that 
56516 ** is less than or equal to the key value. If there are no records 
56517 ** less than or equal to the key and P2 is not zero, then jump to P2.
56518 **
56519 ** See also: Found, NotFound, Distinct, SeekGt, SeekGe, SeekLt
56520 */
56521 case OP_SeekLt:         /* jump, in3 */
56522 case OP_SeekLe:         /* jump, in3 */
56523 case OP_SeekGe:         /* jump, in3 */
56524 case OP_SeekGt: {       /* jump, in3 */
56525 #if 0  /* local variables moved into u.az */
56526   int res;
56527   int oc;
56528   VdbeCursor *pC;
56529   UnpackedRecord r;
56530   int nField;
56531   i64 iKey;      /* The rowid we are to seek to */
56532 #endif /* local variables moved into u.az */
56533
56534   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56535   assert( pOp->p2!=0 );
56536   u.az.pC = p->apCsr[pOp->p1];
56537   assert( u.az.pC!=0 );
56538   assert( u.az.pC->pseudoTableReg==0 );
56539   assert( OP_SeekLe == OP_SeekLt+1 );
56540   assert( OP_SeekGe == OP_SeekLt+2 );
56541   assert( OP_SeekGt == OP_SeekLt+3 );
56542   if( u.az.pC->pCursor!=0 ){
56543     u.az.oc = pOp->opcode;
56544     u.az.pC->nullRow = 0;
56545     if( u.az.pC->isTable ){
56546       /* The input value in P3 might be of any type: integer, real, string,
56547       ** blob, or NULL.  But it needs to be an integer before we can do
56548       ** the seek, so covert it. */
56549       pIn3 = &aMem[pOp->p3];
56550       applyNumericAffinity(pIn3);
56551       u.az.iKey = sqlite3VdbeIntValue(pIn3);
56552       u.az.pC->rowidIsValid = 0;
56553
56554       /* If the P3 value could not be converted into an integer without
56555       ** loss of information, then special processing is required... */
56556       if( (pIn3->flags & MEM_Int)==0 ){
56557         if( (pIn3->flags & MEM_Real)==0 ){
56558           /* If the P3 value cannot be converted into any kind of a number,
56559           ** then the seek is not possible, so jump to P2 */
56560           pc = pOp->p2 - 1;
56561           break;
56562         }
56563         /* If we reach this point, then the P3 value must be a floating
56564         ** point number. */
56565         assert( (pIn3->flags & MEM_Real)!=0 );
56566
56567         if( u.az.iKey==SMALLEST_INT64 && (pIn3->r<(double)u.az.iKey || pIn3->r>0) ){
56568           /* The P3 value is too large in magnitude to be expressed as an
56569           ** integer. */
56570           u.az.res = 1;
56571           if( pIn3->r<0 ){
56572             if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
56573               rc = sqlite3BtreeFirst(u.az.pC->pCursor, &u.az.res);
56574               if( rc!=SQLITE_OK ) goto abort_due_to_error;
56575             }
56576           }else{
56577             if( u.az.oc<=OP_SeekLe ){  assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
56578               rc = sqlite3BtreeLast(u.az.pC->pCursor, &u.az.res);
56579               if( rc!=SQLITE_OK ) goto abort_due_to_error;
56580             }
56581           }
56582           if( u.az.res ){
56583             pc = pOp->p2 - 1;
56584           }
56585           break;
56586         }else if( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekGe ){
56587           /* Use the ceiling() function to convert real->int */
56588           if( pIn3->r > (double)u.az.iKey ) u.az.iKey++;
56589         }else{
56590           /* Use the floor() function to convert real->int */
56591           assert( u.az.oc==OP_SeekLe || u.az.oc==OP_SeekGt );
56592           if( pIn3->r < (double)u.az.iKey ) u.az.iKey--;
56593         }
56594       }
56595       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, 0, (u64)u.az.iKey, 0, &u.az.res);
56596       if( rc!=SQLITE_OK ){
56597         goto abort_due_to_error;
56598       }
56599       if( u.az.res==0 ){
56600         u.az.pC->rowidIsValid = 1;
56601         u.az.pC->lastRowid = u.az.iKey;
56602       }
56603     }else{
56604       u.az.nField = pOp->p4.i;
56605       assert( pOp->p4type==P4_INT32 );
56606       assert( u.az.nField>0 );
56607       u.az.r.pKeyInfo = u.az.pC->pKeyInfo;
56608       u.az.r.nField = (u16)u.az.nField;
56609
56610       /* The next line of code computes as follows, only faster:
56611       **   if( u.az.oc==OP_SeekGt || u.az.oc==OP_SeekLe ){
56612       **     u.az.r.flags = UNPACKED_INCRKEY;
56613       **   }else{
56614       **     u.az.r.flags = 0;
56615       **   }
56616       */
56617       u.az.r.flags = (u16)(UNPACKED_INCRKEY * (1 & (u.az.oc - OP_SeekLt)));
56618       assert( u.az.oc!=OP_SeekGt || u.az.r.flags==UNPACKED_INCRKEY );
56619       assert( u.az.oc!=OP_SeekLe || u.az.r.flags==UNPACKED_INCRKEY );
56620       assert( u.az.oc!=OP_SeekGe || u.az.r.flags==0 );
56621       assert( u.az.oc!=OP_SeekLt || u.az.r.flags==0 );
56622
56623       u.az.r.aMem = &aMem[pOp->p3];
56624       ExpandBlob(u.az.r.aMem);
56625       rc = sqlite3BtreeMovetoUnpacked(u.az.pC->pCursor, &u.az.r, 0, 0, &u.az.res);
56626       if( rc!=SQLITE_OK ){
56627         goto abort_due_to_error;
56628       }
56629       u.az.pC->rowidIsValid = 0;
56630     }
56631     u.az.pC->deferredMoveto = 0;
56632     u.az.pC->cacheStatus = CACHE_STALE;
56633 #ifdef SQLITE_TEST
56634     sqlite3_search_count++;
56635 #endif
56636     if( u.az.oc>=OP_SeekGe ){  assert( u.az.oc==OP_SeekGe || u.az.oc==OP_SeekGt );
56637       if( u.az.res<0 || (u.az.res==0 && u.az.oc==OP_SeekGt) ){
56638         rc = sqlite3BtreeNext(u.az.pC->pCursor, &u.az.res);
56639         if( rc!=SQLITE_OK ) goto abort_due_to_error;
56640         u.az.pC->rowidIsValid = 0;
56641       }else{
56642         u.az.res = 0;
56643       }
56644     }else{
56645       assert( u.az.oc==OP_SeekLt || u.az.oc==OP_SeekLe );
56646       if( u.az.res>0 || (u.az.res==0 && u.az.oc==OP_SeekLt) ){
56647         rc = sqlite3BtreePrevious(u.az.pC->pCursor, &u.az.res);
56648         if( rc!=SQLITE_OK ) goto abort_due_to_error;
56649         u.az.pC->rowidIsValid = 0;
56650       }else{
56651         /* u.az.res might be negative because the table is empty.  Check to
56652         ** see if this is the case.
56653         */
56654         u.az.res = sqlite3BtreeEof(u.az.pC->pCursor);
56655       }
56656     }
56657     assert( pOp->p2>0 );
56658     if( u.az.res ){
56659       pc = pOp->p2 - 1;
56660     }
56661   }else{
56662     /* This happens when attempting to open the sqlite3_master table
56663     ** for read access returns SQLITE_EMPTY. In this case always
56664     ** take the jump (since there are no records in the table).
56665     */
56666     pc = pOp->p2 - 1;
56667   }
56668   break;
56669 }
56670
56671 /* Opcode: Seek P1 P2 * * *
56672 **
56673 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
56674 ** for P1 to move so that it points to the rowid given by P2.
56675 **
56676 ** This is actually a deferred seek.  Nothing actually happens until
56677 ** the cursor is used to read a record.  That way, if no reads
56678 ** occur, no unnecessary I/O happens.
56679 */
56680 case OP_Seek: {    /* in2 */
56681 #if 0  /* local variables moved into u.ba */
56682   VdbeCursor *pC;
56683 #endif /* local variables moved into u.ba */
56684
56685   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56686   u.ba.pC = p->apCsr[pOp->p1];
56687   assert( u.ba.pC!=0 );
56688   if( ALWAYS(u.ba.pC->pCursor!=0) ){
56689     assert( u.ba.pC->isTable );
56690     u.ba.pC->nullRow = 0;
56691     pIn2 = &aMem[pOp->p2];
56692     u.ba.pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
56693     u.ba.pC->rowidIsValid = 0;
56694     u.ba.pC->deferredMoveto = 1;
56695   }
56696   break;
56697 }
56698   
56699
56700 /* Opcode: Found P1 P2 P3 P4 *
56701 **
56702 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
56703 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
56704 ** record.
56705 **
56706 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
56707 ** is a prefix of any entry in P1 then a jump is made to P2 and
56708 ** P1 is left pointing at the matching entry.
56709 */
56710 /* Opcode: NotFound P1 P2 P3 P4 *
56711 **
56712 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
56713 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
56714 ** record.
56715 ** 
56716 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
56717 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
56718 ** does contain an entry whose prefix matches the P3/P4 record then control
56719 ** falls through to the next instruction and P1 is left pointing at the
56720 ** matching entry.
56721 **
56722 ** See also: Found, NotExists, IsUnique
56723 */
56724 case OP_NotFound:       /* jump, in3 */
56725 case OP_Found: {        /* jump, in3 */
56726 #if 0  /* local variables moved into u.bb */
56727   int alreadyExists;
56728   VdbeCursor *pC;
56729   int res;
56730   UnpackedRecord *pIdxKey;
56731   UnpackedRecord r;
56732   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*3 + 7];
56733 #endif /* local variables moved into u.bb */
56734
56735 #ifdef SQLITE_TEST
56736   sqlite3_found_count++;
56737 #endif
56738
56739   u.bb.alreadyExists = 0;
56740   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56741   assert( pOp->p4type==P4_INT32 );
56742   u.bb.pC = p->apCsr[pOp->p1];
56743   assert( u.bb.pC!=0 );
56744   pIn3 = &aMem[pOp->p3];
56745   if( ALWAYS(u.bb.pC->pCursor!=0) ){
56746
56747     assert( u.bb.pC->isTable==0 );
56748     if( pOp->p4.i>0 ){
56749       u.bb.r.pKeyInfo = u.bb.pC->pKeyInfo;
56750       u.bb.r.nField = (u16)pOp->p4.i;
56751       u.bb.r.aMem = pIn3;
56752       u.bb.r.flags = UNPACKED_PREFIX_MATCH;
56753       u.bb.pIdxKey = &u.bb.r;
56754     }else{
56755       assert( pIn3->flags & MEM_Blob );
56756       ExpandBlob(pIn3);
56757       u.bb.pIdxKey = sqlite3VdbeRecordUnpack(u.bb.pC->pKeyInfo, pIn3->n, pIn3->z,
56758                                         u.bb.aTempRec, sizeof(u.bb.aTempRec));
56759       if( u.bb.pIdxKey==0 ){
56760         goto no_mem;
56761       }
56762       u.bb.pIdxKey->flags |= UNPACKED_PREFIX_MATCH;
56763     }
56764     rc = sqlite3BtreeMovetoUnpacked(u.bb.pC->pCursor, u.bb.pIdxKey, 0, 0, &u.bb.res);
56765     if( pOp->p4.i==0 ){
56766       sqlite3VdbeDeleteUnpackedRecord(u.bb.pIdxKey);
56767     }
56768     if( rc!=SQLITE_OK ){
56769       break;
56770     }
56771     u.bb.alreadyExists = (u.bb.res==0);
56772     u.bb.pC->deferredMoveto = 0;
56773     u.bb.pC->cacheStatus = CACHE_STALE;
56774   }
56775   if( pOp->opcode==OP_Found ){
56776     if( u.bb.alreadyExists ) pc = pOp->p2 - 1;
56777   }else{
56778     if( !u.bb.alreadyExists ) pc = pOp->p2 - 1;
56779   }
56780   break;
56781 }
56782
56783 /* Opcode: IsUnique P1 P2 P3 P4 *
56784 **
56785 ** Cursor P1 is open on an index b-tree - that is to say, a btree which
56786 ** no data and where the key are records generated by OP_MakeRecord with
56787 ** the list field being the integer ROWID of the entry that the index
56788 ** entry refers to.
56789 **
56790 ** The P3 register contains an integer record number. Call this record 
56791 ** number R. Register P4 is the first in a set of N contiguous registers
56792 ** that make up an unpacked index key that can be used with cursor P1.
56793 ** The value of N can be inferred from the cursor. N includes the rowid
56794 ** value appended to the end of the index record. This rowid value may
56795 ** or may not be the same as R.
56796 **
56797 ** If any of the N registers beginning with register P4 contains a NULL
56798 ** value, jump immediately to P2.
56799 **
56800 ** Otherwise, this instruction checks if cursor P1 contains an entry
56801 ** where the first (N-1) fields match but the rowid value at the end
56802 ** of the index entry is not R. If there is no such entry, control jumps
56803 ** to instruction P2. Otherwise, the rowid of the conflicting index
56804 ** entry is copied to register P3 and control falls through to the next
56805 ** instruction.
56806 **
56807 ** See also: NotFound, NotExists, Found
56808 */
56809 case OP_IsUnique: {        /* jump, in3 */
56810 #if 0  /* local variables moved into u.bc */
56811   u16 ii;
56812   VdbeCursor *pCx;
56813   BtCursor *pCrsr;
56814   u16 nField;
56815   Mem *aMx;
56816   UnpackedRecord r;                  /* B-Tree index search key */
56817   i64 R;                             /* Rowid stored in register P3 */
56818 #endif /* local variables moved into u.bc */
56819
56820   pIn3 = &aMem[pOp->p3];
56821   u.bc.aMx = &aMem[pOp->p4.i];
56822   /* Assert that the values of parameters P1 and P4 are in range. */
56823   assert( pOp->p4type==P4_INT32 );
56824   assert( pOp->p4.i>0 && pOp->p4.i<=p->nMem );
56825   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56826
56827   /* Find the index cursor. */
56828   u.bc.pCx = p->apCsr[pOp->p1];
56829   assert( u.bc.pCx->deferredMoveto==0 );
56830   u.bc.pCx->seekResult = 0;
56831   u.bc.pCx->cacheStatus = CACHE_STALE;
56832   u.bc.pCrsr = u.bc.pCx->pCursor;
56833
56834   /* If any of the values are NULL, take the jump. */
56835   u.bc.nField = u.bc.pCx->pKeyInfo->nField;
56836   for(u.bc.ii=0; u.bc.ii<u.bc.nField; u.bc.ii++){
56837     if( u.bc.aMx[u.bc.ii].flags & MEM_Null ){
56838       pc = pOp->p2 - 1;
56839       u.bc.pCrsr = 0;
56840       break;
56841     }
56842   }
56843   assert( (u.bc.aMx[u.bc.nField].flags & MEM_Null)==0 );
56844
56845   if( u.bc.pCrsr!=0 ){
56846     /* Populate the index search key. */
56847     u.bc.r.pKeyInfo = u.bc.pCx->pKeyInfo;
56848     u.bc.r.nField = u.bc.nField + 1;
56849     u.bc.r.flags = UNPACKED_PREFIX_SEARCH;
56850     u.bc.r.aMem = u.bc.aMx;
56851
56852     /* Extract the value of u.bc.R from register P3. */
56853     sqlite3VdbeMemIntegerify(pIn3);
56854     u.bc.R = pIn3->u.i;
56855
56856     /* Search the B-Tree index. If no conflicting record is found, jump
56857     ** to P2. Otherwise, copy the rowid of the conflicting record to
56858     ** register P3 and fall through to the next instruction.  */
56859     rc = sqlite3BtreeMovetoUnpacked(u.bc.pCrsr, &u.bc.r, 0, 0, &u.bc.pCx->seekResult);
56860     if( (u.bc.r.flags & UNPACKED_PREFIX_SEARCH) || u.bc.r.rowid==u.bc.R ){
56861       pc = pOp->p2 - 1;
56862     }else{
56863       pIn3->u.i = u.bc.r.rowid;
56864     }
56865   }
56866   break;
56867 }
56868
56869 /* Opcode: NotExists P1 P2 P3 * *
56870 **
56871 ** Use the content of register P3 as a integer key.  If a record 
56872 ** with that key does not exist in table of P1, then jump to P2. 
56873 ** If the record does exist, then fall thru.  The cursor is left 
56874 ** pointing to the record if it exists.
56875 **
56876 ** The difference between this operation and NotFound is that this
56877 ** operation assumes the key is an integer and that P1 is a table whereas
56878 ** NotFound assumes key is a blob constructed from MakeRecord and
56879 ** P1 is an index.
56880 **
56881 ** See also: Found, NotFound, IsUnique
56882 */
56883 case OP_NotExists: {        /* jump, in3 */
56884 #if 0  /* local variables moved into u.bd */
56885   VdbeCursor *pC;
56886   BtCursor *pCrsr;
56887   int res;
56888   u64 iKey;
56889 #endif /* local variables moved into u.bd */
56890
56891   pIn3 = &aMem[pOp->p3];
56892   assert( pIn3->flags & MEM_Int );
56893   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56894   u.bd.pC = p->apCsr[pOp->p1];
56895   assert( u.bd.pC!=0 );
56896   assert( u.bd.pC->isTable );
56897   assert( u.bd.pC->pseudoTableReg==0 );
56898   u.bd.pCrsr = u.bd.pC->pCursor;
56899   if( u.bd.pCrsr!=0 ){
56900     u.bd.res = 0;
56901     u.bd.iKey = pIn3->u.i;
56902     rc = sqlite3BtreeMovetoUnpacked(u.bd.pCrsr, 0, u.bd.iKey, 0, &u.bd.res);
56903     u.bd.pC->lastRowid = pIn3->u.i;
56904     u.bd.pC->rowidIsValid = u.bd.res==0 ?1:0;
56905     u.bd.pC->nullRow = 0;
56906     u.bd.pC->cacheStatus = CACHE_STALE;
56907     u.bd.pC->deferredMoveto = 0;
56908     if( u.bd.res!=0 ){
56909       pc = pOp->p2 - 1;
56910       assert( u.bd.pC->rowidIsValid==0 );
56911     }
56912     u.bd.pC->seekResult = u.bd.res;
56913   }else{
56914     /* This happens when an attempt to open a read cursor on the
56915     ** sqlite_master table returns SQLITE_EMPTY.
56916     */
56917     pc = pOp->p2 - 1;
56918     assert( u.bd.pC->rowidIsValid==0 );
56919     u.bd.pC->seekResult = 0;
56920   }
56921   break;
56922 }
56923
56924 /* Opcode: Sequence P1 P2 * * *
56925 **
56926 ** Find the next available sequence number for cursor P1.
56927 ** Write the sequence number into register P2.
56928 ** The sequence number on the cursor is incremented after this
56929 ** instruction.  
56930 */
56931 case OP_Sequence: {           /* out2-prerelease */
56932   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56933   assert( p->apCsr[pOp->p1]!=0 );
56934   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
56935   break;
56936 }
56937
56938
56939 /* Opcode: NewRowid P1 P2 P3 * *
56940 **
56941 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
56942 ** The record number is not previously used as a key in the database
56943 ** table that cursor P1 points to.  The new record number is written
56944 ** written to register P2.
56945 **
56946 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
56947 ** the largest previously generated record number. No new record numbers are
56948 ** allowed to be less than this value. When this value reaches its maximum, 
56949 ** a SQLITE_FULL error is generated. The P3 register is updated with the '
56950 ** generated record number. This P3 mechanism is used to help implement the
56951 ** AUTOINCREMENT feature.
56952 */
56953 case OP_NewRowid: {           /* out2-prerelease */
56954 #if 0  /* local variables moved into u.be */
56955   i64 v;                 /* The new rowid */
56956   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
56957   int res;               /* Result of an sqlite3BtreeLast() */
56958   int cnt;               /* Counter to limit the number of searches */
56959   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
56960   VdbeFrame *pFrame;     /* Root frame of VDBE */
56961 #endif /* local variables moved into u.be */
56962
56963   u.be.v = 0;
56964   u.be.res = 0;
56965   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
56966   u.be.pC = p->apCsr[pOp->p1];
56967   assert( u.be.pC!=0 );
56968   if( NEVER(u.be.pC->pCursor==0) ){
56969     /* The zero initialization above is all that is needed */
56970   }else{
56971     /* The next rowid or record number (different terms for the same
56972     ** thing) is obtained in a two-step algorithm.
56973     **
56974     ** First we attempt to find the largest existing rowid and add one
56975     ** to that.  But if the largest existing rowid is already the maximum
56976     ** positive integer, we have to fall through to the second
56977     ** probabilistic algorithm
56978     **
56979     ** The second algorithm is to select a rowid at random and see if
56980     ** it already exists in the table.  If it does not exist, we have
56981     ** succeeded.  If the random rowid does exist, we select a new one
56982     ** and try again, up to 100 times.
56983     */
56984     assert( u.be.pC->isTable );
56985     u.be.cnt = 0;
56986
56987 #ifdef SQLITE_32BIT_ROWID
56988 #   define MAX_ROWID 0x7fffffff
56989 #else
56990     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
56991     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
56992     ** to provide the constant while making all compilers happy.
56993     */
56994 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
56995 #endif
56996
56997     if( !u.be.pC->useRandomRowid ){
56998       u.be.v = sqlite3BtreeGetCachedRowid(u.be.pC->pCursor);
56999       if( u.be.v==0 ){
57000         rc = sqlite3BtreeLast(u.be.pC->pCursor, &u.be.res);
57001         if( rc!=SQLITE_OK ){
57002           goto abort_due_to_error;
57003         }
57004         if( u.be.res ){
57005           u.be.v = 1;   /* IMP: R-61914-48074 */
57006         }else{
57007           assert( sqlite3BtreeCursorIsValid(u.be.pC->pCursor) );
57008           rc = sqlite3BtreeKeySize(u.be.pC->pCursor, &u.be.v);
57009           assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
57010           if( u.be.v==MAX_ROWID ){
57011             u.be.pC->useRandomRowid = 1;
57012           }else{
57013             u.be.v++;   /* IMP: R-29538-34987 */
57014           }
57015         }
57016       }
57017
57018 #ifndef SQLITE_OMIT_AUTOINCREMENT
57019       if( pOp->p3 ){
57020         /* Assert that P3 is a valid memory cell. */
57021         assert( pOp->p3>0 );
57022         if( p->pFrame ){
57023           for(u.be.pFrame=p->pFrame; u.be.pFrame->pParent; u.be.pFrame=u.be.pFrame->pParent);
57024           /* Assert that P3 is a valid memory cell. */
57025           assert( pOp->p3<=u.be.pFrame->nMem );
57026           u.be.pMem = &u.be.pFrame->aMem[pOp->p3];
57027         }else{
57028           /* Assert that P3 is a valid memory cell. */
57029           assert( pOp->p3<=p->nMem );
57030           u.be.pMem = &aMem[pOp->p3];
57031         }
57032
57033         REGISTER_TRACE(pOp->p3, u.be.pMem);
57034         sqlite3VdbeMemIntegerify(u.be.pMem);
57035         assert( (u.be.pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
57036         if( u.be.pMem->u.i==MAX_ROWID || u.be.pC->useRandomRowid ){
57037           rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
57038           goto abort_due_to_error;
57039         }
57040         if( u.be.v<u.be.pMem->u.i+1 ){
57041           u.be.v = u.be.pMem->u.i + 1;
57042         }
57043         u.be.pMem->u.i = u.be.v;
57044       }
57045 #endif
57046
57047       sqlite3BtreeSetCachedRowid(u.be.pC->pCursor, u.be.v<MAX_ROWID ? u.be.v+1 : 0);
57048     }
57049     if( u.be.pC->useRandomRowid ){
57050       /* IMPLEMENTATION-OF: R-48598-02938 If the largest ROWID is equal to the
57051       ** largest possible integer (9223372036854775807) then the database
57052       ** engine starts picking candidate ROWIDs at random until it finds one
57053       ** that is not previously used.
57054       */
57055       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
57056                              ** an AUTOINCREMENT table. */
57057       u.be.v = db->lastRowid;
57058       u.be.cnt = 0;
57059       do{
57060         if( u.be.cnt==0 && (u.be.v&0xffffff)==u.be.v ){
57061           u.be.v++;
57062         }else{
57063           sqlite3_randomness(sizeof(u.be.v), &u.be.v);
57064           if( u.be.cnt<5 ) u.be.v &= 0xffffff;
57065         }
57066         rc = sqlite3BtreeMovetoUnpacked(u.be.pC->pCursor, 0, (u64)u.be.v, 0, &u.be.res);
57067         u.be.cnt++;
57068       }while( u.be.cnt<100 && rc==SQLITE_OK && u.be.res==0 );
57069       if( rc==SQLITE_OK && u.be.res==0 ){
57070         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
57071         goto abort_due_to_error;
57072       }
57073     }
57074     u.be.pC->rowidIsValid = 0;
57075     u.be.pC->deferredMoveto = 0;
57076     u.be.pC->cacheStatus = CACHE_STALE;
57077   }
57078   pOut->u.i = u.be.v;
57079   break;
57080 }
57081
57082 /* Opcode: Insert P1 P2 P3 P4 P5
57083 **
57084 ** Write an entry into the table of cursor P1.  A new entry is
57085 ** created if it doesn't already exist or the data for an existing
57086 ** entry is overwritten.  The data is the value MEM_Blob stored in register
57087 ** number P2. The key is stored in register P3. The key must
57088 ** be a MEM_Int.
57089 **
57090 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
57091 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
57092 ** then rowid is stored for subsequent return by the
57093 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
57094 **
57095 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
57096 ** the last seek operation (OP_NotExists) was a success, then this
57097 ** operation will not attempt to find the appropriate row before doing
57098 ** the insert but will instead overwrite the row that the cursor is
57099 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
57100 ** has already positioned the cursor correctly.  This is an optimization
57101 ** that boosts performance by avoiding redundant seeks.
57102 **
57103 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
57104 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
57105 ** is part of an INSERT operation.  The difference is only important to
57106 ** the update hook.
57107 **
57108 ** Parameter P4 may point to a string containing the table-name, or
57109 ** may be NULL. If it is not NULL, then the update-hook 
57110 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
57111 **
57112 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
57113 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
57114 ** and register P2 becomes ephemeral.  If the cursor is changed, the
57115 ** value of register P2 will then change.  Make sure this does not
57116 ** cause any problems.)
57117 **
57118 ** This instruction only works on tables.  The equivalent instruction
57119 ** for indices is OP_IdxInsert.
57120 */
57121 /* Opcode: InsertInt P1 P2 P3 P4 P5
57122 **
57123 ** This works exactly like OP_Insert except that the key is the
57124 ** integer value P3, not the value of the integer stored in register P3.
57125 */
57126 case OP_Insert: 
57127 case OP_InsertInt: {
57128 #if 0  /* local variables moved into u.bf */
57129   Mem *pData;       /* MEM cell holding data for the record to be inserted */
57130   Mem *pKey;        /* MEM cell holding key  for the record */
57131   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
57132   VdbeCursor *pC;   /* Cursor to table into which insert is written */
57133   int nZero;        /* Number of zero-bytes to append */
57134   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
57135   const char *zDb;  /* database name - used by the update hook */
57136   const char *zTbl; /* Table name - used by the opdate hook */
57137   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
57138 #endif /* local variables moved into u.bf */
57139
57140   u.bf.pData = &aMem[pOp->p2];
57141   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
57142   u.bf.pC = p->apCsr[pOp->p1];
57143   assert( u.bf.pC!=0 );
57144   assert( u.bf.pC->pCursor!=0 );
57145   assert( u.bf.pC->pseudoTableReg==0 );
57146   assert( u.bf.pC->isTable );
57147   REGISTER_TRACE(pOp->p2, u.bf.pData);
57148
57149   if( pOp->opcode==OP_Insert ){
57150     u.bf.pKey = &aMem[pOp->p3];
57151     assert( u.bf.pKey->flags & MEM_Int );
57152     REGISTER_TRACE(pOp->p3, u.bf.pKey);
57153     u.bf.iKey = u.bf.pKey->u.i;
57154   }else{
57155     assert( pOp->opcode==OP_InsertInt );
57156     u.bf.iKey = pOp->p3;
57157   }
57158
57159   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
57160   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = u.bf.iKey;
57161   if( u.bf.pData->flags & MEM_Null ){
57162     u.bf.pData->z = 0;
57163     u.bf.pData->n = 0;
57164   }else{
57165     assert( u.bf.pData->flags & (MEM_Blob|MEM_Str) );
57166   }
57167   u.bf.seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bf.pC->seekResult : 0);
57168   if( u.bf.pData->flags & MEM_Zero ){
57169     u.bf.nZero = u.bf.pData->u.nZero;
57170   }else{
57171     u.bf.nZero = 0;
57172   }
57173   sqlite3BtreeSetCachedRowid(u.bf.pC->pCursor, 0);
57174   rc = sqlite3BtreeInsert(u.bf.pC->pCursor, 0, u.bf.iKey,
57175                           u.bf.pData->z, u.bf.pData->n, u.bf.nZero,
57176                           pOp->p5 & OPFLAG_APPEND, u.bf.seekResult
57177   );
57178   u.bf.pC->rowidIsValid = 0;
57179   u.bf.pC->deferredMoveto = 0;
57180   u.bf.pC->cacheStatus = CACHE_STALE;
57181
57182   /* Invoke the update-hook if required. */
57183   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
57184     u.bf.zDb = db->aDb[u.bf.pC->iDb].zName;
57185     u.bf.zTbl = pOp->p4.z;
57186     u.bf.op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
57187     assert( u.bf.pC->isTable );
57188     db->xUpdateCallback(db->pUpdateArg, u.bf.op, u.bf.zDb, u.bf.zTbl, u.bf.iKey);
57189     assert( u.bf.pC->iDb>=0 );
57190   }
57191   break;
57192 }
57193
57194 /* Opcode: Delete P1 P2 * P4 *
57195 **
57196 ** Delete the record at which the P1 cursor is currently pointing.
57197 **
57198 ** The cursor will be left pointing at either the next or the previous
57199 ** record in the table. If it is left pointing at the next record, then
57200 ** the next Next instruction will be a no-op.  Hence it is OK to delete
57201 ** a record from within an Next loop.
57202 **
57203 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
57204 ** incremented (otherwise not).
57205 **
57206 ** P1 must not be pseudo-table.  It has to be a real table with
57207 ** multiple rows.
57208 **
57209 ** If P4 is not NULL, then it is the name of the table that P1 is
57210 ** pointing to.  The update hook will be invoked, if it exists.
57211 ** If P4 is not NULL then the P1 cursor must have been positioned
57212 ** using OP_NotFound prior to invoking this opcode.
57213 */
57214 case OP_Delete: {
57215 #if 0  /* local variables moved into u.bg */
57216   i64 iKey;
57217   VdbeCursor *pC;
57218 #endif /* local variables moved into u.bg */
57219
57220   u.bg.iKey = 0;
57221   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
57222   u.bg.pC = p->apCsr[pOp->p1];
57223   assert( u.bg.pC!=0 );
57224   assert( u.bg.pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
57225
57226   /* If the update-hook will be invoked, set u.bg.iKey to the rowid of the
57227   ** row being deleted.
57228   */
57229   if( db->xUpdateCallback && pOp->p4.z ){
57230     assert( u.bg.pC->isTable );
57231     assert( u.bg.pC->rowidIsValid );  /* lastRowid set by previous OP_NotFound */
57232     u.bg.iKey = u.bg.pC->lastRowid;
57233   }
57234
57235   /* The OP_Delete opcode always follows an OP_NotExists or OP_Last or
57236   ** OP_Column on the same table without any intervening operations that
57237   ** might move or invalidate the cursor.  Hence cursor u.bg.pC is always pointing
57238   ** to the row to be deleted and the sqlite3VdbeCursorMoveto() operation
57239   ** below is always a no-op and cannot fail.  We will run it anyhow, though,
57240   ** to guard against future changes to the code generator.
57241   **/
57242   assert( u.bg.pC->deferredMoveto==0 );
57243   rc = sqlite3VdbeCursorMoveto(u.bg.pC);
57244   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
57245
57246   sqlite3BtreeSetCachedRowid(u.bg.pC->pCursor, 0);
57247   rc = sqlite3BtreeDelete(u.bg.pC->pCursor);
57248   u.bg.pC->cacheStatus = CACHE_STALE;
57249
57250   /* Invoke the update-hook if required. */
57251   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
57252     const char *zDb = db->aDb[u.bg.pC->iDb].zName;
57253     const char *zTbl = pOp->p4.z;
57254     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE, zDb, zTbl, u.bg.iKey);
57255     assert( u.bg.pC->iDb>=0 );
57256   }
57257   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
57258   break;
57259 }
57260 /* Opcode: ResetCount * * * * *
57261 **
57262 ** The value of the change counter is copied to the database handle
57263 ** change counter (returned by subsequent calls to sqlite3_changes()).
57264 ** Then the VMs internal change counter resets to 0.
57265 ** This is used by trigger programs.
57266 */
57267 case OP_ResetCount: {
57268   sqlite3VdbeSetChanges(db, p->nChange);
57269   p->nChange = 0;
57270   break;
57271 }
57272
57273 /* Opcode: RowData P1 P2 * * *
57274 **
57275 ** Write into register P2 the complete row data for cursor P1.
57276 ** There is no interpretation of the data.  
57277 ** It is just copied onto the P2 register exactly as 
57278 ** it is found in the database file.
57279 **
57280 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
57281 ** of a real table, not a pseudo-table.
57282 */
57283 /* Opcode: RowKey P1 P2 * * *
57284 **
57285 ** Write into register P2 the complete row key for cursor P1.
57286 ** There is no interpretation of the data.  
57287 ** The key is copied onto the P3 register exactly as 
57288 ** it is found in the database file.
57289 **
57290 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
57291 ** of a real table, not a pseudo-table.
57292 */
57293 case OP_RowKey:
57294 case OP_RowData: {
57295 #if 0  /* local variables moved into u.bh */
57296   VdbeCursor *pC;
57297   BtCursor *pCrsr;
57298   u32 n;
57299   i64 n64;
57300 #endif /* local variables moved into u.bh */
57301
57302   pOut = &aMem[pOp->p2];
57303
57304   /* Note that RowKey and RowData are really exactly the same instruction */
57305   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
57306   u.bh.pC = p->apCsr[pOp->p1];
57307   assert( u.bh.pC->isTable || pOp->opcode==OP_RowKey );
57308   assert( u.bh.pC->isIndex || pOp->opcode==OP_RowData );
57309   assert( u.bh.pC!=0 );
57310   assert( u.bh.pC->nullRow==0 );
57311   assert( u.bh.pC->pseudoTableReg==0 );
57312   assert( u.bh.pC->pCursor!=0 );
57313   u.bh.pCrsr = u.bh.pC->pCursor;
57314   assert( sqlite3BtreeCursorIsValid(u.bh.pCrsr) );
57315
57316   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
57317   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
57318   ** the cursor.  Hence the following sqlite3VdbeCursorMoveto() call is always
57319   ** a no-op and can never fail.  But we leave it in place as a safety.
57320   */
57321   assert( u.bh.pC->deferredMoveto==0 );
57322   rc = sqlite3VdbeCursorMoveto(u.bh.pC);
57323   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
57324
57325   if( u.bh.pC->isIndex ){
57326     assert( !u.bh.pC->isTable );
57327     rc = sqlite3BtreeKeySize(u.bh.pCrsr, &u.bh.n64);
57328     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
57329     if( u.bh.n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
57330       goto too_big;
57331     }
57332     u.bh.n = (u32)u.bh.n64;
57333   }else{
57334     rc = sqlite3BtreeDataSize(u.bh.pCrsr, &u.bh.n);
57335     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
57336     if( u.bh.n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
57337       goto too_big;
57338     }
57339   }
57340   if( sqlite3VdbeMemGrow(pOut, u.bh.n, 0) ){
57341     goto no_mem;
57342   }
57343   pOut->n = u.bh.n;
57344   MemSetTypeFlag(pOut, MEM_Blob);
57345   if( u.bh.pC->isIndex ){
57346     rc = sqlite3BtreeKey(u.bh.pCrsr, 0, u.bh.n, pOut->z);
57347   }else{
57348     rc = sqlite3BtreeData(u.bh.pCrsr, 0, u.bh.n, pOut->z);
57349   }
57350   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
57351   UPDATE_MAX_BLOBSIZE(pOut);
57352   break;
57353 }
57354
57355 /* Opcode: Rowid P1 P2 * * *
57356 **
57357 ** Store in register P2 an integer which is the key of the table entry that
57358 ** P1 is currently point to.
57359 **
57360 ** P1 can be either an ordinary table or a virtual table.  There used to
57361 ** be a separate OP_VRowid opcode for use with virtual tables, but this
57362 ** one opcode now works for both table types.
57363 */
57364 case OP_Rowid: {                 /* out2-prerelease */
57365 #if 0  /* local variables moved into u.bi */
57366   VdbeCursor *pC;
57367   i64 v;
57368   sqlite3_vtab *pVtab;
57369   const sqlite3_module *pModule;
57370 #endif /* local variables moved into u.bi */
57371
57372   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
57373   u.bi.pC = p->apCsr[pOp->p1];
57374   assert( u.bi.pC!=0 );
57375   assert( u.bi.pC->pseudoTableReg==0 );
57376   if( u.bi.pC->nullRow ){
57377     pOut->flags = MEM_Null;
57378     break;
57379   }else if( u.bi.pC->deferredMoveto ){
57380     u.bi.v = u.bi.pC->movetoTarget;
57381 #ifndef SQLITE_OMIT_VIRTUALTABLE
57382   }else if( u.bi.pC->pVtabCursor ){
57383     u.bi.pVtab = u.bi.pC->pVtabCursor->pVtab;
57384     u.bi.pModule = u.bi.pVtab->pModule;
57385     assert( u.bi.pModule->xRowid );
57386     rc = u.bi.pModule->xRowid(u.bi.pC->pVtabCursor, &u.bi.v);
57387     sqlite3DbFree(db, p->zErrMsg);
57388     p->zErrMsg = u.bi.pVtab->zErrMsg;
57389     u.bi.pVtab->zErrMsg = 0;
57390 #endif /* SQLITE_OMIT_VIRTUALTABLE */
57391   }else{
57392     assert( u.bi.pC->pCursor!=0 );
57393     rc = sqlite3VdbeCursorMoveto(u.bi.pC);
57394     if( rc ) goto abort_due_to_error;
57395     if( u.bi.pC->rowidIsValid ){
57396       u.bi.v = u.bi.pC->lastRowid;
57397     }else{
57398       rc = sqlite3BtreeKeySize(u.bi.pC->pCursor, &u.bi.v);
57399       assert( rc==SQLITE_OK );  /* Always so because of CursorMoveto() above */
57400     }
57401   }
57402   pOut->u.i = u.bi.v;
57403   break;
57404 }
57405
57406 /* Opcode: NullRow P1 * * * *
57407 **
57408 ** Move the cursor P1 to a null row.  Any OP_Column operations
57409 ** that occur while the cursor is on the null row will always
57410 ** write a NULL.
57411 */
57412 case OP_NullRow: {
57413 #if 0  /* local variables moved into u.bj */
57414   VdbeCursor *pC;
57415 #endif /* local variables moved into u.bj */
57416
57417   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
57418   u.bj.pC = p->apCsr[pOp->p1];
57419   assert( u.bj.pC!=0 );
57420   u.bj.pC->nullRow = 1;
57421   u.bj.pC->rowidIsValid = 0;
57422   if( u.bj.pC->pCursor ){
57423     sqlite3BtreeClearCursor(u.bj.pC->pCursor);
57424   }
57425   break;
57426 }
57427
57428 /* Opcode: Last P1 P2 * * *
57429 **
57430 ** The next use of the Rowid or Column or Next instruction for P1 
57431 ** will refer to the last entry in the database table or index.
57432 ** If the table or index is empty and P2>0, then jump immediately to P2.
57433 ** If P2 is 0 or if the table or index is not empty, fall through
57434 ** to the following instruction.
57435 */
57436 case OP_Last: {        /* jump */
57437 #if 0  /* local variables moved into u.bk */
57438   VdbeCursor *pC;
57439   BtCursor *pCrsr;
57440   int res;
57441 #endif /* local variables moved into u.bk */
57442
57443   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
57444   u.bk.pC = p->apCsr[pOp->p1];
57445   assert( u.bk.pC!=0 );
57446   u.bk.pCrsr = u.bk.pC->pCursor;
57447   if( u.bk.pCrsr==0 ){
57448     u.bk.res = 1;
57449   }else{
57450     rc = sqlite3BtreeLast(u.bk.pCrsr, &u.bk.res);
57451   }
57452   u.bk.pC->nullRow = (u8)u.bk.res;
57453   u.bk.pC->deferredMoveto = 0;
57454   u.bk.pC->rowidIsValid = 0;
57455   u.bk.pC->cacheStatus = CACHE_STALE;
57456   if( pOp->p2>0 && u.bk.res ){
57457     pc = pOp->p2 - 1;
57458   }
57459   break;
57460 }
57461
57462
57463 /* Opcode: Sort P1 P2 * * *
57464 **
57465 ** This opcode does exactly the same thing as OP_Rewind except that
57466 ** it increments an undocumented global variable used for testing.
57467 **
57468 ** Sorting is accomplished by writing records into a sorting index,
57469 ** then rewinding that index and playing it back from beginning to
57470 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
57471 ** rewinding so that the global variable will be incremented and
57472 ** regression tests can determine whether or not the optimizer is
57473 ** correctly optimizing out sorts.
57474 */
57475 case OP_Sort: {        /* jump */
57476 #ifdef SQLITE_TEST
57477   sqlite3_sort_count++;
57478   sqlite3_search_count--;
57479 #endif
57480   p->aCounter[SQLITE_STMTSTATUS_SORT-1]++;
57481   /* Fall through into OP_Rewind */
57482 }
57483 /* Opcode: Rewind P1 P2 * * *
57484 **
57485 ** The next use of the Rowid or Column or Next instruction for P1 
57486 ** will refer to the first entry in the database table or index.
57487 ** If the table or index is empty and P2>0, then jump immediately to P2.
57488 ** If P2 is 0 or if the table or index is not empty, fall through
57489 ** to the following instruction.
57490 */
57491 case OP_Rewind: {        /* jump */
57492 #if 0  /* local variables moved into u.bl */
57493   VdbeCursor *pC;
57494   BtCursor *pCrsr;
57495   int res;
57496 #endif /* local variables moved into u.bl */
57497
57498   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
57499   u.bl.pC = p->apCsr[pOp->p1];
57500   assert( u.bl.pC!=0 );
57501   if( (u.bl.pCrsr = u.bl.pC->pCursor)!=0 ){
57502     rc = sqlite3BtreeFirst(u.bl.pCrsr, &u.bl.res);
57503     u.bl.pC->atFirst = u.bl.res==0 ?1:0;
57504     u.bl.pC->deferredMoveto = 0;
57505     u.bl.pC->cacheStatus = CACHE_STALE;
57506     u.bl.pC->rowidIsValid = 0;
57507   }else{
57508     u.bl.res = 1;
57509   }
57510   u.bl.pC->nullRow = (u8)u.bl.res;
57511   assert( pOp->p2>0 && pOp->p2<p->nOp );
57512   if( u.bl.res ){
57513     pc = pOp->p2 - 1;
57514   }
57515   break;
57516 }
57517
57518 /* Opcode: Next P1 P2 * * *
57519 **
57520 ** Advance cursor P1 so that it points to the next key/data pair in its
57521 ** table or index.  If there are no more key/value pairs then fall through
57522 ** to the following instruction.  But if the cursor advance was successful,
57523 ** jump immediately to P2.
57524 **
57525 ** The P1 cursor must be for a real table, not a pseudo-table.
57526 **
57527 ** See also: Prev
57528 */
57529 /* Opcode: Prev P1 P2 * * *
57530 **
57531 ** Back up cursor P1 so that it points to the previous key/data pair in its
57532 ** table or index.  If there is no previous key/value pairs then fall through
57533 ** to the following instruction.  But if the cursor backup was successful,
57534 ** jump immediately to P2.
57535 **
57536 ** The P1 cursor must be for a real table, not a pseudo-table.
57537 */
57538 case OP_Prev:          /* jump */
57539 case OP_Next: {        /* jump */
57540 #if 0  /* local variables moved into u.bm */
57541   VdbeCursor *pC;
57542   BtCursor *pCrsr;
57543   int res;
57544 #endif /* local variables moved into u.bm */
57545
57546   CHECK_FOR_INTERRUPT;
57547   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
57548   u.bm.pC = p->apCsr[pOp->p1];
57549   if( u.bm.pC==0 ){
57550     break;  /* See ticket #2273 */
57551   }
57552   u.bm.pCrsr = u.bm.pC->pCursor;
57553   if( u.bm.pCrsr==0 ){
57554     u.bm.pC->nullRow = 1;
57555     break;
57556   }
57557   u.bm.res = 1;
57558   assert( u.bm.pC->deferredMoveto==0 );
57559   rc = pOp->opcode==OP_Next ? sqlite3BtreeNext(u.bm.pCrsr, &u.bm.res) :
57560                               sqlite3BtreePrevious(u.bm.pCrsr, &u.bm.res);
57561   u.bm.pC->nullRow = (u8)u.bm.res;
57562   u.bm.pC->cacheStatus = CACHE_STALE;
57563   if( u.bm.res==0 ){
57564     pc = pOp->p2 - 1;
57565     if( pOp->p5 ) p->aCounter[pOp->p5-1]++;
57566 #ifdef SQLITE_TEST
57567     sqlite3_search_count++;
57568 #endif
57569   }
57570   u.bm.pC->rowidIsValid = 0;
57571   break;
57572 }
57573
57574 /* Opcode: IdxInsert P1 P2 P3 * P5
57575 **
57576 ** Register P2 holds a SQL index key made using the
57577 ** MakeRecord instructions.  This opcode writes that key
57578 ** into the index P1.  Data for the entry is nil.
57579 **
57580 ** P3 is a flag that provides a hint to the b-tree layer that this
57581 ** insert is likely to be an append.
57582 **
57583 ** This instruction only works for indices.  The equivalent instruction
57584 ** for tables is OP_Insert.
57585 */
57586 case OP_IdxInsert: {        /* in2 */
57587 #if 0  /* local variables moved into u.bn */
57588   VdbeCursor *pC;
57589   BtCursor *pCrsr;
57590   int nKey;
57591   const char *zKey;
57592 #endif /* local variables moved into u.bn */
57593
57594   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
57595   u.bn.pC = p->apCsr[pOp->p1];
57596   assert( u.bn.pC!=0 );
57597   pIn2 = &aMem[pOp->p2];
57598   assert( pIn2->flags & MEM_Blob );
57599   u.bn.pCrsr = u.bn.pC->pCursor;
57600   if( ALWAYS(u.bn.pCrsr!=0) ){
57601     assert( u.bn.pC->isTable==0 );
57602     rc = ExpandBlob(pIn2);
57603     if( rc==SQLITE_OK ){
57604       u.bn.nKey = pIn2->n;
57605       u.bn.zKey = pIn2->z;
57606       rc = sqlite3BtreeInsert(u.bn.pCrsr, u.bn.zKey, u.bn.nKey, "", 0, 0, pOp->p3,
57607           ((pOp->p5 & OPFLAG_USESEEKRESULT) ? u.bn.pC->seekResult : 0)
57608       );
57609       assert( u.bn.pC->deferredMoveto==0 );
57610       u.bn.pC->cacheStatus = CACHE_STALE;
57611     }
57612   }
57613   break;
57614 }
57615
57616 /* Opcode: IdxDelete P1 P2 P3 * *
57617 **
57618 ** The content of P3 registers starting at register P2 form
57619 ** an unpacked index key. This opcode removes that entry from the 
57620 ** index opened by cursor P1.
57621 */
57622 case OP_IdxDelete: {
57623 #if 0  /* local variables moved into u.bo */
57624   VdbeCursor *pC;
57625   BtCursor *pCrsr;
57626   int res;
57627   UnpackedRecord r;
57628 #endif /* local variables moved into u.bo */
57629
57630   assert( pOp->p3>0 );
57631   assert( pOp->p2>0 && pOp->p2+pOp->p3<=p->nMem+1 );
57632   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
57633   u.bo.pC = p->apCsr[pOp->p1];
57634   assert( u.bo.pC!=0 );
57635   u.bo.pCrsr = u.bo.pC->pCursor;
57636   if( ALWAYS(u.bo.pCrsr!=0) ){
57637     u.bo.r.pKeyInfo = u.bo.pC->pKeyInfo;
57638     u.bo.r.nField = (u16)pOp->p3;
57639     u.bo.r.flags = 0;
57640     u.bo.r.aMem = &aMem[pOp->p2];
57641     rc = sqlite3BtreeMovetoUnpacked(u.bo.pCrsr, &u.bo.r, 0, 0, &u.bo.res);
57642     if( rc==SQLITE_OK && u.bo.res==0 ){
57643       rc = sqlite3BtreeDelete(u.bo.pCrsr);
57644     }
57645     assert( u.bo.pC->deferredMoveto==0 );
57646     u.bo.pC->cacheStatus = CACHE_STALE;
57647   }
57648   break;
57649 }
57650
57651 /* Opcode: IdxRowid P1 P2 * * *
57652 **
57653 ** Write into register P2 an integer which is the last entry in the record at
57654 ** the end of the index key pointed to by cursor P1.  This integer should be
57655 ** the rowid of the table entry to which this index entry points.
57656 **
57657 ** See also: Rowid, MakeRecord.
57658 */
57659 case OP_IdxRowid: {              /* out2-prerelease */
57660 #if 0  /* local variables moved into u.bp */
57661   BtCursor *pCrsr;
57662   VdbeCursor *pC;
57663   i64 rowid;
57664 #endif /* local variables moved into u.bp */
57665
57666   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
57667   u.bp.pC = p->apCsr[pOp->p1];
57668   assert( u.bp.pC!=0 );
57669   u.bp.pCrsr = u.bp.pC->pCursor;
57670   pOut->flags = MEM_Null;
57671   if( ALWAYS(u.bp.pCrsr!=0) ){
57672     rc = sqlite3VdbeCursorMoveto(u.bp.pC);
57673     if( NEVER(rc) ) goto abort_due_to_error;
57674     assert( u.bp.pC->deferredMoveto==0 );
57675     assert( u.bp.pC->isTable==0 );
57676     if( !u.bp.pC->nullRow ){
57677       rc = sqlite3VdbeIdxRowid(db, u.bp.pCrsr, &u.bp.rowid);
57678       if( rc!=SQLITE_OK ){
57679         goto abort_due_to_error;
57680       }
57681       pOut->u.i = u.bp.rowid;
57682       pOut->flags = MEM_Int;
57683     }
57684   }
57685   break;
57686 }
57687
57688 /* Opcode: IdxGE P1 P2 P3 P4 P5
57689 **
57690 ** The P4 register values beginning with P3 form an unpacked index 
57691 ** key that omits the ROWID.  Compare this key value against the index 
57692 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
57693 **
57694 ** If the P1 index entry is greater than or equal to the key value
57695 ** then jump to P2.  Otherwise fall through to the next instruction.
57696 **
57697 ** If P5 is non-zero then the key value is increased by an epsilon 
57698 ** prior to the comparison.  This make the opcode work like IdxGT except
57699 ** that if the key from register P3 is a prefix of the key in the cursor,
57700 ** the result is false whereas it would be true with IdxGT.
57701 */
57702 /* Opcode: IdxLT P1 P2 P3 * P5
57703 **
57704 ** The P4 register values beginning with P3 form an unpacked index 
57705 ** key that omits the ROWID.  Compare this key value against the index 
57706 ** that P1 is currently pointing to, ignoring the ROWID on the P1 index.
57707 **
57708 ** If the P1 index entry is less than the key value then jump to P2.
57709 ** Otherwise fall through to the next instruction.
57710 **
57711 ** If P5 is non-zero then the key value is increased by an epsilon prior 
57712 ** to the comparison.  This makes the opcode work like IdxLE.
57713 */
57714 case OP_IdxLT:          /* jump */
57715 case OP_IdxGE: {        /* jump */
57716 #if 0  /* local variables moved into u.bq */
57717   VdbeCursor *pC;
57718   int res;
57719   UnpackedRecord r;
57720 #endif /* local variables moved into u.bq */
57721
57722   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
57723   u.bq.pC = p->apCsr[pOp->p1];
57724   assert( u.bq.pC!=0 );
57725   if( ALWAYS(u.bq.pC->pCursor!=0) ){
57726     assert( u.bq.pC->deferredMoveto==0 );
57727     assert( pOp->p5==0 || pOp->p5==1 );
57728     assert( pOp->p4type==P4_INT32 );
57729     u.bq.r.pKeyInfo = u.bq.pC->pKeyInfo;
57730     u.bq.r.nField = (u16)pOp->p4.i;
57731     if( pOp->p5 ){
57732       u.bq.r.flags = UNPACKED_INCRKEY | UNPACKED_IGNORE_ROWID;
57733     }else{
57734       u.bq.r.flags = UNPACKED_IGNORE_ROWID;
57735     }
57736     u.bq.r.aMem = &aMem[pOp->p3];
57737     rc = sqlite3VdbeIdxKeyCompare(u.bq.pC, &u.bq.r, &u.bq.res);
57738     if( pOp->opcode==OP_IdxLT ){
57739       u.bq.res = -u.bq.res;
57740     }else{
57741       assert( pOp->opcode==OP_IdxGE );
57742       u.bq.res++;
57743     }
57744     if( u.bq.res>0 ){
57745       pc = pOp->p2 - 1 ;
57746     }
57747   }
57748   break;
57749 }
57750
57751 /* Opcode: Destroy P1 P2 P3 * *
57752 **
57753 ** Delete an entire database table or index whose root page in the database
57754 ** file is given by P1.
57755 **
57756 ** The table being destroyed is in the main database file if P3==0.  If
57757 ** P3==1 then the table to be clear is in the auxiliary database file
57758 ** that is used to store tables create using CREATE TEMPORARY TABLE.
57759 **
57760 ** If AUTOVACUUM is enabled then it is possible that another root page
57761 ** might be moved into the newly deleted root page in order to keep all
57762 ** root pages contiguous at the beginning of the database.  The former
57763 ** value of the root page that moved - its value before the move occurred -
57764 ** is stored in register P2.  If no page 
57765 ** movement was required (because the table being dropped was already 
57766 ** the last one in the database) then a zero is stored in register P2.
57767 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
57768 **
57769 ** See also: Clear
57770 */
57771 case OP_Destroy: {     /* out2-prerelease */
57772 #if 0  /* local variables moved into u.br */
57773   int iMoved;
57774   int iCnt;
57775   Vdbe *pVdbe;
57776   int iDb;
57777 #endif /* local variables moved into u.br */
57778 #ifndef SQLITE_OMIT_VIRTUALTABLE
57779   u.br.iCnt = 0;
57780   for(u.br.pVdbe=db->pVdbe; u.br.pVdbe; u.br.pVdbe = u.br.pVdbe->pNext){
57781     if( u.br.pVdbe->magic==VDBE_MAGIC_RUN && u.br.pVdbe->inVtabMethod<2 && u.br.pVdbe->pc>=0 ){
57782       u.br.iCnt++;
57783     }
57784   }
57785 #else
57786   u.br.iCnt = db->activeVdbeCnt;
57787 #endif
57788   pOut->flags = MEM_Null;
57789   if( u.br.iCnt>1 ){
57790     rc = SQLITE_LOCKED;
57791     p->errorAction = OE_Abort;
57792   }else{
57793     u.br.iDb = pOp->p3;
57794     assert( u.br.iCnt==1 );
57795     assert( (p->btreeMask & (1<<u.br.iDb))!=0 );
57796     rc = sqlite3BtreeDropTable(db->aDb[u.br.iDb].pBt, pOp->p1, &u.br.iMoved);
57797     pOut->flags = MEM_Int;
57798     pOut->u.i = u.br.iMoved;
57799 #ifndef SQLITE_OMIT_AUTOVACUUM
57800     if( rc==SQLITE_OK && u.br.iMoved!=0 ){
57801       sqlite3RootPageMoved(&db->aDb[u.br.iDb], u.br.iMoved, pOp->p1);
57802       resetSchemaOnFault = 1;
57803     }
57804 #endif
57805   }
57806   break;
57807 }
57808
57809 /* Opcode: Clear P1 P2 P3
57810 **
57811 ** Delete all contents of the database table or index whose root page
57812 ** in the database file is given by P1.  But, unlike Destroy, do not
57813 ** remove the table or index from the database file.
57814 **
57815 ** The table being clear is in the main database file if P2==0.  If
57816 ** P2==1 then the table to be clear is in the auxiliary database file
57817 ** that is used to store tables create using CREATE TEMPORARY TABLE.
57818 **
57819 ** If the P3 value is non-zero, then the table referred to must be an
57820 ** intkey table (an SQL table, not an index). In this case the row change 
57821 ** count is incremented by the number of rows in the table being cleared. 
57822 ** If P3 is greater than zero, then the value stored in register P3 is
57823 ** also incremented by the number of rows in the table being cleared.
57824 **
57825 ** See also: Destroy
57826 */
57827 case OP_Clear: {
57828 #if 0  /* local variables moved into u.bs */
57829   int nChange;
57830 #endif /* local variables moved into u.bs */
57831
57832   u.bs.nChange = 0;
57833   assert( (p->btreeMask & (1<<pOp->p2))!=0 );
57834   rc = sqlite3BtreeClearTable(
57835       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &u.bs.nChange : 0)
57836   );
57837   if( pOp->p3 ){
57838     p->nChange += u.bs.nChange;
57839     if( pOp->p3>0 ){
57840       aMem[pOp->p3].u.i += u.bs.nChange;
57841     }
57842   }
57843   break;
57844 }
57845
57846 /* Opcode: CreateTable P1 P2 * * *
57847 **
57848 ** Allocate a new table in the main database file if P1==0 or in the
57849 ** auxiliary database file if P1==1 or in an attached database if
57850 ** P1>1.  Write the root page number of the new table into
57851 ** register P2
57852 **
57853 ** The difference between a table and an index is this:  A table must
57854 ** have a 4-byte integer key and can have arbitrary data.  An index
57855 ** has an arbitrary key but no data.
57856 **
57857 ** See also: CreateIndex
57858 */
57859 /* Opcode: CreateIndex P1 P2 * * *
57860 **
57861 ** Allocate a new index in the main database file if P1==0 or in the
57862 ** auxiliary database file if P1==1 or in an attached database if
57863 ** P1>1.  Write the root page number of the new table into
57864 ** register P2.
57865 **
57866 ** See documentation on OP_CreateTable for additional information.
57867 */
57868 case OP_CreateIndex:            /* out2-prerelease */
57869 case OP_CreateTable: {          /* out2-prerelease */
57870 #if 0  /* local variables moved into u.bt */
57871   int pgno;
57872   int flags;
57873   Db *pDb;
57874 #endif /* local variables moved into u.bt */
57875
57876   u.bt.pgno = 0;
57877   assert( pOp->p1>=0 && pOp->p1<db->nDb );
57878   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
57879   u.bt.pDb = &db->aDb[pOp->p1];
57880   assert( u.bt.pDb->pBt!=0 );
57881   if( pOp->opcode==OP_CreateTable ){
57882     /* u.bt.flags = BTREE_INTKEY; */
57883     u.bt.flags = BTREE_LEAFDATA|BTREE_INTKEY;
57884   }else{
57885     u.bt.flags = BTREE_ZERODATA;
57886   }
57887   rc = sqlite3BtreeCreateTable(u.bt.pDb->pBt, &u.bt.pgno, u.bt.flags);
57888   pOut->u.i = u.bt.pgno;
57889   break;
57890 }
57891
57892 /* Opcode: ParseSchema P1 P2 * P4 *
57893 **
57894 ** Read and parse all entries from the SQLITE_MASTER table of database P1
57895 ** that match the WHERE clause P4.  P2 is the "force" flag.   Always do
57896 ** the parsing if P2 is true.  If P2 is false, then this routine is a
57897 ** no-op if the schema is not currently loaded.  In other words, if P2
57898 ** is false, the SQLITE_MASTER table is only parsed if the rest of the
57899 ** schema is already loaded into the symbol table.
57900 **
57901 ** This opcode invokes the parser to create a new virtual machine,
57902 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
57903 */
57904 case OP_ParseSchema: {
57905 #if 0  /* local variables moved into u.bu */
57906   int iDb;
57907   const char *zMaster;
57908   char *zSql;
57909   InitData initData;
57910 #endif /* local variables moved into u.bu */
57911
57912   u.bu.iDb = pOp->p1;
57913   assert( u.bu.iDb>=0 && u.bu.iDb<db->nDb );
57914
57915   /* If pOp->p2 is 0, then this opcode is being executed to read a
57916   ** single row, for example the row corresponding to a new index
57917   ** created by this VDBE, from the sqlite_master table. It only
57918   ** does this if the corresponding in-memory schema is currently
57919   ** loaded. Otherwise, the new index definition can be loaded along
57920   ** with the rest of the schema when it is required.
57921   **
57922   ** Although the mutex on the BtShared object that corresponds to
57923   ** database u.bu.iDb (the database containing the sqlite_master table
57924   ** read by this instruction) is currently held, it is necessary to
57925   ** obtain the mutexes on all attached databases before checking if
57926   ** the schema of u.bu.iDb is loaded. This is because, at the start of
57927   ** the sqlite3_exec() call below, SQLite will invoke
57928   ** sqlite3BtreeEnterAll(). If all mutexes are not already held, the
57929   ** u.bu.iDb mutex may be temporarily released to avoid deadlock. If
57930   ** this happens, then some other thread may delete the in-memory
57931   ** schema of database u.bu.iDb before the SQL statement runs. The schema
57932   ** will not be reloaded becuase the db->init.busy flag is set. This
57933   ** can result in a "no such table: sqlite_master" or "malformed
57934   ** database schema" error being returned to the user.
57935   */
57936   assert( sqlite3BtreeHoldsMutex(db->aDb[u.bu.iDb].pBt) );
57937   sqlite3BtreeEnterAll(db);
57938   if( pOp->p2 || DbHasProperty(db, u.bu.iDb, DB_SchemaLoaded) ){
57939     u.bu.zMaster = SCHEMA_TABLE(u.bu.iDb);
57940     u.bu.initData.db = db;
57941     u.bu.initData.iDb = pOp->p1;
57942     u.bu.initData.pzErrMsg = &p->zErrMsg;
57943     u.bu.zSql = sqlite3MPrintf(db,
57944        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
57945        db->aDb[u.bu.iDb].zName, u.bu.zMaster, pOp->p4.z);
57946     if( u.bu.zSql==0 ){
57947       rc = SQLITE_NOMEM;
57948     }else{
57949       assert( db->init.busy==0 );
57950       db->init.busy = 1;
57951       u.bu.initData.rc = SQLITE_OK;
57952       assert( !db->mallocFailed );
57953       rc = sqlite3_exec(db, u.bu.zSql, sqlite3InitCallback, &u.bu.initData, 0);
57954       if( rc==SQLITE_OK ) rc = u.bu.initData.rc;
57955       sqlite3DbFree(db, u.bu.zSql);
57956       db->init.busy = 0;
57957     }
57958   }
57959   sqlite3BtreeLeaveAll(db);
57960   if( rc==SQLITE_NOMEM ){
57961     goto no_mem;
57962   }
57963   break;
57964 }
57965
57966 #if !defined(SQLITE_OMIT_ANALYZE)
57967 /* Opcode: LoadAnalysis P1 * * * *
57968 **
57969 ** Read the sqlite_stat1 table for database P1 and load the content
57970 ** of that table into the internal index hash table.  This will cause
57971 ** the analysis to be used when preparing all subsequent queries.
57972 */
57973 case OP_LoadAnalysis: {
57974   assert( pOp->p1>=0 && pOp->p1<db->nDb );
57975   rc = sqlite3AnalysisLoad(db, pOp->p1);
57976   break;  
57977 }
57978 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
57979
57980 /* Opcode: DropTable P1 * * P4 *
57981 **
57982 ** Remove the internal (in-memory) data structures that describe
57983 ** the table named P4 in database P1.  This is called after a table
57984 ** is dropped in order to keep the internal representation of the
57985 ** schema consistent with what is on disk.
57986 */
57987 case OP_DropTable: {
57988   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
57989   break;
57990 }
57991
57992 /* Opcode: DropIndex P1 * * P4 *
57993 **
57994 ** Remove the internal (in-memory) data structures that describe
57995 ** the index named P4 in database P1.  This is called after an index
57996 ** is dropped in order to keep the internal representation of the
57997 ** schema consistent with what is on disk.
57998 */
57999 case OP_DropIndex: {
58000   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
58001   break;
58002 }
58003
58004 /* Opcode: DropTrigger P1 * * P4 *
58005 **
58006 ** Remove the internal (in-memory) data structures that describe
58007 ** the trigger named P4 in database P1.  This is called after a trigger
58008 ** is dropped in order to keep the internal representation of the
58009 ** schema consistent with what is on disk.
58010 */
58011 case OP_DropTrigger: {
58012   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
58013   break;
58014 }
58015
58016
58017 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
58018 /* Opcode: IntegrityCk P1 P2 P3 * P5
58019 **
58020 ** Do an analysis of the currently open database.  Store in
58021 ** register P1 the text of an error message describing any problems.
58022 ** If no problems are found, store a NULL in register P1.
58023 **
58024 ** The register P3 contains the maximum number of allowed errors.
58025 ** At most reg(P3) errors will be reported.
58026 ** In other words, the analysis stops as soon as reg(P1) errors are 
58027 ** seen.  Reg(P1) is updated with the number of errors remaining.
58028 **
58029 ** The root page numbers of all tables in the database are integer
58030 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
58031 ** total.
58032 **
58033 ** If P5 is not zero, the check is done on the auxiliary database
58034 ** file, not the main database file.
58035 **
58036 ** This opcode is used to implement the integrity_check pragma.
58037 */
58038 case OP_IntegrityCk: {
58039 #if 0  /* local variables moved into u.bv */
58040   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
58041   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
58042   int j;          /* Loop counter */
58043   int nErr;       /* Number of errors reported */
58044   char *z;        /* Text of the error report */
58045   Mem *pnErr;     /* Register keeping track of errors remaining */
58046 #endif /* local variables moved into u.bv */
58047
58048   u.bv.nRoot = pOp->p2;
58049   assert( u.bv.nRoot>0 );
58050   u.bv.aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(u.bv.nRoot+1) );
58051   if( u.bv.aRoot==0 ) goto no_mem;
58052   assert( pOp->p3>0 && pOp->p3<=p->nMem );
58053   u.bv.pnErr = &aMem[pOp->p3];
58054   assert( (u.bv.pnErr->flags & MEM_Int)!=0 );
58055   assert( (u.bv.pnErr->flags & (MEM_Str|MEM_Blob))==0 );
58056   pIn1 = &aMem[pOp->p1];
58057   for(u.bv.j=0; u.bv.j<u.bv.nRoot; u.bv.j++){
58058     u.bv.aRoot[u.bv.j] = (int)sqlite3VdbeIntValue(&pIn1[u.bv.j]);
58059   }
58060   u.bv.aRoot[u.bv.j] = 0;
58061   assert( pOp->p5<db->nDb );
58062   assert( (p->btreeMask & (1<<pOp->p5))!=0 );
58063   u.bv.z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, u.bv.aRoot, u.bv.nRoot,
58064                                  (int)u.bv.pnErr->u.i, &u.bv.nErr);
58065   sqlite3DbFree(db, u.bv.aRoot);
58066   u.bv.pnErr->u.i -= u.bv.nErr;
58067   sqlite3VdbeMemSetNull(pIn1);
58068   if( u.bv.nErr==0 ){
58069     assert( u.bv.z==0 );
58070   }else if( u.bv.z==0 ){
58071     goto no_mem;
58072   }else{
58073     sqlite3VdbeMemSetStr(pIn1, u.bv.z, -1, SQLITE_UTF8, sqlite3_free);
58074   }
58075   UPDATE_MAX_BLOBSIZE(pIn1);
58076   sqlite3VdbeChangeEncoding(pIn1, encoding);
58077   break;
58078 }
58079 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
58080
58081 /* Opcode: RowSetAdd P1 P2 * * *
58082 **
58083 ** Insert the integer value held by register P2 into a boolean index
58084 ** held in register P1.
58085 **
58086 ** An assertion fails if P2 is not an integer.
58087 */
58088 case OP_RowSetAdd: {       /* in1, in2 */
58089   pIn1 = &aMem[pOp->p1];
58090   pIn2 = &aMem[pOp->p2];
58091   assert( (pIn2->flags & MEM_Int)!=0 );
58092   if( (pIn1->flags & MEM_RowSet)==0 ){
58093     sqlite3VdbeMemSetRowSet(pIn1);
58094     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
58095   }
58096   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
58097   break;
58098 }
58099
58100 /* Opcode: RowSetRead P1 P2 P3 * *
58101 **
58102 ** Extract the smallest value from boolean index P1 and put that value into
58103 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
58104 ** unchanged and jump to instruction P2.
58105 */
58106 case OP_RowSetRead: {       /* jump, in1, out3 */
58107 #if 0  /* local variables moved into u.bw */
58108   i64 val;
58109 #endif /* local variables moved into u.bw */
58110   CHECK_FOR_INTERRUPT;
58111   pIn1 = &aMem[pOp->p1];
58112   if( (pIn1->flags & MEM_RowSet)==0
58113    || sqlite3RowSetNext(pIn1->u.pRowSet, &u.bw.val)==0
58114   ){
58115     /* The boolean index is empty */
58116     sqlite3VdbeMemSetNull(pIn1);
58117     pc = pOp->p2 - 1;
58118   }else{
58119     /* A value was pulled from the index */
58120     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], u.bw.val);
58121   }
58122   break;
58123 }
58124
58125 /* Opcode: RowSetTest P1 P2 P3 P4
58126 **
58127 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
58128 ** contains a RowSet object and that RowSet object contains
58129 ** the value held in P3, jump to register P2. Otherwise, insert the
58130 ** integer in P3 into the RowSet and continue on to the
58131 ** next opcode.
58132 **
58133 ** The RowSet object is optimized for the case where successive sets
58134 ** of integers, where each set contains no duplicates. Each set
58135 ** of values is identified by a unique P4 value. The first set
58136 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
58137 ** non-negative.  For non-negative values of P4 only the lower 4
58138 ** bits are significant.
58139 **
58140 ** This allows optimizations: (a) when P4==0 there is no need to test
58141 ** the rowset object for P3, as it is guaranteed not to contain it,
58142 ** (b) when P4==-1 there is no need to insert the value, as it will
58143 ** never be tested for, and (c) when a value that is part of set X is
58144 ** inserted, there is no need to search to see if the same value was
58145 ** previously inserted as part of set X (only if it was previously
58146 ** inserted as part of some other set).
58147 */
58148 case OP_RowSetTest: {                     /* jump, in1, in3 */
58149 #if 0  /* local variables moved into u.bx */
58150   int iSet;
58151   int exists;
58152 #endif /* local variables moved into u.bx */
58153
58154   pIn1 = &aMem[pOp->p1];
58155   pIn3 = &aMem[pOp->p3];
58156   u.bx.iSet = pOp->p4.i;
58157   assert( pIn3->flags&MEM_Int );
58158
58159   /* If there is anything other than a rowset object in memory cell P1,
58160   ** delete it now and initialize P1 with an empty rowset
58161   */
58162   if( (pIn1->flags & MEM_RowSet)==0 ){
58163     sqlite3VdbeMemSetRowSet(pIn1);
58164     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
58165   }
58166
58167   assert( pOp->p4type==P4_INT32 );
58168   assert( u.bx.iSet==-1 || u.bx.iSet>=0 );
58169   if( u.bx.iSet ){
58170     u.bx.exists = sqlite3RowSetTest(pIn1->u.pRowSet,
58171                                (u8)(u.bx.iSet>=0 ? u.bx.iSet & 0xf : 0xff),
58172                                pIn3->u.i);
58173     if( u.bx.exists ){
58174       pc = pOp->p2 - 1;
58175       break;
58176     }
58177   }
58178   if( u.bx.iSet>=0 ){
58179     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
58180   }
58181   break;
58182 }
58183
58184
58185 #ifndef SQLITE_OMIT_TRIGGER
58186
58187 /* Opcode: Program P1 P2 P3 P4 *
58188 **
58189 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
58190 **
58191 ** P1 contains the address of the memory cell that contains the first memory 
58192 ** cell in an array of values used as arguments to the sub-program. P2 
58193 ** contains the address to jump to if the sub-program throws an IGNORE 
58194 ** exception using the RAISE() function. Register P3 contains the address 
58195 ** of a memory cell in this (the parent) VM that is used to allocate the 
58196 ** memory required by the sub-vdbe at runtime.
58197 **
58198 ** P4 is a pointer to the VM containing the trigger program.
58199 */
58200 case OP_Program: {        /* jump */
58201 #if 0  /* local variables moved into u.by */
58202   int nMem;               /* Number of memory registers for sub-program */
58203   int nByte;              /* Bytes of runtime space required for sub-program */
58204   Mem *pRt;               /* Register to allocate runtime space */
58205   Mem *pMem;              /* Used to iterate through memory cells */
58206   Mem *pEnd;              /* Last memory cell in new array */
58207   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
58208   SubProgram *pProgram;   /* Sub-program to execute */
58209   void *t;                /* Token identifying trigger */
58210 #endif /* local variables moved into u.by */
58211
58212   u.by.pProgram = pOp->p4.pProgram;
58213   u.by.pRt = &aMem[pOp->p3];
58214   assert( u.by.pProgram->nOp>0 );
58215
58216   /* If the p5 flag is clear, then recursive invocation of triggers is
58217   ** disabled for backwards compatibility (p5 is set if this sub-program
58218   ** is really a trigger, not a foreign key action, and the flag set
58219   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
58220   **
58221   ** It is recursive invocation of triggers, at the SQL level, that is
58222   ** disabled. In some cases a single trigger may generate more than one
58223   ** SubProgram (if the trigger may be executed with more than one different
58224   ** ON CONFLICT algorithm). SubProgram structures associated with a
58225   ** single trigger all have the same value for the SubProgram.token
58226   ** variable.  */
58227   if( pOp->p5 ){
58228     u.by.t = u.by.pProgram->token;
58229     for(u.by.pFrame=p->pFrame; u.by.pFrame && u.by.pFrame->token!=u.by.t; u.by.pFrame=u.by.pFrame->pParent);
58230     if( u.by.pFrame ) break;
58231   }
58232
58233   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
58234     rc = SQLITE_ERROR;
58235     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
58236     break;
58237   }
58238
58239   /* Register u.by.pRt is used to store the memory required to save the state
58240   ** of the current program, and the memory required at runtime to execute
58241   ** the trigger program. If this trigger has been fired before, then u.by.pRt
58242   ** is already allocated. Otherwise, it must be initialized.  */
58243   if( (u.by.pRt->flags&MEM_Frame)==0 ){
58244     /* SubProgram.nMem is set to the number of memory cells used by the
58245     ** program stored in SubProgram.aOp. As well as these, one memory
58246     ** cell is required for each cursor used by the program. Set local
58247     ** variable u.by.nMem (and later, VdbeFrame.nChildMem) to this value.
58248     */
58249     u.by.nMem = u.by.pProgram->nMem + u.by.pProgram->nCsr;
58250     u.by.nByte = ROUND8(sizeof(VdbeFrame))
58251               + u.by.nMem * sizeof(Mem)
58252               + u.by.pProgram->nCsr * sizeof(VdbeCursor *);
58253     u.by.pFrame = sqlite3DbMallocZero(db, u.by.nByte);
58254     if( !u.by.pFrame ){
58255       goto no_mem;
58256     }
58257     sqlite3VdbeMemRelease(u.by.pRt);
58258     u.by.pRt->flags = MEM_Frame;
58259     u.by.pRt->u.pFrame = u.by.pFrame;
58260
58261     u.by.pFrame->v = p;
58262     u.by.pFrame->nChildMem = u.by.nMem;
58263     u.by.pFrame->nChildCsr = u.by.pProgram->nCsr;
58264     u.by.pFrame->pc = pc;
58265     u.by.pFrame->aMem = p->aMem;
58266     u.by.pFrame->nMem = p->nMem;
58267     u.by.pFrame->apCsr = p->apCsr;
58268     u.by.pFrame->nCursor = p->nCursor;
58269     u.by.pFrame->aOp = p->aOp;
58270     u.by.pFrame->nOp = p->nOp;
58271     u.by.pFrame->token = u.by.pProgram->token;
58272
58273     u.by.pEnd = &VdbeFrameMem(u.by.pFrame)[u.by.pFrame->nChildMem];
58274     for(u.by.pMem=VdbeFrameMem(u.by.pFrame); u.by.pMem!=u.by.pEnd; u.by.pMem++){
58275       u.by.pMem->flags = MEM_Null;
58276       u.by.pMem->db = db;
58277     }
58278   }else{
58279     u.by.pFrame = u.by.pRt->u.pFrame;
58280     assert( u.by.pProgram->nMem+u.by.pProgram->nCsr==u.by.pFrame->nChildMem );
58281     assert( u.by.pProgram->nCsr==u.by.pFrame->nChildCsr );
58282     assert( pc==u.by.pFrame->pc );
58283   }
58284
58285   p->nFrame++;
58286   u.by.pFrame->pParent = p->pFrame;
58287   u.by.pFrame->lastRowid = db->lastRowid;
58288   u.by.pFrame->nChange = p->nChange;
58289   p->nChange = 0;
58290   p->pFrame = u.by.pFrame;
58291   p->aMem = aMem = &VdbeFrameMem(u.by.pFrame)[-1];
58292   p->nMem = u.by.pFrame->nChildMem;
58293   p->nCursor = (u16)u.by.pFrame->nChildCsr;
58294   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
58295   p->aOp = aOp = u.by.pProgram->aOp;
58296   p->nOp = u.by.pProgram->nOp;
58297   pc = -1;
58298
58299   break;
58300 }
58301
58302 /* Opcode: Param P1 P2 * * *
58303 **
58304 ** This opcode is only ever present in sub-programs called via the 
58305 ** OP_Program instruction. Copy a value currently stored in a memory 
58306 ** cell of the calling (parent) frame to cell P2 in the current frames 
58307 ** address space. This is used by trigger programs to access the new.* 
58308 ** and old.* values.
58309 **
58310 ** The address of the cell in the parent frame is determined by adding
58311 ** the value of the P1 argument to the value of the P1 argument to the
58312 ** calling OP_Program instruction.
58313 */
58314 case OP_Param: {           /* out2-prerelease */
58315 #if 0  /* local variables moved into u.bz */
58316   VdbeFrame *pFrame;
58317   Mem *pIn;
58318 #endif /* local variables moved into u.bz */
58319   u.bz.pFrame = p->pFrame;
58320   u.bz.pIn = &u.bz.pFrame->aMem[pOp->p1 + u.bz.pFrame->aOp[u.bz.pFrame->pc].p1];
58321   sqlite3VdbeMemShallowCopy(pOut, u.bz.pIn, MEM_Ephem);
58322   break;
58323 }
58324
58325 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
58326
58327 #ifndef SQLITE_OMIT_FOREIGN_KEY
58328 /* Opcode: FkCounter P1 P2 * * *
58329 **
58330 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
58331 ** If P1 is non-zero, the database constraint counter is incremented 
58332 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
58333 ** statement counter is incremented (immediate foreign key constraints).
58334 */
58335 case OP_FkCounter: {
58336   if( pOp->p1 ){
58337     db->nDeferredCons += pOp->p2;
58338   }else{
58339     p->nFkConstraint += pOp->p2;
58340   }
58341   break;
58342 }
58343
58344 /* Opcode: FkIfZero P1 P2 * * *
58345 **
58346 ** This opcode tests if a foreign key constraint-counter is currently zero.
58347 ** If so, jump to instruction P2. Otherwise, fall through to the next 
58348 ** instruction.
58349 **
58350 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
58351 ** is zero (the one that counts deferred constraint violations). If P1 is
58352 ** zero, the jump is taken if the statement constraint-counter is zero
58353 ** (immediate foreign key constraint violations).
58354 */
58355 case OP_FkIfZero: {         /* jump */
58356   if( pOp->p1 ){
58357     if( db->nDeferredCons==0 ) pc = pOp->p2-1;
58358   }else{
58359     if( p->nFkConstraint==0 ) pc = pOp->p2-1;
58360   }
58361   break;
58362 }
58363 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
58364
58365 #ifndef SQLITE_OMIT_AUTOINCREMENT
58366 /* Opcode: MemMax P1 P2 * * *
58367 **
58368 ** P1 is a register in the root frame of this VM (the root frame is
58369 ** different from the current frame if this instruction is being executed
58370 ** within a sub-program). Set the value of register P1 to the maximum of 
58371 ** its current value and the value in register P2.
58372 **
58373 ** This instruction throws an error if the memory cell is not initially
58374 ** an integer.
58375 */
58376 case OP_MemMax: {        /* in2 */
58377 #if 0  /* local variables moved into u.ca */
58378   Mem *pIn1;
58379   VdbeFrame *pFrame;
58380 #endif /* local variables moved into u.ca */
58381   if( p->pFrame ){
58382     for(u.ca.pFrame=p->pFrame; u.ca.pFrame->pParent; u.ca.pFrame=u.ca.pFrame->pParent);
58383     u.ca.pIn1 = &u.ca.pFrame->aMem[pOp->p1];
58384   }else{
58385     u.ca.pIn1 = &aMem[pOp->p1];
58386   }
58387   sqlite3VdbeMemIntegerify(u.ca.pIn1);
58388   pIn2 = &aMem[pOp->p2];
58389   sqlite3VdbeMemIntegerify(pIn2);
58390   if( u.ca.pIn1->u.i<pIn2->u.i){
58391     u.ca.pIn1->u.i = pIn2->u.i;
58392   }
58393   break;
58394 }
58395 #endif /* SQLITE_OMIT_AUTOINCREMENT */
58396
58397 /* Opcode: IfPos P1 P2 * * *
58398 **
58399 ** If the value of register P1 is 1 or greater, jump to P2.
58400 **
58401 ** It is illegal to use this instruction on a register that does
58402 ** not contain an integer.  An assertion fault will result if you try.
58403 */
58404 case OP_IfPos: {        /* jump, in1 */
58405   pIn1 = &aMem[pOp->p1];
58406   assert( pIn1->flags&MEM_Int );
58407   if( pIn1->u.i>0 ){
58408      pc = pOp->p2 - 1;
58409   }
58410   break;
58411 }
58412
58413 /* Opcode: IfNeg P1 P2 * * *
58414 **
58415 ** If the value of register P1 is less than zero, jump to P2. 
58416 **
58417 ** It is illegal to use this instruction on a register that does
58418 ** not contain an integer.  An assertion fault will result if you try.
58419 */
58420 case OP_IfNeg: {        /* jump, in1 */
58421   pIn1 = &aMem[pOp->p1];
58422   assert( pIn1->flags&MEM_Int );
58423   if( pIn1->u.i<0 ){
58424      pc = pOp->p2 - 1;
58425   }
58426   break;
58427 }
58428
58429 /* Opcode: IfZero P1 P2 P3 * *
58430 **
58431 ** The register P1 must contain an integer.  Add literal P3 to the
58432 ** value in register P1.  If the result is exactly 0, jump to P2. 
58433 **
58434 ** It is illegal to use this instruction on a register that does
58435 ** not contain an integer.  An assertion fault will result if you try.
58436 */
58437 case OP_IfZero: {        /* jump, in1 */
58438   pIn1 = &aMem[pOp->p1];
58439   assert( pIn1->flags&MEM_Int );
58440   pIn1->u.i += pOp->p3;
58441   if( pIn1->u.i==0 ){
58442      pc = pOp->p2 - 1;
58443   }
58444   break;
58445 }
58446
58447 /* Opcode: AggStep * P2 P3 P4 P5
58448 **
58449 ** Execute the step function for an aggregate.  The
58450 ** function has P5 arguments.   P4 is a pointer to the FuncDef
58451 ** structure that specifies the function.  Use register
58452 ** P3 as the accumulator.
58453 **
58454 ** The P5 arguments are taken from register P2 and its
58455 ** successors.
58456 */
58457 case OP_AggStep: {
58458 #if 0  /* local variables moved into u.cb */
58459   int n;
58460   int i;
58461   Mem *pMem;
58462   Mem *pRec;
58463   sqlite3_context ctx;
58464   sqlite3_value **apVal;
58465 #endif /* local variables moved into u.cb */
58466
58467   u.cb.n = pOp->p5;
58468   assert( u.cb.n>=0 );
58469   u.cb.pRec = &aMem[pOp->p2];
58470   u.cb.apVal = p->apArg;
58471   assert( u.cb.apVal || u.cb.n==0 );
58472   for(u.cb.i=0; u.cb.i<u.cb.n; u.cb.i++, u.cb.pRec++){
58473     u.cb.apVal[u.cb.i] = u.cb.pRec;
58474     sqlite3VdbeMemStoreType(u.cb.pRec);
58475   }
58476   u.cb.ctx.pFunc = pOp->p4.pFunc;
58477   assert( pOp->p3>0 && pOp->p3<=p->nMem );
58478   u.cb.ctx.pMem = u.cb.pMem = &aMem[pOp->p3];
58479   u.cb.pMem->n++;
58480   u.cb.ctx.s.flags = MEM_Null;
58481   u.cb.ctx.s.z = 0;
58482   u.cb.ctx.s.zMalloc = 0;
58483   u.cb.ctx.s.xDel = 0;
58484   u.cb.ctx.s.db = db;
58485   u.cb.ctx.isError = 0;
58486   u.cb.ctx.pColl = 0;
58487   if( u.cb.ctx.pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
58488     assert( pOp>p->aOp );
58489     assert( pOp[-1].p4type==P4_COLLSEQ );
58490     assert( pOp[-1].opcode==OP_CollSeq );
58491     u.cb.ctx.pColl = pOp[-1].p4.pColl;
58492   }
58493   (u.cb.ctx.pFunc->xStep)(&u.cb.ctx, u.cb.n, u.cb.apVal);
58494   if( u.cb.ctx.isError ){
58495     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&u.cb.ctx.s));
58496     rc = u.cb.ctx.isError;
58497   }
58498   sqlite3VdbeMemRelease(&u.cb.ctx.s);
58499   break;
58500 }
58501
58502 /* Opcode: AggFinal P1 P2 * P4 *
58503 **
58504 ** Execute the finalizer function for an aggregate.  P1 is
58505 ** the memory location that is the accumulator for the aggregate.
58506 **
58507 ** P2 is the number of arguments that the step function takes and
58508 ** P4 is a pointer to the FuncDef for this function.  The P2
58509 ** argument is not used by this opcode.  It is only there to disambiguate
58510 ** functions that can take varying numbers of arguments.  The
58511 ** P4 argument is only needed for the degenerate case where
58512 ** the step function was not previously called.
58513 */
58514 case OP_AggFinal: {
58515 #if 0  /* local variables moved into u.cc */
58516   Mem *pMem;
58517 #endif /* local variables moved into u.cc */
58518   assert( pOp->p1>0 && pOp->p1<=p->nMem );
58519   u.cc.pMem = &aMem[pOp->p1];
58520   assert( (u.cc.pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
58521   rc = sqlite3VdbeMemFinalize(u.cc.pMem, pOp->p4.pFunc);
58522   if( rc ){
58523     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(u.cc.pMem));
58524   }
58525   sqlite3VdbeChangeEncoding(u.cc.pMem, encoding);
58526   UPDATE_MAX_BLOBSIZE(u.cc.pMem);
58527   if( sqlite3VdbeMemTooBig(u.cc.pMem) ){
58528     goto too_big;
58529   }
58530   break;
58531 }
58532
58533
58534 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
58535 /* Opcode: Vacuum * * * * *
58536 **
58537 ** Vacuum the entire database.  This opcode will cause other virtual
58538 ** machines to be created and run.  It may not be called from within
58539 ** a transaction.
58540 */
58541 case OP_Vacuum: {
58542   rc = sqlite3RunVacuum(&p->zErrMsg, db);
58543   break;
58544 }
58545 #endif
58546
58547 #if !defined(SQLITE_OMIT_AUTOVACUUM)
58548 /* Opcode: IncrVacuum P1 P2 * * *
58549 **
58550 ** Perform a single step of the incremental vacuum procedure on
58551 ** the P1 database. If the vacuum has finished, jump to instruction
58552 ** P2. Otherwise, fall through to the next instruction.
58553 */
58554 case OP_IncrVacuum: {        /* jump */
58555 #if 0  /* local variables moved into u.cd */
58556   Btree *pBt;
58557 #endif /* local variables moved into u.cd */
58558
58559   assert( pOp->p1>=0 && pOp->p1<db->nDb );
58560   assert( (p->btreeMask & (1<<pOp->p1))!=0 );
58561   u.cd.pBt = db->aDb[pOp->p1].pBt;
58562   rc = sqlite3BtreeIncrVacuum(u.cd.pBt);
58563   if( rc==SQLITE_DONE ){
58564     pc = pOp->p2 - 1;
58565     rc = SQLITE_OK;
58566   }
58567   break;
58568 }
58569 #endif
58570
58571 /* Opcode: Expire P1 * * * *
58572 **
58573 ** Cause precompiled statements to become expired. An expired statement
58574 ** fails with an error code of SQLITE_SCHEMA if it is ever executed 
58575 ** (via sqlite3_step()).
58576 ** 
58577 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
58578 ** then only the currently executing statement is affected. 
58579 */
58580 case OP_Expire: {
58581   if( !pOp->p1 ){
58582     sqlite3ExpirePreparedStatements(db);
58583   }else{
58584     p->expired = 1;
58585   }
58586   break;
58587 }
58588
58589 #ifndef SQLITE_OMIT_SHARED_CACHE
58590 /* Opcode: TableLock P1 P2 P3 P4 *
58591 **
58592 ** Obtain a lock on a particular table. This instruction is only used when
58593 ** the shared-cache feature is enabled. 
58594 **
58595 ** P1 is the index of the database in sqlite3.aDb[] of the database
58596 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
58597 ** a write lock if P3==1.
58598 **
58599 ** P2 contains the root-page of the table to lock.
58600 **
58601 ** P4 contains a pointer to the name of the table being locked. This is only
58602 ** used to generate an error message if the lock cannot be obtained.
58603 */
58604 case OP_TableLock: {
58605   u8 isWriteLock = (u8)pOp->p3;
58606   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
58607     int p1 = pOp->p1; 
58608     assert( p1>=0 && p1<db->nDb );
58609     assert( (p->btreeMask & (1<<p1))!=0 );
58610     assert( isWriteLock==0 || isWriteLock==1 );
58611     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
58612     if( (rc&0xFF)==SQLITE_LOCKED ){
58613       const char *z = pOp->p4.z;
58614       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
58615     }
58616   }
58617   break;
58618 }
58619 #endif /* SQLITE_OMIT_SHARED_CACHE */
58620
58621 #ifndef SQLITE_OMIT_VIRTUALTABLE
58622 /* Opcode: VBegin * * * P4 *
58623 **
58624 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
58625 ** xBegin method for that table.
58626 **
58627 ** Also, whether or not P4 is set, check that this is not being called from
58628 ** within a callback to a virtual table xSync() method. If it is, the error
58629 ** code will be set to SQLITE_LOCKED.
58630 */
58631 case OP_VBegin: {
58632 #if 0  /* local variables moved into u.ce */
58633   VTable *pVTab;
58634 #endif /* local variables moved into u.ce */
58635   u.ce.pVTab = pOp->p4.pVtab;
58636   rc = sqlite3VtabBegin(db, u.ce.pVTab);
58637   if( u.ce.pVTab ){
58638     sqlite3DbFree(db, p->zErrMsg);
58639     p->zErrMsg = u.ce.pVTab->pVtab->zErrMsg;
58640     u.ce.pVTab->pVtab->zErrMsg = 0;
58641   }
58642   break;
58643 }
58644 #endif /* SQLITE_OMIT_VIRTUALTABLE */
58645
58646 #ifndef SQLITE_OMIT_VIRTUALTABLE
58647 /* Opcode: VCreate P1 * * P4 *
58648 **
58649 ** P4 is the name of a virtual table in database P1. Call the xCreate method
58650 ** for that table.
58651 */
58652 case OP_VCreate: {
58653   rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
58654   break;
58655 }
58656 #endif /* SQLITE_OMIT_VIRTUALTABLE */
58657
58658 #ifndef SQLITE_OMIT_VIRTUALTABLE
58659 /* Opcode: VDestroy P1 * * P4 *
58660 **
58661 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
58662 ** of that table.
58663 */
58664 case OP_VDestroy: {
58665   p->inVtabMethod = 2;
58666   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
58667   p->inVtabMethod = 0;
58668   break;
58669 }
58670 #endif /* SQLITE_OMIT_VIRTUALTABLE */
58671
58672 #ifndef SQLITE_OMIT_VIRTUALTABLE
58673 /* Opcode: VOpen P1 * * P4 *
58674 **
58675 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
58676 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
58677 ** table and stores that cursor in P1.
58678 */
58679 case OP_VOpen: {
58680 #if 0  /* local variables moved into u.cf */
58681   VdbeCursor *pCur;
58682   sqlite3_vtab_cursor *pVtabCursor;
58683   sqlite3_vtab *pVtab;
58684   sqlite3_module *pModule;
58685 #endif /* local variables moved into u.cf */
58686
58687   u.cf.pCur = 0;
58688   u.cf.pVtabCursor = 0;
58689   u.cf.pVtab = pOp->p4.pVtab->pVtab;
58690   u.cf.pModule = (sqlite3_module *)u.cf.pVtab->pModule;
58691   assert(u.cf.pVtab && u.cf.pModule);
58692   rc = u.cf.pModule->xOpen(u.cf.pVtab, &u.cf.pVtabCursor);
58693   sqlite3DbFree(db, p->zErrMsg);
58694   p->zErrMsg = u.cf.pVtab->zErrMsg;
58695   u.cf.pVtab->zErrMsg = 0;
58696   if( SQLITE_OK==rc ){
58697     /* Initialize sqlite3_vtab_cursor base class */
58698     u.cf.pVtabCursor->pVtab = u.cf.pVtab;
58699
58700     /* Initialise vdbe cursor object */
58701     u.cf.pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
58702     if( u.cf.pCur ){
58703       u.cf.pCur->pVtabCursor = u.cf.pVtabCursor;
58704       u.cf.pCur->pModule = u.cf.pVtabCursor->pVtab->pModule;
58705     }else{
58706       db->mallocFailed = 1;
58707       u.cf.pModule->xClose(u.cf.pVtabCursor);
58708     }
58709   }
58710   break;
58711 }
58712 #endif /* SQLITE_OMIT_VIRTUALTABLE */
58713
58714 #ifndef SQLITE_OMIT_VIRTUALTABLE
58715 /* Opcode: VFilter P1 P2 P3 P4 *
58716 **
58717 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
58718 ** the filtered result set is empty.
58719 **
58720 ** P4 is either NULL or a string that was generated by the xBestIndex
58721 ** method of the module.  The interpretation of the P4 string is left
58722 ** to the module implementation.
58723 **
58724 ** This opcode invokes the xFilter method on the virtual table specified
58725 ** by P1.  The integer query plan parameter to xFilter is stored in register
58726 ** P3. Register P3+1 stores the argc parameter to be passed to the
58727 ** xFilter method. Registers P3+2..P3+1+argc are the argc
58728 ** additional parameters which are passed to
58729 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
58730 **
58731 ** A jump is made to P2 if the result set after filtering would be empty.
58732 */
58733 case OP_VFilter: {   /* jump */
58734 #if 0  /* local variables moved into u.cg */
58735   int nArg;
58736   int iQuery;
58737   const sqlite3_module *pModule;
58738   Mem *pQuery;
58739   Mem *pArgc;
58740   sqlite3_vtab_cursor *pVtabCursor;
58741   sqlite3_vtab *pVtab;
58742   VdbeCursor *pCur;
58743   int res;
58744   int i;
58745   Mem **apArg;
58746 #endif /* local variables moved into u.cg */
58747
58748   u.cg.pQuery = &aMem[pOp->p3];
58749   u.cg.pArgc = &u.cg.pQuery[1];
58750   u.cg.pCur = p->apCsr[pOp->p1];
58751   REGISTER_TRACE(pOp->p3, u.cg.pQuery);
58752   assert( u.cg.pCur->pVtabCursor );
58753   u.cg.pVtabCursor = u.cg.pCur->pVtabCursor;
58754   u.cg.pVtab = u.cg.pVtabCursor->pVtab;
58755   u.cg.pModule = u.cg.pVtab->pModule;
58756
58757   /* Grab the index number and argc parameters */
58758   assert( (u.cg.pQuery->flags&MEM_Int)!=0 && u.cg.pArgc->flags==MEM_Int );
58759   u.cg.nArg = (int)u.cg.pArgc->u.i;
58760   u.cg.iQuery = (int)u.cg.pQuery->u.i;
58761
58762   /* Invoke the xFilter method */
58763   {
58764     u.cg.res = 0;
58765     u.cg.apArg = p->apArg;
58766     for(u.cg.i = 0; u.cg.i<u.cg.nArg; u.cg.i++){
58767       u.cg.apArg[u.cg.i] = &u.cg.pArgc[u.cg.i+1];
58768       sqlite3VdbeMemStoreType(u.cg.apArg[u.cg.i]);
58769     }
58770
58771     p->inVtabMethod = 1;
58772     rc = u.cg.pModule->xFilter(u.cg.pVtabCursor, u.cg.iQuery, pOp->p4.z, u.cg.nArg, u.cg.apArg);
58773     p->inVtabMethod = 0;
58774     sqlite3DbFree(db, p->zErrMsg);
58775     p->zErrMsg = u.cg.pVtab->zErrMsg;
58776     u.cg.pVtab->zErrMsg = 0;
58777     if( rc==SQLITE_OK ){
58778       u.cg.res = u.cg.pModule->xEof(u.cg.pVtabCursor);
58779     }
58780
58781     if( u.cg.res ){
58782       pc = pOp->p2 - 1;
58783     }
58784   }
58785   u.cg.pCur->nullRow = 0;
58786
58787   break;
58788 }
58789 #endif /* SQLITE_OMIT_VIRTUALTABLE */
58790
58791 #ifndef SQLITE_OMIT_VIRTUALTABLE
58792 /* Opcode: VColumn P1 P2 P3 * *
58793 **
58794 ** Store the value of the P2-th column of
58795 ** the row of the virtual-table that the 
58796 ** P1 cursor is pointing to into register P3.
58797 */
58798 case OP_VColumn: {
58799 #if 0  /* local variables moved into u.ch */
58800   sqlite3_vtab *pVtab;
58801   const sqlite3_module *pModule;
58802   Mem *pDest;
58803   sqlite3_context sContext;
58804 #endif /* local variables moved into u.ch */
58805
58806   VdbeCursor *pCur = p->apCsr[pOp->p1];
58807   assert( pCur->pVtabCursor );
58808   assert( pOp->p3>0 && pOp->p3<=p->nMem );
58809   u.ch.pDest = &aMem[pOp->p3];
58810   if( pCur->nullRow ){
58811     sqlite3VdbeMemSetNull(u.ch.pDest);
58812     break;
58813   }
58814   u.ch.pVtab = pCur->pVtabCursor->pVtab;
58815   u.ch.pModule = u.ch.pVtab->pModule;
58816   assert( u.ch.pModule->xColumn );
58817   memset(&u.ch.sContext, 0, sizeof(u.ch.sContext));
58818
58819   /* The output cell may already have a buffer allocated. Move
58820   ** the current contents to u.ch.sContext.s so in case the user-function
58821   ** can use the already allocated buffer instead of allocating a
58822   ** new one.
58823   */
58824   sqlite3VdbeMemMove(&u.ch.sContext.s, u.ch.pDest);
58825   MemSetTypeFlag(&u.ch.sContext.s, MEM_Null);
58826
58827   rc = u.ch.pModule->xColumn(pCur->pVtabCursor, &u.ch.sContext, pOp->p2);
58828   sqlite3DbFree(db, p->zErrMsg);
58829   p->zErrMsg = u.ch.pVtab->zErrMsg;
58830   u.ch.pVtab->zErrMsg = 0;
58831   if( u.ch.sContext.isError ){
58832     rc = u.ch.sContext.isError;
58833   }
58834
58835   /* Copy the result of the function to the P3 register. We
58836   ** do this regardless of whether or not an error occurred to ensure any
58837   ** dynamic allocation in u.ch.sContext.s (a Mem struct) is  released.
58838   */
58839   sqlite3VdbeChangeEncoding(&u.ch.sContext.s, encoding);
58840   sqlite3VdbeMemMove(u.ch.pDest, &u.ch.sContext.s);
58841   REGISTER_TRACE(pOp->p3, u.ch.pDest);
58842   UPDATE_MAX_BLOBSIZE(u.ch.pDest);
58843
58844   if( sqlite3VdbeMemTooBig(u.ch.pDest) ){
58845     goto too_big;
58846   }
58847   break;
58848 }
58849 #endif /* SQLITE_OMIT_VIRTUALTABLE */
58850
58851 #ifndef SQLITE_OMIT_VIRTUALTABLE
58852 /* Opcode: VNext P1 P2 * * *
58853 **
58854 ** Advance virtual table P1 to the next row in its result set and
58855 ** jump to instruction P2.  Or, if the virtual table has reached
58856 ** the end of its result set, then fall through to the next instruction.
58857 */
58858 case OP_VNext: {   /* jump */
58859 #if 0  /* local variables moved into u.ci */
58860   sqlite3_vtab *pVtab;
58861   const sqlite3_module *pModule;
58862   int res;
58863   VdbeCursor *pCur;
58864 #endif /* local variables moved into u.ci */
58865
58866   u.ci.res = 0;
58867   u.ci.pCur = p->apCsr[pOp->p1];
58868   assert( u.ci.pCur->pVtabCursor );
58869   if( u.ci.pCur->nullRow ){
58870     break;
58871   }
58872   u.ci.pVtab = u.ci.pCur->pVtabCursor->pVtab;
58873   u.ci.pModule = u.ci.pVtab->pModule;
58874   assert( u.ci.pModule->xNext );
58875
58876   /* Invoke the xNext() method of the module. There is no way for the
58877   ** underlying implementation to return an error if one occurs during
58878   ** xNext(). Instead, if an error occurs, true is returned (indicating that
58879   ** data is available) and the error code returned when xColumn or
58880   ** some other method is next invoked on the save virtual table cursor.
58881   */
58882   p->inVtabMethod = 1;
58883   rc = u.ci.pModule->xNext(u.ci.pCur->pVtabCursor);
58884   p->inVtabMethod = 0;
58885   sqlite3DbFree(db, p->zErrMsg);
58886   p->zErrMsg = u.ci.pVtab->zErrMsg;
58887   u.ci.pVtab->zErrMsg = 0;
58888   if( rc==SQLITE_OK ){
58889     u.ci.res = u.ci.pModule->xEof(u.ci.pCur->pVtabCursor);
58890   }
58891
58892   if( !u.ci.res ){
58893     /* If there is data, jump to P2 */
58894     pc = pOp->p2 - 1;
58895   }
58896   break;
58897 }
58898 #endif /* SQLITE_OMIT_VIRTUALTABLE */
58899
58900 #ifndef SQLITE_OMIT_VIRTUALTABLE
58901 /* Opcode: VRename P1 * * P4 *
58902 **
58903 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
58904 ** This opcode invokes the corresponding xRename method. The value
58905 ** in register P1 is passed as the zName argument to the xRename method.
58906 */
58907 case OP_VRename: {
58908 #if 0  /* local variables moved into u.cj */
58909   sqlite3_vtab *pVtab;
58910   Mem *pName;
58911 #endif /* local variables moved into u.cj */
58912
58913   u.cj.pVtab = pOp->p4.pVtab->pVtab;
58914   u.cj.pName = &aMem[pOp->p1];
58915   assert( u.cj.pVtab->pModule->xRename );
58916   REGISTER_TRACE(pOp->p1, u.cj.pName);
58917   assert( u.cj.pName->flags & MEM_Str );
58918   rc = u.cj.pVtab->pModule->xRename(u.cj.pVtab, u.cj.pName->z);
58919   sqlite3DbFree(db, p->zErrMsg);
58920   p->zErrMsg = u.cj.pVtab->zErrMsg;
58921   u.cj.pVtab->zErrMsg = 0;
58922
58923   break;
58924 }
58925 #endif
58926
58927 #ifndef SQLITE_OMIT_VIRTUALTABLE
58928 /* Opcode: VUpdate P1 P2 P3 P4 *
58929 **
58930 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
58931 ** This opcode invokes the corresponding xUpdate method. P2 values
58932 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
58933 ** invocation. The value in register (P3+P2-1) corresponds to the 
58934 ** p2th element of the argv array passed to xUpdate.
58935 **
58936 ** The xUpdate method will do a DELETE or an INSERT or both.
58937 ** The argv[0] element (which corresponds to memory cell P3)
58938 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
58939 ** deletion occurs.  The argv[1] element is the rowid of the new 
58940 ** row.  This can be NULL to have the virtual table select the new 
58941 ** rowid for itself.  The subsequent elements in the array are 
58942 ** the values of columns in the new row.
58943 **
58944 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
58945 ** a row to delete.
58946 **
58947 ** P1 is a boolean flag. If it is set to true and the xUpdate call
58948 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
58949 ** is set to the value of the rowid for the row just inserted.
58950 */
58951 case OP_VUpdate: {
58952 #if 0  /* local variables moved into u.ck */
58953   sqlite3_vtab *pVtab;
58954   sqlite3_module *pModule;
58955   int nArg;
58956   int i;
58957   sqlite_int64 rowid;
58958   Mem **apArg;
58959   Mem *pX;
58960 #endif /* local variables moved into u.ck */
58961
58962   u.ck.pVtab = pOp->p4.pVtab->pVtab;
58963   u.ck.pModule = (sqlite3_module *)u.ck.pVtab->pModule;
58964   u.ck.nArg = pOp->p2;
58965   assert( pOp->p4type==P4_VTAB );
58966   if( ALWAYS(u.ck.pModule->xUpdate) ){
58967     u.ck.apArg = p->apArg;
58968     u.ck.pX = &aMem[pOp->p3];
58969     for(u.ck.i=0; u.ck.i<u.ck.nArg; u.ck.i++){
58970       sqlite3VdbeMemStoreType(u.ck.pX);
58971       u.ck.apArg[u.ck.i] = u.ck.pX;
58972       u.ck.pX++;
58973     }
58974     rc = u.ck.pModule->xUpdate(u.ck.pVtab, u.ck.nArg, u.ck.apArg, &u.ck.rowid);
58975     sqlite3DbFree(db, p->zErrMsg);
58976     p->zErrMsg = u.ck.pVtab->zErrMsg;
58977     u.ck.pVtab->zErrMsg = 0;
58978     if( rc==SQLITE_OK && pOp->p1 ){
58979       assert( u.ck.nArg>1 && u.ck.apArg[0] && (u.ck.apArg[0]->flags&MEM_Null) );
58980       db->lastRowid = u.ck.rowid;
58981     }
58982     p->nChange++;
58983   }
58984   break;
58985 }
58986 #endif /* SQLITE_OMIT_VIRTUALTABLE */
58987
58988 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
58989 /* Opcode: Pagecount P1 P2 * * *
58990 **
58991 ** Write the current number of pages in database P1 to memory cell P2.
58992 */
58993 case OP_Pagecount: {            /* out2-prerelease */
58994 #if 0  /* local variables moved into u.cl */
58995   int p1;
58996   int nPage;
58997   Pager *pPager;
58998 #endif /* local variables moved into u.cl */
58999
59000   u.cl.p1 = pOp->p1;
59001   u.cl.pPager = sqlite3BtreePager(db->aDb[u.cl.p1].pBt);
59002   rc = sqlite3PagerPagecount(u.cl.pPager, &u.cl.nPage);
59003   /* OP_Pagecount is always called from within a read transaction.  The
59004   ** page count has already been successfully read and cached.  So the
59005   ** sqlite3PagerPagecount() call above cannot fail. */
59006   if( ALWAYS(rc==SQLITE_OK) ){
59007     pOut->u.i = u.cl.nPage;
59008   }
59009   break;
59010 }
59011 #endif
59012
59013 #ifndef SQLITE_OMIT_TRACE
59014 /* Opcode: Trace * * * P4 *
59015 **
59016 ** If tracing is enabled (by the sqlite3_trace()) interface, then
59017 ** the UTF-8 string contained in P4 is emitted on the trace callback.
59018 */
59019 case OP_Trace: {
59020 #if 0  /* local variables moved into u.cm */
59021   char *zTrace;
59022 #endif /* local variables moved into u.cm */
59023
59024   u.cm.zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
59025   if( u.cm.zTrace ){
59026     if( db->xTrace ){
59027       char *z = sqlite3VdbeExpandSql(p, u.cm.zTrace);
59028       db->xTrace(db->pTraceArg, z);
59029       sqlite3DbFree(db, z);
59030     }
59031 #ifdef SQLITE_DEBUG
59032     if( (db->flags & SQLITE_SqlTrace)!=0 ){
59033       sqlite3DebugPrintf("SQL-trace: %s\n", u.cm.zTrace);
59034     }
59035 #endif /* SQLITE_DEBUG */
59036   }
59037   break;
59038 }
59039 #endif
59040
59041
59042 /* Opcode: Noop * * * * *
59043 **
59044 ** Do nothing.  This instruction is often useful as a jump
59045 ** destination.
59046 */
59047 /*
59048 ** The magic Explain opcode are only inserted when explain==2 (which
59049 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
59050 ** This opcode records information from the optimizer.  It is the
59051 ** the same as a no-op.  This opcodesnever appears in a real VM program.
59052 */
59053 default: {          /* This is really OP_Noop and OP_Explain */
59054   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
59055   break;
59056 }
59057
59058 /*****************************************************************************
59059 ** The cases of the switch statement above this line should all be indented
59060 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
59061 ** readability.  From this point on down, the normal indentation rules are
59062 ** restored.
59063 *****************************************************************************/
59064     }
59065
59066 #ifdef VDBE_PROFILE
59067     {
59068       u64 elapsed = sqlite3Hwtime() - start;
59069       pOp->cycles += elapsed;
59070       pOp->cnt++;
59071 #if 0
59072         fprintf(stdout, "%10llu ", elapsed);
59073         sqlite3VdbePrintOp(stdout, origPc, &aOp[origPc]);
59074 #endif
59075     }
59076 #endif
59077
59078     /* The following code adds nothing to the actual functionality
59079     ** of the program.  It is only here for testing and debugging.
59080     ** On the other hand, it does burn CPU cycles every time through
59081     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
59082     */
59083 #ifndef NDEBUG
59084     assert( pc>=-1 && pc<p->nOp );
59085
59086 #ifdef SQLITE_DEBUG
59087     if( p->trace ){
59088       if( rc!=0 ) fprintf(p->trace,"rc=%d\n",rc);
59089       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
59090         registerTrace(p->trace, pOp->p2, &aMem[pOp->p2]);
59091       }
59092       if( pOp->opflags & OPFLG_OUT3 ){
59093         registerTrace(p->trace, pOp->p3, &aMem[pOp->p3]);
59094       }
59095     }
59096 #endif  /* SQLITE_DEBUG */
59097 #endif  /* NDEBUG */
59098   }  /* The end of the for(;;) loop the loops through opcodes */
59099
59100   /* If we reach this point, it means that execution is finished with
59101   ** an error of some kind.
59102   */
59103 vdbe_error_halt:
59104   assert( rc );
59105   p->rc = rc;
59106   testcase( sqlite3GlobalConfig.xLog!=0 );
59107   sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
59108                    pc, p->zSql, p->zErrMsg);
59109   sqlite3VdbeHalt(p);
59110   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
59111   rc = SQLITE_ERROR;
59112   if( resetSchemaOnFault ) sqlite3ResetInternalSchema(db, 0);
59113
59114   /* This is the only way out of this procedure.  We have to
59115   ** release the mutexes on btrees that were acquired at the
59116   ** top. */
59117 vdbe_return:
59118   sqlite3BtreeMutexArrayLeave(&p->aMutex);
59119   return rc;
59120
59121   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
59122   ** is encountered.
59123   */
59124 too_big:
59125   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
59126   rc = SQLITE_TOOBIG;
59127   goto vdbe_error_halt;
59128
59129   /* Jump to here if a malloc() fails.
59130   */
59131 no_mem:
59132   db->mallocFailed = 1;
59133   sqlite3SetString(&p->zErrMsg, db, "out of memory");
59134   rc = SQLITE_NOMEM;
59135   goto vdbe_error_halt;
59136
59137   /* Jump to here for any other kind of fatal error.  The "rc" variable
59138   ** should hold the error number.
59139   */
59140 abort_due_to_error:
59141   assert( p->zErrMsg==0 );
59142   if( db->mallocFailed ) rc = SQLITE_NOMEM;
59143   if( rc!=SQLITE_IOERR_NOMEM ){
59144     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
59145   }
59146   goto vdbe_error_halt;
59147
59148   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
59149   ** flag.
59150   */
59151 abort_due_to_interrupt:
59152   assert( db->u1.isInterrupted );
59153   rc = SQLITE_INTERRUPT;
59154   p->rc = rc;
59155   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
59156   goto vdbe_error_halt;
59157 }
59158
59159 /************** End of vdbe.c ************************************************/
59160 /************** Begin file vdbeblob.c ****************************************/
59161 /*
59162 ** 2007 May 1
59163 **
59164 ** The author disclaims copyright to this source code.  In place of
59165 ** a legal notice, here is a blessing:
59166 **
59167 **    May you do good and not evil.
59168 **    May you find forgiveness for yourself and forgive others.
59169 **    May you share freely, never taking more than you give.
59170 **
59171 *************************************************************************
59172 **
59173 ** This file contains code used to implement incremental BLOB I/O.
59174 */
59175
59176
59177 #ifndef SQLITE_OMIT_INCRBLOB
59178
59179 /*
59180 ** Valid sqlite3_blob* handles point to Incrblob structures.
59181 */
59182 typedef struct Incrblob Incrblob;
59183 struct Incrblob {
59184   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
59185   int nByte;              /* Size of open blob, in bytes */
59186   int iOffset;            /* Byte offset of blob in cursor data */
59187   BtCursor *pCsr;         /* Cursor pointing at blob row */
59188   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
59189   sqlite3 *db;            /* The associated database */
59190 };
59191
59192 /*
59193 ** Open a blob handle.
59194 */
59195 SQLITE_API int sqlite3_blob_open(
59196   sqlite3* db,            /* The database connection */
59197   const char *zDb,        /* The attached database containing the blob */
59198   const char *zTable,     /* The table containing the blob */
59199   const char *zColumn,    /* The column containing the blob */
59200   sqlite_int64 iRow,      /* The row containing the glob */
59201   int flags,              /* True -> read/write access, false -> read-only */
59202   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
59203 ){
59204   int nAttempt = 0;
59205   int iCol;               /* Index of zColumn in row-record */
59206
59207   /* This VDBE program seeks a btree cursor to the identified 
59208   ** db/table/row entry. The reason for using a vdbe program instead
59209   ** of writing code to use the b-tree layer directly is that the
59210   ** vdbe program will take advantage of the various transaction,
59211   ** locking and error handling infrastructure built into the vdbe.
59212   **
59213   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
59214   ** Code external to the Vdbe then "borrows" the b-tree cursor and
59215   ** uses it to implement the blob_read(), blob_write() and 
59216   ** blob_bytes() functions.
59217   **
59218   ** The sqlite3_blob_close() function finalizes the vdbe program,
59219   ** which closes the b-tree cursor and (possibly) commits the 
59220   ** transaction.
59221   */
59222   static const VdbeOpList openBlob[] = {
59223     {OP_Transaction, 0, 0, 0},     /* 0: Start a transaction */
59224     {OP_VerifyCookie, 0, 0, 0},    /* 1: Check the schema cookie */
59225     {OP_TableLock, 0, 0, 0},       /* 2: Acquire a read or write lock */
59226
59227     /* One of the following two instructions is replaced by an OP_Noop. */
59228     {OP_OpenRead, 0, 0, 0},        /* 3: Open cursor 0 for reading */
59229     {OP_OpenWrite, 0, 0, 0},       /* 4: Open cursor 0 for read/write */
59230
59231     {OP_Variable, 1, 1, 1},        /* 5: Push the rowid to the stack */
59232     {OP_NotExists, 0, 9, 1},       /* 6: Seek the cursor */
59233     {OP_Column, 0, 0, 1},          /* 7  */
59234     {OP_ResultRow, 1, 0, 0},       /* 8  */
59235     {OP_Close, 0, 0, 0},           /* 9  */
59236     {OP_Halt, 0, 0, 0},            /* 10 */
59237   };
59238
59239   Vdbe *v = 0;
59240   int rc = SQLITE_OK;
59241   char *zErr = 0;
59242   Table *pTab;
59243   Parse *pParse;
59244
59245   *ppBlob = 0;
59246   sqlite3_mutex_enter(db->mutex);
59247   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
59248   if( pParse==0 ){
59249     rc = SQLITE_NOMEM;
59250     goto blob_open_out;
59251   }
59252   do {
59253     memset(pParse, 0, sizeof(Parse));
59254     pParse->db = db;
59255
59256     sqlite3BtreeEnterAll(db);
59257     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
59258     if( pTab && IsVirtual(pTab) ){
59259       pTab = 0;
59260       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
59261     }
59262 #ifndef SQLITE_OMIT_VIEW
59263     if( pTab && pTab->pSelect ){
59264       pTab = 0;
59265       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
59266     }
59267 #endif
59268     if( !pTab ){
59269       if( pParse->zErrMsg ){
59270         sqlite3DbFree(db, zErr);
59271         zErr = pParse->zErrMsg;
59272         pParse->zErrMsg = 0;
59273       }
59274       rc = SQLITE_ERROR;
59275       sqlite3BtreeLeaveAll(db);
59276       goto blob_open_out;
59277     }
59278
59279     /* Now search pTab for the exact column. */
59280     for(iCol=0; iCol < pTab->nCol; iCol++) {
59281       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
59282         break;
59283       }
59284     }
59285     if( iCol==pTab->nCol ){
59286       sqlite3DbFree(db, zErr);
59287       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
59288       rc = SQLITE_ERROR;
59289       sqlite3BtreeLeaveAll(db);
59290       goto blob_open_out;
59291     }
59292
59293     /* If the value is being opened for writing, check that the
59294     ** column is not indexed, and that it is not part of a foreign key. 
59295     ** It is against the rules to open a column to which either of these
59296     ** descriptions applies for writing.  */
59297     if( flags ){
59298       const char *zFault = 0;
59299       Index *pIdx;
59300 #ifndef SQLITE_OMIT_FOREIGN_KEY
59301       if( db->flags&SQLITE_ForeignKeys ){
59302         /* Check that the column is not part of an FK child key definition. It
59303         ** is not necessary to check if it is part of a parent key, as parent
59304         ** key columns must be indexed. The check below will pick up this 
59305         ** case.  */
59306         FKey *pFKey;
59307         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
59308           int j;
59309           for(j=0; j<pFKey->nCol; j++){
59310             if( pFKey->aCol[j].iFrom==iCol ){
59311               zFault = "foreign key";
59312             }
59313           }
59314         }
59315       }
59316 #endif
59317       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
59318         int j;
59319         for(j=0; j<pIdx->nColumn; j++){
59320           if( pIdx->aiColumn[j]==iCol ){
59321             zFault = "indexed";
59322           }
59323         }
59324       }
59325       if( zFault ){
59326         sqlite3DbFree(db, zErr);
59327         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
59328         rc = SQLITE_ERROR;
59329         sqlite3BtreeLeaveAll(db);
59330         goto blob_open_out;
59331       }
59332     }
59333
59334     v = sqlite3VdbeCreate(db);
59335     if( v ){
59336       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
59337       sqlite3VdbeAddOpList(v, sizeof(openBlob)/sizeof(VdbeOpList), openBlob);
59338       flags = !!flags;                 /* flags = (flags ? 1 : 0); */
59339
59340       /* Configure the OP_Transaction */
59341       sqlite3VdbeChangeP1(v, 0, iDb);
59342       sqlite3VdbeChangeP2(v, 0, flags);
59343
59344       /* Configure the OP_VerifyCookie */
59345       sqlite3VdbeChangeP1(v, 1, iDb);
59346       sqlite3VdbeChangeP2(v, 1, pTab->pSchema->schema_cookie);
59347
59348       /* Make sure a mutex is held on the table to be accessed */
59349       sqlite3VdbeUsesBtree(v, iDb); 
59350
59351       /* Configure the OP_TableLock instruction */
59352       sqlite3VdbeChangeP1(v, 2, iDb);
59353       sqlite3VdbeChangeP2(v, 2, pTab->tnum);
59354       sqlite3VdbeChangeP3(v, 2, flags);
59355       sqlite3VdbeChangeP4(v, 2, pTab->zName, P4_TRANSIENT);
59356
59357       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
59358       ** parameter of the other to pTab->tnum.  */
59359       sqlite3VdbeChangeToNoop(v, 4 - flags, 1);
59360       sqlite3VdbeChangeP2(v, 3 + flags, pTab->tnum);
59361       sqlite3VdbeChangeP3(v, 3 + flags, iDb);
59362
59363       /* Configure the number of columns. Configure the cursor to
59364       ** think that the table has one more column than it really
59365       ** does. An OP_Column to retrieve this imaginary column will
59366       ** always return an SQL NULL. This is useful because it means
59367       ** we can invoke OP_Column to fill in the vdbe cursors type 
59368       ** and offset cache without causing any IO.
59369       */
59370       sqlite3VdbeChangeP4(v, 3+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
59371       sqlite3VdbeChangeP2(v, 7, pTab->nCol);
59372       if( !db->mallocFailed ){
59373         sqlite3VdbeMakeReady(v, 1, 1, 1, 0, 0, 0);
59374       }
59375     }
59376    
59377     sqlite3BtreeLeaveAll(db);
59378     if( db->mallocFailed ){
59379       goto blob_open_out;
59380     }
59381
59382     sqlite3_bind_int64((sqlite3_stmt *)v, 1, iRow);
59383     rc = sqlite3_step((sqlite3_stmt *)v);
59384     if( rc!=SQLITE_ROW ){
59385       nAttempt++;
59386       rc = sqlite3_finalize((sqlite3_stmt *)v);
59387       sqlite3DbFree(db, zErr);
59388       zErr = sqlite3MPrintf(db, sqlite3_errmsg(db));
59389       v = 0;
59390     }
59391   } while( nAttempt<5 && rc==SQLITE_SCHEMA );
59392
59393   if( rc==SQLITE_ROW ){
59394     /* The row-record has been opened successfully. Check that the
59395     ** column in question contains text or a blob. If it contains
59396     ** text, it is up to the caller to get the encoding right.
59397     */
59398     Incrblob *pBlob;
59399     u32 type = v->apCsr[0]->aType[iCol];
59400
59401     if( type<12 ){
59402       sqlite3DbFree(db, zErr);
59403       zErr = sqlite3MPrintf(db, "cannot open value of type %s",
59404           type==0?"null": type==7?"real": "integer"
59405       );
59406       rc = SQLITE_ERROR;
59407       goto blob_open_out;
59408     }
59409     pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
59410     if( db->mallocFailed ){
59411       sqlite3DbFree(db, pBlob);
59412       goto blob_open_out;
59413     }
59414     pBlob->flags = flags;
59415     pBlob->pCsr =  v->apCsr[0]->pCursor;
59416     sqlite3BtreeEnterCursor(pBlob->pCsr);
59417     sqlite3BtreeCacheOverflow(pBlob->pCsr);
59418     sqlite3BtreeLeaveCursor(pBlob->pCsr);
59419     pBlob->pStmt = (sqlite3_stmt *)v;
59420     pBlob->iOffset = v->apCsr[0]->aOffset[iCol];
59421     pBlob->nByte = sqlite3VdbeSerialTypeLen(type);
59422     pBlob->db = db;
59423     *ppBlob = (sqlite3_blob *)pBlob;
59424     rc = SQLITE_OK;
59425   }else if( rc==SQLITE_OK ){
59426     sqlite3DbFree(db, zErr);
59427     zErr = sqlite3MPrintf(db, "no such rowid: %lld", iRow);
59428     rc = SQLITE_ERROR;
59429   }
59430
59431 blob_open_out:
59432   if( v && (rc!=SQLITE_OK || db->mallocFailed) ){
59433     sqlite3VdbeFinalize(v);
59434   }
59435   sqlite3Error(db, rc, zErr);
59436   sqlite3DbFree(db, zErr);
59437   sqlite3StackFree(db, pParse);
59438   rc = sqlite3ApiExit(db, rc);
59439   sqlite3_mutex_leave(db->mutex);
59440   return rc;
59441 }
59442
59443 /*
59444 ** Close a blob handle that was previously created using
59445 ** sqlite3_blob_open().
59446 */
59447 SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
59448   Incrblob *p = (Incrblob *)pBlob;
59449   int rc;
59450   sqlite3 *db;
59451
59452   if( p ){
59453     db = p->db;
59454     sqlite3_mutex_enter(db->mutex);
59455     rc = sqlite3_finalize(p->pStmt);
59456     sqlite3DbFree(db, p);
59457     sqlite3_mutex_leave(db->mutex);
59458   }else{
59459     rc = SQLITE_OK;
59460   }
59461   return rc;
59462 }
59463
59464 /*
59465 ** Perform a read or write operation on a blob
59466 */
59467 static int blobReadWrite(
59468   sqlite3_blob *pBlob, 
59469   void *z, 
59470   int n, 
59471   int iOffset, 
59472   int (*xCall)(BtCursor*, u32, u32, void*)
59473 ){
59474   int rc;
59475   Incrblob *p = (Incrblob *)pBlob;
59476   Vdbe *v;
59477   sqlite3 *db;
59478
59479   if( p==0 ) return SQLITE_MISUSE_BKPT;
59480   db = p->db;
59481   sqlite3_mutex_enter(db->mutex);
59482   v = (Vdbe*)p->pStmt;
59483
59484   if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
59485     /* Request is out of range. Return a transient error. */
59486     rc = SQLITE_ERROR;
59487     sqlite3Error(db, SQLITE_ERROR, 0);
59488   } else if( v==0 ){
59489     /* If there is no statement handle, then the blob-handle has
59490     ** already been invalidated. Return SQLITE_ABORT in this case.
59491     */
59492     rc = SQLITE_ABORT;
59493   }else{
59494     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
59495     ** returned, clean-up the statement handle.
59496     */
59497     assert( db == v->db );
59498     sqlite3BtreeEnterCursor(p->pCsr);
59499     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
59500     sqlite3BtreeLeaveCursor(p->pCsr);
59501     if( rc==SQLITE_ABORT ){
59502       sqlite3VdbeFinalize(v);
59503       p->pStmt = 0;
59504     }else{
59505       db->errCode = rc;
59506       v->rc = rc;
59507     }
59508   }
59509   rc = sqlite3ApiExit(db, rc);
59510   sqlite3_mutex_leave(db->mutex);
59511   return rc;
59512 }
59513
59514 /*
59515 ** Read data from a blob handle.
59516 */
59517 SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
59518   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
59519 }
59520
59521 /*
59522 ** Write data to a blob handle.
59523 */
59524 SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
59525   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
59526 }
59527
59528 /*
59529 ** Query a blob handle for the size of the data.
59530 **
59531 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
59532 ** so no mutex is required for access.
59533 */
59534 SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
59535   Incrblob *p = (Incrblob *)pBlob;
59536   return p ? p->nByte : 0;
59537 }
59538
59539 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
59540
59541 /************** End of vdbeblob.c ********************************************/
59542 /************** Begin file journal.c *****************************************/
59543 /*
59544 ** 2007 August 22
59545 **
59546 ** The author disclaims copyright to this source code.  In place of
59547 ** a legal notice, here is a blessing:
59548 **
59549 **    May you do good and not evil.
59550 **    May you find forgiveness for yourself and forgive others.
59551 **    May you share freely, never taking more than you give.
59552 **
59553 *************************************************************************
59554 **
59555 ** This file implements a special kind of sqlite3_file object used
59556 ** by SQLite to create journal files if the atomic-write optimization
59557 ** is enabled.
59558 **
59559 ** The distinctive characteristic of this sqlite3_file is that the
59560 ** actual on disk file is created lazily. When the file is created,
59561 ** the caller specifies a buffer size for an in-memory buffer to
59562 ** be used to service read() and write() requests. The actual file
59563 ** on disk is not created or populated until either:
59564 **
59565 **   1) The in-memory representation grows too large for the allocated 
59566 **      buffer, or
59567 **   2) The sqlite3JournalCreate() function is called.
59568 */
59569 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
59570
59571
59572 /*
59573 ** A JournalFile object is a subclass of sqlite3_file used by
59574 ** as an open file handle for journal files.
59575 */
59576 struct JournalFile {
59577   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
59578   int nBuf;                       /* Size of zBuf[] in bytes */
59579   char *zBuf;                     /* Space to buffer journal writes */
59580   int iSize;                      /* Amount of zBuf[] currently used */
59581   int flags;                      /* xOpen flags */
59582   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
59583   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
59584   const char *zJournal;           /* Name of the journal file */
59585 };
59586 typedef struct JournalFile JournalFile;
59587
59588 /*
59589 ** If it does not already exists, create and populate the on-disk file 
59590 ** for JournalFile p.
59591 */
59592 static int createFile(JournalFile *p){
59593   int rc = SQLITE_OK;
59594   if( !p->pReal ){
59595     sqlite3_file *pReal = (sqlite3_file *)&p[1];
59596     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
59597     if( rc==SQLITE_OK ){
59598       p->pReal = pReal;
59599       if( p->iSize>0 ){
59600         assert(p->iSize<=p->nBuf);
59601         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
59602       }
59603     }
59604   }
59605   return rc;
59606 }
59607
59608 /*
59609 ** Close the file.
59610 */
59611 static int jrnlClose(sqlite3_file *pJfd){
59612   JournalFile *p = (JournalFile *)pJfd;
59613   if( p->pReal ){
59614     sqlite3OsClose(p->pReal);
59615   }
59616   sqlite3_free(p->zBuf);
59617   return SQLITE_OK;
59618 }
59619
59620 /*
59621 ** Read data from the file.
59622 */
59623 static int jrnlRead(
59624   sqlite3_file *pJfd,    /* The journal file from which to read */
59625   void *zBuf,            /* Put the results here */
59626   int iAmt,              /* Number of bytes to read */
59627   sqlite_int64 iOfst     /* Begin reading at this offset */
59628 ){
59629   int rc = SQLITE_OK;
59630   JournalFile *p = (JournalFile *)pJfd;
59631   if( p->pReal ){
59632     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
59633   }else if( (iAmt+iOfst)>p->iSize ){
59634     rc = SQLITE_IOERR_SHORT_READ;
59635   }else{
59636     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
59637   }
59638   return rc;
59639 }
59640
59641 /*
59642 ** Write data to the file.
59643 */
59644 static int jrnlWrite(
59645   sqlite3_file *pJfd,    /* The journal file into which to write */
59646   const void *zBuf,      /* Take data to be written from here */
59647   int iAmt,              /* Number of bytes to write */
59648   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
59649 ){
59650   int rc = SQLITE_OK;
59651   JournalFile *p = (JournalFile *)pJfd;
59652   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
59653     rc = createFile(p);
59654   }
59655   if( rc==SQLITE_OK ){
59656     if( p->pReal ){
59657       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
59658     }else{
59659       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
59660       if( p->iSize<(iOfst+iAmt) ){
59661         p->iSize = (iOfst+iAmt);
59662       }
59663     }
59664   }
59665   return rc;
59666 }
59667
59668 /*
59669 ** Truncate the file.
59670 */
59671 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
59672   int rc = SQLITE_OK;
59673   JournalFile *p = (JournalFile *)pJfd;
59674   if( p->pReal ){
59675     rc = sqlite3OsTruncate(p->pReal, size);
59676   }else if( size<p->iSize ){
59677     p->iSize = size;
59678   }
59679   return rc;
59680 }
59681
59682 /*
59683 ** Sync the file.
59684 */
59685 static int jrnlSync(sqlite3_file *pJfd, int flags){
59686   int rc;
59687   JournalFile *p = (JournalFile *)pJfd;
59688   if( p->pReal ){
59689     rc = sqlite3OsSync(p->pReal, flags);
59690   }else{
59691     rc = SQLITE_OK;
59692   }
59693   return rc;
59694 }
59695
59696 /*
59697 ** Query the size of the file in bytes.
59698 */
59699 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
59700   int rc = SQLITE_OK;
59701   JournalFile *p = (JournalFile *)pJfd;
59702   if( p->pReal ){
59703     rc = sqlite3OsFileSize(p->pReal, pSize);
59704   }else{
59705     *pSize = (sqlite_int64) p->iSize;
59706   }
59707   return rc;
59708 }
59709
59710 /*
59711 ** Table of methods for JournalFile sqlite3_file object.
59712 */
59713 static struct sqlite3_io_methods JournalFileMethods = {
59714   1,             /* iVersion */
59715   jrnlClose,     /* xClose */
59716   jrnlRead,      /* xRead */
59717   jrnlWrite,     /* xWrite */
59718   jrnlTruncate,  /* xTruncate */
59719   jrnlSync,      /* xSync */
59720   jrnlFileSize,  /* xFileSize */
59721   0,             /* xLock */
59722   0,             /* xUnlock */
59723   0,             /* xCheckReservedLock */
59724   0,             /* xFileControl */
59725   0,             /* xSectorSize */
59726   0              /* xDeviceCharacteristics */
59727 };
59728
59729 /* 
59730 ** Open a journal file.
59731 */
59732 SQLITE_PRIVATE int sqlite3JournalOpen(
59733   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
59734   const char *zName,         /* Name of the journal file */
59735   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
59736   int flags,                 /* Opening flags */
59737   int nBuf                   /* Bytes buffered before opening the file */
59738 ){
59739   JournalFile *p = (JournalFile *)pJfd;
59740   memset(p, 0, sqlite3JournalSize(pVfs));
59741   if( nBuf>0 ){
59742     p->zBuf = sqlite3MallocZero(nBuf);
59743     if( !p->zBuf ){
59744       return SQLITE_NOMEM;
59745     }
59746   }else{
59747     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
59748   }
59749   p->pMethod = &JournalFileMethods;
59750   p->nBuf = nBuf;
59751   p->flags = flags;
59752   p->zJournal = zName;
59753   p->pVfs = pVfs;
59754   return SQLITE_OK;
59755 }
59756
59757 /*
59758 ** If the argument p points to a JournalFile structure, and the underlying
59759 ** file has not yet been created, create it now.
59760 */
59761 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
59762   if( p->pMethods!=&JournalFileMethods ){
59763     return SQLITE_OK;
59764   }
59765   return createFile((JournalFile *)p);
59766 }
59767
59768 /* 
59769 ** Return the number of bytes required to store a JournalFile that uses vfs
59770 ** pVfs to create the underlying on-disk files.
59771 */
59772 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
59773   return (pVfs->szOsFile+sizeof(JournalFile));
59774 }
59775 #endif
59776
59777 /************** End of journal.c *********************************************/
59778 /************** Begin file memjournal.c **************************************/
59779 /*
59780 ** 2008 October 7
59781 **
59782 ** The author disclaims copyright to this source code.  In place of
59783 ** a legal notice, here is a blessing:
59784 **
59785 **    May you do good and not evil.
59786 **    May you find forgiveness for yourself and forgive others.
59787 **    May you share freely, never taking more than you give.
59788 **
59789 *************************************************************************
59790 **
59791 ** This file contains code use to implement an in-memory rollback journal.
59792 ** The in-memory rollback journal is used to journal transactions for
59793 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
59794 */
59795
59796 /* Forward references to internal structures */
59797 typedef struct MemJournal MemJournal;
59798 typedef struct FilePoint FilePoint;
59799 typedef struct FileChunk FileChunk;
59800
59801 /* Space to hold the rollback journal is allocated in increments of
59802 ** this many bytes.
59803 **
59804 ** The size chosen is a little less than a power of two.  That way,
59805 ** the FileChunk object will have a size that almost exactly fills
59806 ** a power-of-two allocation.  This mimimizes wasted space in power-of-two
59807 ** memory allocators.
59808 */
59809 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
59810
59811 /* Macro to find the minimum of two numeric values.
59812 */
59813 #ifndef MIN
59814 # define MIN(x,y) ((x)<(y)?(x):(y))
59815 #endif
59816
59817 /*
59818 ** The rollback journal is composed of a linked list of these structures.
59819 */
59820 struct FileChunk {
59821   FileChunk *pNext;               /* Next chunk in the journal */
59822   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
59823 };
59824
59825 /*
59826 ** An instance of this object serves as a cursor into the rollback journal.
59827 ** The cursor can be either for reading or writing.
59828 */
59829 struct FilePoint {
59830   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
59831   FileChunk *pChunk;              /* Specific chunk into which cursor points */
59832 };
59833
59834 /*
59835 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
59836 ** is an instance of this class.
59837 */
59838 struct MemJournal {
59839   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
59840   FileChunk *pFirst;              /* Head of in-memory chunk-list */
59841   FilePoint endpoint;             /* Pointer to the end of the file */
59842   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
59843 };
59844
59845 /*
59846 ** Read data from the in-memory journal file.  This is the implementation
59847 ** of the sqlite3_vfs.xRead method.
59848 */
59849 static int memjrnlRead(
59850   sqlite3_file *pJfd,    /* The journal file from which to read */
59851   void *zBuf,            /* Put the results here */
59852   int iAmt,              /* Number of bytes to read */
59853   sqlite_int64 iOfst     /* Begin reading at this offset */
59854 ){
59855   MemJournal *p = (MemJournal *)pJfd;
59856   u8 *zOut = zBuf;
59857   int nRead = iAmt;
59858   int iChunkOffset;
59859   FileChunk *pChunk;
59860
59861   /* SQLite never tries to read past the end of a rollback journal file */
59862   assert( iOfst+iAmt<=p->endpoint.iOffset );
59863
59864   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
59865     sqlite3_int64 iOff = 0;
59866     for(pChunk=p->pFirst; 
59867         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
59868         pChunk=pChunk->pNext
59869     ){
59870       iOff += JOURNAL_CHUNKSIZE;
59871     }
59872   }else{
59873     pChunk = p->readpoint.pChunk;
59874   }
59875
59876   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
59877   do {
59878     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
59879     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
59880     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
59881     zOut += nCopy;
59882     nRead -= iSpace;
59883     iChunkOffset = 0;
59884   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
59885   p->readpoint.iOffset = iOfst+iAmt;
59886   p->readpoint.pChunk = pChunk;
59887
59888   return SQLITE_OK;
59889 }
59890
59891 /*
59892 ** Write data to the file.
59893 */
59894 static int memjrnlWrite(
59895   sqlite3_file *pJfd,    /* The journal file into which to write */
59896   const void *zBuf,      /* Take data to be written from here */
59897   int iAmt,              /* Number of bytes to write */
59898   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
59899 ){
59900   MemJournal *p = (MemJournal *)pJfd;
59901   int nWrite = iAmt;
59902   u8 *zWrite = (u8 *)zBuf;
59903
59904   /* An in-memory journal file should only ever be appended to. Random
59905   ** access writes are not required by sqlite.
59906   */
59907   assert( iOfst==p->endpoint.iOffset );
59908   UNUSED_PARAMETER(iOfst);
59909
59910   while( nWrite>0 ){
59911     FileChunk *pChunk = p->endpoint.pChunk;
59912     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
59913     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
59914
59915     if( iChunkOffset==0 ){
59916       /* New chunk is required to extend the file. */
59917       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
59918       if( !pNew ){
59919         return SQLITE_IOERR_NOMEM;
59920       }
59921       pNew->pNext = 0;
59922       if( pChunk ){
59923         assert( p->pFirst );
59924         pChunk->pNext = pNew;
59925       }else{
59926         assert( !p->pFirst );
59927         p->pFirst = pNew;
59928       }
59929       p->endpoint.pChunk = pNew;
59930     }
59931
59932     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
59933     zWrite += iSpace;
59934     nWrite -= iSpace;
59935     p->endpoint.iOffset += iSpace;
59936   }
59937
59938   return SQLITE_OK;
59939 }
59940
59941 /*
59942 ** Truncate the file.
59943 */
59944 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
59945   MemJournal *p = (MemJournal *)pJfd;
59946   FileChunk *pChunk;
59947   assert(size==0);
59948   UNUSED_PARAMETER(size);
59949   pChunk = p->pFirst;
59950   while( pChunk ){
59951     FileChunk *pTmp = pChunk;
59952     pChunk = pChunk->pNext;
59953     sqlite3_free(pTmp);
59954   }
59955   sqlite3MemJournalOpen(pJfd);
59956   return SQLITE_OK;
59957 }
59958
59959 /*
59960 ** Close the file.
59961 */
59962 static int memjrnlClose(sqlite3_file *pJfd){
59963   memjrnlTruncate(pJfd, 0);
59964   return SQLITE_OK;
59965 }
59966
59967
59968 /*
59969 ** Sync the file.
59970 **
59971 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
59972 ** is never called in a working implementation.  This implementation
59973 ** exists purely as a contingency, in case some malfunction in some other
59974 ** part of SQLite causes Sync to be called by mistake.
59975 */
59976 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){   /*NO_TEST*/
59977   UNUSED_PARAMETER2(NotUsed, NotUsed2);                        /*NO_TEST*/
59978   assert( 0 );                                                 /*NO_TEST*/
59979   return SQLITE_OK;                                            /*NO_TEST*/
59980 }                                                              /*NO_TEST*/
59981
59982 /*
59983 ** Query the size of the file in bytes.
59984 */
59985 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
59986   MemJournal *p = (MemJournal *)pJfd;
59987   *pSize = (sqlite_int64) p->endpoint.iOffset;
59988   return SQLITE_OK;
59989 }
59990
59991 /*
59992 ** Table of methods for MemJournal sqlite3_file object.
59993 */
59994 static struct sqlite3_io_methods MemJournalMethods = {
59995   1,                /* iVersion */
59996   memjrnlClose,     /* xClose */
59997   memjrnlRead,      /* xRead */
59998   memjrnlWrite,     /* xWrite */
59999   memjrnlTruncate,  /* xTruncate */
60000   memjrnlSync,      /* xSync */
60001   memjrnlFileSize,  /* xFileSize */
60002   0,                /* xLock */
60003   0,                /* xUnlock */
60004   0,                /* xCheckReservedLock */
60005   0,                /* xFileControl */
60006   0,                /* xSectorSize */
60007   0                 /* xDeviceCharacteristics */
60008 };
60009
60010 /* 
60011 ** Open a journal file.
60012 */
60013 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
60014   MemJournal *p = (MemJournal *)pJfd;
60015   assert( EIGHT_BYTE_ALIGNMENT(p) );
60016   memset(p, 0, sqlite3MemJournalSize());
60017   p->pMethod = &MemJournalMethods;
60018 }
60019
60020 /*
60021 ** Return true if the file-handle passed as an argument is 
60022 ** an in-memory journal 
60023 */
60024 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
60025   return pJfd->pMethods==&MemJournalMethods;
60026 }
60027
60028 /* 
60029 ** Return the number of bytes required to store a MemJournal that uses vfs
60030 ** pVfs to create the underlying on-disk files.
60031 */
60032 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
60033   return sizeof(MemJournal);
60034 }
60035
60036 /************** End of memjournal.c ******************************************/
60037 /************** Begin file walker.c ******************************************/
60038 /*
60039 ** 2008 August 16
60040 **
60041 ** The author disclaims copyright to this source code.  In place of
60042 ** a legal notice, here is a blessing:
60043 **
60044 **    May you do good and not evil.
60045 **    May you find forgiveness for yourself and forgive others.
60046 **    May you share freely, never taking more than you give.
60047 **
60048 *************************************************************************
60049 ** This file contains routines used for walking the parser tree for
60050 ** an SQL statement.
60051 */
60052
60053
60054 /*
60055 ** Walk an expression tree.  Invoke the callback once for each node
60056 ** of the expression, while decending.  (In other words, the callback
60057 ** is invoked before visiting children.)
60058 **
60059 ** The return value from the callback should be one of the WRC_*
60060 ** constants to specify how to proceed with the walk.
60061 **
60062 **    WRC_Continue      Continue descending down the tree.
60063 **
60064 **    WRC_Prune         Do not descend into child nodes.  But allow
60065 **                      the walk to continue with sibling nodes.
60066 **
60067 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
60068 **                      return the top-level walk call.
60069 **
60070 ** The return value from this routine is WRC_Abort to abandon the tree walk
60071 ** and WRC_Continue to continue.
60072 */
60073 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
60074   int rc;
60075   if( pExpr==0 ) return WRC_Continue;
60076   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
60077   testcase( ExprHasProperty(pExpr, EP_Reduced) );
60078   rc = pWalker->xExprCallback(pWalker, pExpr);
60079   if( rc==WRC_Continue
60080               && !ExprHasAnyProperty(pExpr,EP_TokenOnly) ){
60081     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
60082     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
60083     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
60084       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
60085     }else{
60086       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
60087     }
60088   }
60089   return rc & WRC_Abort;
60090 }
60091
60092 /*
60093 ** Call sqlite3WalkExpr() for every expression in list p or until
60094 ** an abort request is seen.
60095 */
60096 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
60097   int i;
60098   struct ExprList_item *pItem;
60099   if( p ){
60100     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
60101       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
60102     }
60103   }
60104   return WRC_Continue;
60105 }
60106
60107 /*
60108 ** Walk all expressions associated with SELECT statement p.  Do
60109 ** not invoke the SELECT callback on p, but do (of course) invoke
60110 ** any expr callbacks and SELECT callbacks that come from subqueries.
60111 ** Return WRC_Abort or WRC_Continue.
60112 */
60113 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
60114   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
60115   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
60116   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
60117   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
60118   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
60119   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
60120   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
60121   return WRC_Continue;
60122 }
60123
60124 /*
60125 ** Walk the parse trees associated with all subqueries in the
60126 ** FROM clause of SELECT statement p.  Do not invoke the select
60127 ** callback on p, but do invoke it on each FROM clause subquery
60128 ** and on any subqueries further down in the tree.  Return 
60129 ** WRC_Abort or WRC_Continue;
60130 */
60131 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
60132   SrcList *pSrc;
60133   int i;
60134   struct SrcList_item *pItem;
60135
60136   pSrc = p->pSrc;
60137   if( ALWAYS(pSrc) ){
60138     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
60139       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
60140         return WRC_Abort;
60141       }
60142     }
60143   }
60144   return WRC_Continue;
60145
60146
60147 /*
60148 ** Call sqlite3WalkExpr() for every expression in Select statement p.
60149 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
60150 ** on the compound select chain, p->pPrior.
60151 **
60152 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
60153 ** there is an abort request.
60154 **
60155 ** If the Walker does not have an xSelectCallback() then this routine
60156 ** is a no-op returning WRC_Continue.
60157 */
60158 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
60159   int rc;
60160   if( p==0 || pWalker->xSelectCallback==0 ) return WRC_Continue;
60161   rc = WRC_Continue;
60162   while( p  ){
60163     rc = pWalker->xSelectCallback(pWalker, p);
60164     if( rc ) break;
60165     if( sqlite3WalkSelectExpr(pWalker, p) ) return WRC_Abort;
60166     if( sqlite3WalkSelectFrom(pWalker, p) ) return WRC_Abort;
60167     p = p->pPrior;
60168   }
60169   return rc & WRC_Abort;
60170 }
60171
60172 /************** End of walker.c **********************************************/
60173 /************** Begin file resolve.c *****************************************/
60174 /*
60175 ** 2008 August 18
60176 **
60177 ** The author disclaims copyright to this source code.  In place of
60178 ** a legal notice, here is a blessing:
60179 **
60180 **    May you do good and not evil.
60181 **    May you find forgiveness for yourself and forgive others.
60182 **    May you share freely, never taking more than you give.
60183 **
60184 *************************************************************************
60185 **
60186 ** This file contains routines used for walking the parser tree and
60187 ** resolve all identifiers by associating them with a particular
60188 ** table and column.
60189 */
60190
60191 /*
60192 ** Turn the pExpr expression into an alias for the iCol-th column of the
60193 ** result set in pEList.
60194 **
60195 ** If the result set column is a simple column reference, then this routine
60196 ** makes an exact copy.  But for any other kind of expression, this
60197 ** routine make a copy of the result set column as the argument to the
60198 ** TK_AS operator.  The TK_AS operator causes the expression to be
60199 ** evaluated just once and then reused for each alias.
60200 **
60201 ** The reason for suppressing the TK_AS term when the expression is a simple
60202 ** column reference is so that the column reference will be recognized as
60203 ** usable by indices within the WHERE clause processing logic. 
60204 **
60205 ** Hack:  The TK_AS operator is inhibited if zType[0]=='G'.  This means
60206 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
60207 **
60208 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
60209 **
60210 ** Is equivalent to:
60211 **
60212 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
60213 **
60214 ** The result of random()%5 in the GROUP BY clause is probably different
60215 ** from the result in the result-set.  We might fix this someday.  Or
60216 ** then again, we might not...
60217 */
60218 static void resolveAlias(
60219   Parse *pParse,         /* Parsing context */
60220   ExprList *pEList,      /* A result set */
60221   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
60222   Expr *pExpr,           /* Transform this into an alias to the result set */
60223   const char *zType      /* "GROUP" or "ORDER" or "" */
60224 ){
60225   Expr *pOrig;           /* The iCol-th column of the result set */
60226   Expr *pDup;            /* Copy of pOrig */
60227   sqlite3 *db;           /* The database connection */
60228
60229   assert( iCol>=0 && iCol<pEList->nExpr );
60230   pOrig = pEList->a[iCol].pExpr;
60231   assert( pOrig!=0 );
60232   assert( pOrig->flags & EP_Resolved );
60233   db = pParse->db;
60234   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
60235     pDup = sqlite3ExprDup(db, pOrig, 0);
60236     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
60237     if( pDup==0 ) return;
60238     if( pEList->a[iCol].iAlias==0 ){
60239       pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
60240     }
60241     pDup->iTable = pEList->a[iCol].iAlias;
60242   }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
60243     pDup = sqlite3ExprDup(db, pOrig, 0);
60244     if( pDup==0 ) return;
60245   }else{
60246     char *zToken = pOrig->u.zToken;
60247     assert( zToken!=0 );
60248     pOrig->u.zToken = 0;
60249     pDup = sqlite3ExprDup(db, pOrig, 0);
60250     pOrig->u.zToken = zToken;
60251     if( pDup==0 ) return;
60252     assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
60253     pDup->flags2 |= EP2_MallocedToken;
60254     pDup->u.zToken = sqlite3DbStrDup(db, zToken);
60255   }
60256   if( pExpr->flags & EP_ExpCollate ){
60257     pDup->pColl = pExpr->pColl;
60258     pDup->flags |= EP_ExpCollate;
60259   }
60260
60261   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
60262   ** prevents ExprDelete() from deleting the Expr structure itself,
60263   ** allowing it to be repopulated by the memcpy() on the following line.
60264   */
60265   ExprSetProperty(pExpr, EP_Static);
60266   sqlite3ExprDelete(db, pExpr);
60267   memcpy(pExpr, pDup, sizeof(*pExpr));
60268   sqlite3DbFree(db, pDup);
60269 }
60270
60271 /*
60272 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
60273 ** that name in the set of source tables in pSrcList and make the pExpr 
60274 ** expression node refer back to that source column.  The following changes
60275 ** are made to pExpr:
60276 **
60277 **    pExpr->iDb           Set the index in db->aDb[] of the database X
60278 **                         (even if X is implied).
60279 **    pExpr->iTable        Set to the cursor number for the table obtained
60280 **                         from pSrcList.
60281 **    pExpr->pTab          Points to the Table structure of X.Y (even if
60282 **                         X and/or Y are implied.)
60283 **    pExpr->iColumn       Set to the column number within the table.
60284 **    pExpr->op            Set to TK_COLUMN.
60285 **    pExpr->pLeft         Any expression this points to is deleted
60286 **    pExpr->pRight        Any expression this points to is deleted.
60287 **
60288 ** The zDb variable is the name of the database (the "X").  This value may be
60289 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
60290 ** can be used.  The zTable variable is the name of the table (the "Y").  This
60291 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
60292 ** means that the form of the name is Z and that columns from any table
60293 ** can be used.
60294 **
60295 ** If the name cannot be resolved unambiguously, leave an error message
60296 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
60297 */
60298 static int lookupName(
60299   Parse *pParse,       /* The parsing context */
60300   const char *zDb,     /* Name of the database containing table, or NULL */
60301   const char *zTab,    /* Name of table containing column, or NULL */
60302   const char *zCol,    /* Name of the column. */
60303   NameContext *pNC,    /* The name context used to resolve the name */
60304   Expr *pExpr          /* Make this EXPR node point to the selected column */
60305 ){
60306   int i, j;            /* Loop counters */
60307   int cnt = 0;                      /* Number of matching column names */
60308   int cntTab = 0;                   /* Number of matching table names */
60309   sqlite3 *db = pParse->db;         /* The database connection */
60310   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
60311   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
60312   NameContext *pTopNC = pNC;        /* First namecontext in the list */
60313   Schema *pSchema = 0;              /* Schema of the expression */
60314   int isTrigger = 0;
60315
60316   assert( pNC );     /* the name context cannot be NULL. */
60317   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
60318   assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
60319
60320   /* Initialize the node to no-match */
60321   pExpr->iTable = -1;
60322   pExpr->pTab = 0;
60323   ExprSetIrreducible(pExpr);
60324
60325   /* Start at the inner-most context and move outward until a match is found */
60326   while( pNC && cnt==0 ){
60327     ExprList *pEList;
60328     SrcList *pSrcList = pNC->pSrcList;
60329
60330     if( pSrcList ){
60331       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
60332         Table *pTab;
60333         int iDb;
60334         Column *pCol;
60335   
60336         pTab = pItem->pTab;
60337         assert( pTab!=0 && pTab->zName!=0 );
60338         iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
60339         assert( pTab->nCol>0 );
60340         if( zTab ){
60341           if( pItem->zAlias ){
60342             char *zTabName = pItem->zAlias;
60343             if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
60344           }else{
60345             char *zTabName = pTab->zName;
60346             if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
60347               continue;
60348             }
60349             if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
60350               continue;
60351             }
60352           }
60353         }
60354         if( 0==(cntTab++) ){
60355           pExpr->iTable = pItem->iCursor;
60356           pExpr->pTab = pTab;
60357           pSchema = pTab->pSchema;
60358           pMatch = pItem;
60359         }
60360         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
60361           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
60362             IdList *pUsing;
60363             cnt++;
60364             pExpr->iTable = pItem->iCursor;
60365             pExpr->pTab = pTab;
60366             pMatch = pItem;
60367             pSchema = pTab->pSchema;
60368             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
60369             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
60370             if( i<pSrcList->nSrc-1 ){
60371               if( pItem[1].jointype & JT_NATURAL ){
60372                 /* If this match occurred in the left table of a natural join,
60373                 ** then skip the right table to avoid a duplicate match */
60374                 pItem++;
60375                 i++;
60376               }else if( (pUsing = pItem[1].pUsing)!=0 ){
60377                 /* If this match occurs on a column that is in the USING clause
60378                 ** of a join, skip the search of the right table of the join
60379                 ** to avoid a duplicate match there. */
60380                 int k;
60381                 for(k=0; k<pUsing->nId; k++){
60382                   if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
60383                     pItem++;
60384                     i++;
60385                     break;
60386                   }
60387                 }
60388               }
60389             }
60390             break;
60391           }
60392         }
60393       }
60394     }
60395
60396 #ifndef SQLITE_OMIT_TRIGGER
60397     /* If we have not already resolved the name, then maybe 
60398     ** it is a new.* or old.* trigger argument reference
60399     */
60400     if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
60401       int op = pParse->eTriggerOp;
60402       Table *pTab = 0;
60403       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
60404       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
60405         pExpr->iTable = 1;
60406         pTab = pParse->pTriggerTab;
60407       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
60408         pExpr->iTable = 0;
60409         pTab = pParse->pTriggerTab;
60410       }
60411
60412       if( pTab ){ 
60413         int iCol;
60414         pSchema = pTab->pSchema;
60415         cntTab++;
60416         for(iCol=0; iCol<pTab->nCol; iCol++){
60417           Column *pCol = &pTab->aCol[iCol];
60418           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
60419             if( iCol==pTab->iPKey ){
60420               iCol = -1;
60421             }
60422             break;
60423           }
60424         }
60425         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
60426           iCol = -1;        /* IMP: R-44911-55124 */
60427         }
60428         if( iCol<pTab->nCol ){
60429           cnt++;
60430           if( iCol<0 ){
60431             pExpr->affinity = SQLITE_AFF_INTEGER;
60432           }else if( pExpr->iTable==0 ){
60433             testcase( iCol==31 );
60434             testcase( iCol==32 );
60435             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
60436           }else{
60437             testcase( iCol==31 );
60438             testcase( iCol==32 );
60439             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
60440           }
60441           pExpr->iColumn = (i16)iCol;
60442           pExpr->pTab = pTab;
60443           isTrigger = 1;
60444         }
60445       }
60446     }
60447 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
60448
60449     /*
60450     ** Perhaps the name is a reference to the ROWID
60451     */
60452     if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
60453       cnt = 1;
60454       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
60455       pExpr->affinity = SQLITE_AFF_INTEGER;
60456     }
60457
60458     /*
60459     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
60460     ** might refer to an result-set alias.  This happens, for example, when
60461     ** we are resolving names in the WHERE clause of the following command:
60462     **
60463     **     SELECT a+b AS x FROM table WHERE x<10;
60464     **
60465     ** In cases like this, replace pExpr with a copy of the expression that
60466     ** forms the result set entry ("a+b" in the example) and return immediately.
60467     ** Note that the expression in the result set should have already been
60468     ** resolved by the time the WHERE clause is resolved.
60469     */
60470     if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
60471       for(j=0; j<pEList->nExpr; j++){
60472         char *zAs = pEList->a[j].zName;
60473         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
60474           Expr *pOrig;
60475           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
60476           assert( pExpr->x.pList==0 );
60477           assert( pExpr->x.pSelect==0 );
60478           pOrig = pEList->a[j].pExpr;
60479           if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
60480             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
60481             return WRC_Abort;
60482           }
60483           resolveAlias(pParse, pEList, j, pExpr, "");
60484           cnt = 1;
60485           pMatch = 0;
60486           assert( zTab==0 && zDb==0 );
60487           goto lookupname_end;
60488         }
60489       } 
60490     }
60491
60492     /* Advance to the next name context.  The loop will exit when either
60493     ** we have a match (cnt>0) or when we run out of name contexts.
60494     */
60495     if( cnt==0 ){
60496       pNC = pNC->pNext;
60497     }
60498   }
60499
60500   /*
60501   ** If X and Y are NULL (in other words if only the column name Z is
60502   ** supplied) and the value of Z is enclosed in double-quotes, then
60503   ** Z is a string literal if it doesn't match any column names.  In that
60504   ** case, we need to return right away and not make any changes to
60505   ** pExpr.
60506   **
60507   ** Because no reference was made to outer contexts, the pNC->nRef
60508   ** fields are not changed in any context.
60509   */
60510   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
60511     pExpr->op = TK_STRING;
60512     pExpr->pTab = 0;
60513     return WRC_Prune;
60514   }
60515
60516   /*
60517   ** cnt==0 means there was not match.  cnt>1 means there were two or
60518   ** more matches.  Either way, we have an error.
60519   */
60520   if( cnt!=1 ){
60521     const char *zErr;
60522     zErr = cnt==0 ? "no such column" : "ambiguous column name";
60523     if( zDb ){
60524       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
60525     }else if( zTab ){
60526       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
60527     }else{
60528       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
60529     }
60530     pTopNC->nErr++;
60531   }
60532
60533   /* If a column from a table in pSrcList is referenced, then record
60534   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
60535   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
60536   ** column number is greater than the number of bits in the bitmask
60537   ** then set the high-order bit of the bitmask.
60538   */
60539   if( pExpr->iColumn>=0 && pMatch!=0 ){
60540     int n = pExpr->iColumn;
60541     testcase( n==BMS-1 );
60542     if( n>=BMS ){
60543       n = BMS-1;
60544     }
60545     assert( pMatch->iCursor==pExpr->iTable );
60546     pMatch->colUsed |= ((Bitmask)1)<<n;
60547   }
60548
60549   /* Clean up and return
60550   */
60551   sqlite3ExprDelete(db, pExpr->pLeft);
60552   pExpr->pLeft = 0;
60553   sqlite3ExprDelete(db, pExpr->pRight);
60554   pExpr->pRight = 0;
60555   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
60556 lookupname_end:
60557   if( cnt==1 ){
60558     assert( pNC!=0 );
60559     sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
60560     /* Increment the nRef value on all name contexts from TopNC up to
60561     ** the point where the name matched. */
60562     for(;;){
60563       assert( pTopNC!=0 );
60564       pTopNC->nRef++;
60565       if( pTopNC==pNC ) break;
60566       pTopNC = pTopNC->pNext;
60567     }
60568     return WRC_Prune;
60569   } else {
60570     return WRC_Abort;
60571   }
60572 }
60573
60574 /*
60575 ** Allocate and return a pointer to an expression to load the column iCol
60576 ** from datasource iSrc datasource in SrcList pSrc.
60577 */
60578 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
60579   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
60580   if( p ){
60581     struct SrcList_item *pItem = &pSrc->a[iSrc];
60582     p->pTab = pItem->pTab;
60583     p->iTable = pItem->iCursor;
60584     if( p->pTab->iPKey==iCol ){
60585       p->iColumn = -1;
60586     }else{
60587       p->iColumn = (ynVar)iCol;
60588       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
60589     }
60590     ExprSetProperty(p, EP_Resolved);
60591   }
60592   return p;
60593 }
60594
60595 /*
60596 ** This routine is callback for sqlite3WalkExpr().
60597 **
60598 ** Resolve symbolic names into TK_COLUMN operators for the current
60599 ** node in the expression tree.  Return 0 to continue the search down
60600 ** the tree or 2 to abort the tree walk.
60601 **
60602 ** This routine also does error checking and name resolution for
60603 ** function names.  The operator for aggregate functions is changed
60604 ** to TK_AGG_FUNCTION.
60605 */
60606 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
60607   NameContext *pNC;
60608   Parse *pParse;
60609
60610   pNC = pWalker->u.pNC;
60611   assert( pNC!=0 );
60612   pParse = pNC->pParse;
60613   assert( pParse==pWalker->pParse );
60614
60615   if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
60616   ExprSetProperty(pExpr, EP_Resolved);
60617 #ifndef NDEBUG
60618   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
60619     SrcList *pSrcList = pNC->pSrcList;
60620     int i;
60621     for(i=0; i<pNC->pSrcList->nSrc; i++){
60622       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
60623     }
60624   }
60625 #endif
60626   switch( pExpr->op ){
60627
60628 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
60629     /* The special operator TK_ROW means use the rowid for the first
60630     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
60631     ** clause processing on UPDATE and DELETE statements.
60632     */
60633     case TK_ROW: {
60634       SrcList *pSrcList = pNC->pSrcList;
60635       struct SrcList_item *pItem;
60636       assert( pSrcList && pSrcList->nSrc==1 );
60637       pItem = pSrcList->a; 
60638       pExpr->op = TK_COLUMN;
60639       pExpr->pTab = pItem->pTab;
60640       pExpr->iTable = pItem->iCursor;
60641       pExpr->iColumn = -1;
60642       pExpr->affinity = SQLITE_AFF_INTEGER;
60643       break;
60644     }
60645 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
60646
60647     /* A lone identifier is the name of a column.
60648     */
60649     case TK_ID: {
60650       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
60651     }
60652   
60653     /* A table name and column name:     ID.ID
60654     ** Or a database, table and column:  ID.ID.ID
60655     */
60656     case TK_DOT: {
60657       const char *zColumn;
60658       const char *zTable;
60659       const char *zDb;
60660       Expr *pRight;
60661
60662       /* if( pSrcList==0 ) break; */
60663       pRight = pExpr->pRight;
60664       if( pRight->op==TK_ID ){
60665         zDb = 0;
60666         zTable = pExpr->pLeft->u.zToken;
60667         zColumn = pRight->u.zToken;
60668       }else{
60669         assert( pRight->op==TK_DOT );
60670         zDb = pExpr->pLeft->u.zToken;
60671         zTable = pRight->pLeft->u.zToken;
60672         zColumn = pRight->pRight->u.zToken;
60673       }
60674       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
60675     }
60676
60677     /* Resolve function names
60678     */
60679     case TK_CONST_FUNC:
60680     case TK_FUNCTION: {
60681       ExprList *pList = pExpr->x.pList;    /* The argument list */
60682       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
60683       int no_such_func = 0;       /* True if no such function exists */
60684       int wrong_num_args = 0;     /* True if wrong number of arguments */
60685       int is_agg = 0;             /* True if is an aggregate function */
60686       int auth;                   /* Authorization to use the function */
60687       int nId;                    /* Number of characters in function name */
60688       const char *zId;            /* The function name. */
60689       FuncDef *pDef;              /* Information about the function */
60690       u8 enc = ENC(pParse->db);   /* The database encoding */
60691
60692       testcase( pExpr->op==TK_CONST_FUNC );
60693       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
60694       zId = pExpr->u.zToken;
60695       nId = sqlite3Strlen30(zId);
60696       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
60697       if( pDef==0 ){
60698         pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
60699         if( pDef==0 ){
60700           no_such_func = 1;
60701         }else{
60702           wrong_num_args = 1;
60703         }
60704       }else{
60705         is_agg = pDef->xFunc==0;
60706       }
60707 #ifndef SQLITE_OMIT_AUTHORIZATION
60708       if( pDef ){
60709         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
60710         if( auth!=SQLITE_OK ){
60711           if( auth==SQLITE_DENY ){
60712             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
60713                                     pDef->zName);
60714             pNC->nErr++;
60715           }
60716           pExpr->op = TK_NULL;
60717           return WRC_Prune;
60718         }
60719       }
60720 #endif
60721       if( is_agg && !pNC->allowAgg ){
60722         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
60723         pNC->nErr++;
60724         is_agg = 0;
60725       }else if( no_such_func ){
60726         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
60727         pNC->nErr++;
60728       }else if( wrong_num_args ){
60729         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
60730              nId, zId);
60731         pNC->nErr++;
60732       }
60733       if( is_agg ){
60734         pExpr->op = TK_AGG_FUNCTION;
60735         pNC->hasAgg = 1;
60736       }
60737       if( is_agg ) pNC->allowAgg = 0;
60738       sqlite3WalkExprList(pWalker, pList);
60739       if( is_agg ) pNC->allowAgg = 1;
60740       /* FIX ME:  Compute pExpr->affinity based on the expected return
60741       ** type of the function 
60742       */
60743       return WRC_Prune;
60744     }
60745 #ifndef SQLITE_OMIT_SUBQUERY
60746     case TK_SELECT:
60747     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
60748 #endif
60749     case TK_IN: {
60750       testcase( pExpr->op==TK_IN );
60751       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
60752         int nRef = pNC->nRef;
60753 #ifndef SQLITE_OMIT_CHECK
60754         if( pNC->isCheck ){
60755           sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
60756         }
60757 #endif
60758         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
60759         assert( pNC->nRef>=nRef );
60760         if( nRef!=pNC->nRef ){
60761           ExprSetProperty(pExpr, EP_VarSelect);
60762         }
60763       }
60764       break;
60765     }
60766 #ifndef SQLITE_OMIT_CHECK
60767     case TK_VARIABLE: {
60768       if( pNC->isCheck ){
60769         sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
60770       }
60771       break;
60772     }
60773 #endif
60774   }
60775   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
60776 }
60777
60778 /*
60779 ** pEList is a list of expressions which are really the result set of the
60780 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
60781 ** This routine checks to see if pE is a simple identifier which corresponds
60782 ** to the AS-name of one of the terms of the expression list.  If it is,
60783 ** this routine return an integer between 1 and N where N is the number of
60784 ** elements in pEList, corresponding to the matching entry.  If there is
60785 ** no match, or if pE is not a simple identifier, then this routine
60786 ** return 0.
60787 **
60788 ** pEList has been resolved.  pE has not.
60789 */
60790 static int resolveAsName(
60791   Parse *pParse,     /* Parsing context for error messages */
60792   ExprList *pEList,  /* List of expressions to scan */
60793   Expr *pE           /* Expression we are trying to match */
60794 ){
60795   int i;             /* Loop counter */
60796
60797   UNUSED_PARAMETER(pParse);
60798
60799   if( pE->op==TK_ID ){
60800     char *zCol = pE->u.zToken;
60801     for(i=0; i<pEList->nExpr; i++){
60802       char *zAs = pEList->a[i].zName;
60803       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
60804         return i+1;
60805       }
60806     }
60807   }
60808   return 0;
60809 }
60810
60811 /*
60812 ** pE is a pointer to an expression which is a single term in the
60813 ** ORDER BY of a compound SELECT.  The expression has not been
60814 ** name resolved.
60815 **
60816 ** At the point this routine is called, we already know that the
60817 ** ORDER BY term is not an integer index into the result set.  That
60818 ** case is handled by the calling routine.
60819 **
60820 ** Attempt to match pE against result set columns in the left-most
60821 ** SELECT statement.  Return the index i of the matching column,
60822 ** as an indication to the caller that it should sort by the i-th column.
60823 ** The left-most column is 1.  In other words, the value returned is the
60824 ** same integer value that would be used in the SQL statement to indicate
60825 ** the column.
60826 **
60827 ** If there is no match, return 0.  Return -1 if an error occurs.
60828 */
60829 static int resolveOrderByTermToExprList(
60830   Parse *pParse,     /* Parsing context for error messages */
60831   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
60832   Expr *pE           /* The specific ORDER BY term */
60833 ){
60834   int i;             /* Loop counter */
60835   ExprList *pEList;  /* The columns of the result set */
60836   NameContext nc;    /* Name context for resolving pE */
60837   sqlite3 *db;       /* Database connection */
60838   int rc;            /* Return code from subprocedures */
60839   u8 savedSuppErr;   /* Saved value of db->suppressErr */
60840
60841   assert( sqlite3ExprIsInteger(pE, &i)==0 );
60842   pEList = pSelect->pEList;
60843
60844   /* Resolve all names in the ORDER BY term expression
60845   */
60846   memset(&nc, 0, sizeof(nc));
60847   nc.pParse = pParse;
60848   nc.pSrcList = pSelect->pSrc;
60849   nc.pEList = pEList;
60850   nc.allowAgg = 1;
60851   nc.nErr = 0;
60852   db = pParse->db;
60853   savedSuppErr = db->suppressErr;
60854   db->suppressErr = 1;
60855   rc = sqlite3ResolveExprNames(&nc, pE);
60856   db->suppressErr = savedSuppErr;
60857   if( rc ) return 0;
60858
60859   /* Try to match the ORDER BY expression against an expression
60860   ** in the result set.  Return an 1-based index of the matching
60861   ** result-set entry.
60862   */
60863   for(i=0; i<pEList->nExpr; i++){
60864     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
60865       return i+1;
60866     }
60867   }
60868
60869   /* If no match, return 0. */
60870   return 0;
60871 }
60872
60873 /*
60874 ** Generate an ORDER BY or GROUP BY term out-of-range error.
60875 */
60876 static void resolveOutOfRangeError(
60877   Parse *pParse,         /* The error context into which to write the error */
60878   const char *zType,     /* "ORDER" or "GROUP" */
60879   int i,                 /* The index (1-based) of the term out of range */
60880   int mx                 /* Largest permissible value of i */
60881 ){
60882   sqlite3ErrorMsg(pParse, 
60883     "%r %s BY term out of range - should be "
60884     "between 1 and %d", i, zType, mx);
60885 }
60886
60887 /*
60888 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
60889 ** each term of the ORDER BY clause is a constant integer between 1
60890 ** and N where N is the number of columns in the compound SELECT.
60891 **
60892 ** ORDER BY terms that are already an integer between 1 and N are
60893 ** unmodified.  ORDER BY terms that are integers outside the range of
60894 ** 1 through N generate an error.  ORDER BY terms that are expressions
60895 ** are matched against result set expressions of compound SELECT
60896 ** beginning with the left-most SELECT and working toward the right.
60897 ** At the first match, the ORDER BY expression is transformed into
60898 ** the integer column number.
60899 **
60900 ** Return the number of errors seen.
60901 */
60902 static int resolveCompoundOrderBy(
60903   Parse *pParse,        /* Parsing context.  Leave error messages here */
60904   Select *pSelect       /* The SELECT statement containing the ORDER BY */
60905 ){
60906   int i;
60907   ExprList *pOrderBy;
60908   ExprList *pEList;
60909   sqlite3 *db;
60910   int moreToDo = 1;
60911
60912   pOrderBy = pSelect->pOrderBy;
60913   if( pOrderBy==0 ) return 0;
60914   db = pParse->db;
60915 #if SQLITE_MAX_COLUMN
60916   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
60917     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
60918     return 1;
60919   }
60920 #endif
60921   for(i=0; i<pOrderBy->nExpr; i++){
60922     pOrderBy->a[i].done = 0;
60923   }
60924   pSelect->pNext = 0;
60925   while( pSelect->pPrior ){
60926     pSelect->pPrior->pNext = pSelect;
60927     pSelect = pSelect->pPrior;
60928   }
60929   while( pSelect && moreToDo ){
60930     struct ExprList_item *pItem;
60931     moreToDo = 0;
60932     pEList = pSelect->pEList;
60933     assert( pEList!=0 );
60934     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
60935       int iCol = -1;
60936       Expr *pE, *pDup;
60937       if( pItem->done ) continue;
60938       pE = pItem->pExpr;
60939       if( sqlite3ExprIsInteger(pE, &iCol) ){
60940         if( iCol<=0 || iCol>pEList->nExpr ){
60941           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
60942           return 1;
60943         }
60944       }else{
60945         iCol = resolveAsName(pParse, pEList, pE);
60946         if( iCol==0 ){
60947           pDup = sqlite3ExprDup(db, pE, 0);
60948           if( !db->mallocFailed ){
60949             assert(pDup);
60950             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
60951           }
60952           sqlite3ExprDelete(db, pDup);
60953         }
60954       }
60955       if( iCol>0 ){
60956         CollSeq *pColl = pE->pColl;
60957         int flags = pE->flags & EP_ExpCollate;
60958         sqlite3ExprDelete(db, pE);
60959         pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
60960         if( pE==0 ) return 1;
60961         pE->pColl = pColl;
60962         pE->flags |= EP_IntValue | flags;
60963         pE->u.iValue = iCol;
60964         pItem->iCol = (u16)iCol;
60965         pItem->done = 1;
60966       }else{
60967         moreToDo = 1;
60968       }
60969     }
60970     pSelect = pSelect->pNext;
60971   }
60972   for(i=0; i<pOrderBy->nExpr; i++){
60973     if( pOrderBy->a[i].done==0 ){
60974       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
60975             "column in the result set", i+1);
60976       return 1;
60977     }
60978   }
60979   return 0;
60980 }
60981
60982 /*
60983 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
60984 ** the SELECT statement pSelect.  If any term is reference to a
60985 ** result set expression (as determined by the ExprList.a.iCol field)
60986 ** then convert that term into a copy of the corresponding result set
60987 ** column.
60988 **
60989 ** If any errors are detected, add an error message to pParse and
60990 ** return non-zero.  Return zero if no errors are seen.
60991 */
60992 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
60993   Parse *pParse,        /* Parsing context.  Leave error messages here */
60994   Select *pSelect,      /* The SELECT statement containing the clause */
60995   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
60996   const char *zType     /* "ORDER" or "GROUP" */
60997 ){
60998   int i;
60999   sqlite3 *db = pParse->db;
61000   ExprList *pEList;
61001   struct ExprList_item *pItem;
61002
61003   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
61004 #if SQLITE_MAX_COLUMN
61005   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
61006     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
61007     return 1;
61008   }
61009 #endif
61010   pEList = pSelect->pEList;
61011   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
61012   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
61013     if( pItem->iCol ){
61014       if( pItem->iCol>pEList->nExpr ){
61015         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
61016         return 1;
61017       }
61018       resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
61019     }
61020   }
61021   return 0;
61022 }
61023
61024 /*
61025 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
61026 ** The Name context of the SELECT statement is pNC.  zType is either
61027 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
61028 **
61029 ** This routine resolves each term of the clause into an expression.
61030 ** If the order-by term is an integer I between 1 and N (where N is the
61031 ** number of columns in the result set of the SELECT) then the expression
61032 ** in the resolution is a copy of the I-th result-set expression.  If
61033 ** the order-by term is an identify that corresponds to the AS-name of
61034 ** a result-set expression, then the term resolves to a copy of the
61035 ** result-set expression.  Otherwise, the expression is resolved in
61036 ** the usual way - using sqlite3ResolveExprNames().
61037 **
61038 ** This routine returns the number of errors.  If errors occur, then
61039 ** an appropriate error message might be left in pParse.  (OOM errors
61040 ** excepted.)
61041 */
61042 static int resolveOrderGroupBy(
61043   NameContext *pNC,     /* The name context of the SELECT statement */
61044   Select *pSelect,      /* The SELECT statement holding pOrderBy */
61045   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
61046   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
61047 ){
61048   int i;                         /* Loop counter */
61049   int iCol;                      /* Column number */
61050   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
61051   Parse *pParse;                 /* Parsing context */
61052   int nResult;                   /* Number of terms in the result set */
61053
61054   if( pOrderBy==0 ) return 0;
61055   nResult = pSelect->pEList->nExpr;
61056   pParse = pNC->pParse;
61057   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
61058     Expr *pE = pItem->pExpr;
61059     iCol = resolveAsName(pParse, pSelect->pEList, pE);
61060     if( iCol>0 ){
61061       /* If an AS-name match is found, mark this ORDER BY column as being
61062       ** a copy of the iCol-th result-set column.  The subsequent call to
61063       ** sqlite3ResolveOrderGroupBy() will convert the expression to a
61064       ** copy of the iCol-th result-set expression. */
61065       pItem->iCol = (u16)iCol;
61066       continue;
61067     }
61068     if( sqlite3ExprIsInteger(pE, &iCol) ){
61069       /* The ORDER BY term is an integer constant.  Again, set the column
61070       ** number so that sqlite3ResolveOrderGroupBy() will convert the
61071       ** order-by term to a copy of the result-set expression */
61072       if( iCol<1 ){
61073         resolveOutOfRangeError(pParse, zType, i+1, nResult);
61074         return 1;
61075       }
61076       pItem->iCol = (u16)iCol;
61077       continue;
61078     }
61079
61080     /* Otherwise, treat the ORDER BY term as an ordinary expression */
61081     pItem->iCol = 0;
61082     if( sqlite3ResolveExprNames(pNC, pE) ){
61083       return 1;
61084     }
61085   }
61086   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
61087 }
61088
61089 /*
61090 ** Resolve names in the SELECT statement p and all of its descendents.
61091 */
61092 static int resolveSelectStep(Walker *pWalker, Select *p){
61093   NameContext *pOuterNC;  /* Context that contains this SELECT */
61094   NameContext sNC;        /* Name context of this SELECT */
61095   int isCompound;         /* True if p is a compound select */
61096   int nCompound;          /* Number of compound terms processed so far */
61097   Parse *pParse;          /* Parsing context */
61098   ExprList *pEList;       /* Result set expression list */
61099   int i;                  /* Loop counter */
61100   ExprList *pGroupBy;     /* The GROUP BY clause */
61101   Select *pLeftmost;      /* Left-most of SELECT of a compound */
61102   sqlite3 *db;            /* Database connection */
61103   
61104
61105   assert( p!=0 );
61106   if( p->selFlags & SF_Resolved ){
61107     return WRC_Prune;
61108   }
61109   pOuterNC = pWalker->u.pNC;
61110   pParse = pWalker->pParse;
61111   db = pParse->db;
61112
61113   /* Normally sqlite3SelectExpand() will be called first and will have
61114   ** already expanded this SELECT.  However, if this is a subquery within
61115   ** an expression, sqlite3ResolveExprNames() will be called without a
61116   ** prior call to sqlite3SelectExpand().  When that happens, let
61117   ** sqlite3SelectPrep() do all of the processing for this SELECT.
61118   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
61119   ** this routine in the correct order.
61120   */
61121   if( (p->selFlags & SF_Expanded)==0 ){
61122     sqlite3SelectPrep(pParse, p, pOuterNC);
61123     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
61124   }
61125
61126   isCompound = p->pPrior!=0;
61127   nCompound = 0;
61128   pLeftmost = p;
61129   while( p ){
61130     assert( (p->selFlags & SF_Expanded)!=0 );
61131     assert( (p->selFlags & SF_Resolved)==0 );
61132     p->selFlags |= SF_Resolved;
61133
61134     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
61135     ** are not allowed to refer to any names, so pass an empty NameContext.
61136     */
61137     memset(&sNC, 0, sizeof(sNC));
61138     sNC.pParse = pParse;
61139     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
61140         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
61141       return WRC_Abort;
61142     }
61143   
61144     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
61145     ** resolve the result-set expression list.
61146     */
61147     sNC.allowAgg = 1;
61148     sNC.pSrcList = p->pSrc;
61149     sNC.pNext = pOuterNC;
61150   
61151     /* Resolve names in the result set. */
61152     pEList = p->pEList;
61153     assert( pEList!=0 );
61154     for(i=0; i<pEList->nExpr; i++){
61155       Expr *pX = pEList->a[i].pExpr;
61156       if( sqlite3ResolveExprNames(&sNC, pX) ){
61157         return WRC_Abort;
61158       }
61159     }
61160   
61161     /* Recursively resolve names in all subqueries
61162     */
61163     for(i=0; i<p->pSrc->nSrc; i++){
61164       struct SrcList_item *pItem = &p->pSrc->a[i];
61165       if( pItem->pSelect ){
61166         const char *zSavedContext = pParse->zAuthContext;
61167         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
61168         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
61169         pParse->zAuthContext = zSavedContext;
61170         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
61171       }
61172     }
61173   
61174     /* If there are no aggregate functions in the result-set, and no GROUP BY 
61175     ** expression, do not allow aggregates in any of the other expressions.
61176     */
61177     assert( (p->selFlags & SF_Aggregate)==0 );
61178     pGroupBy = p->pGroupBy;
61179     if( pGroupBy || sNC.hasAgg ){
61180       p->selFlags |= SF_Aggregate;
61181     }else{
61182       sNC.allowAgg = 0;
61183     }
61184   
61185     /* If a HAVING clause is present, then there must be a GROUP BY clause.
61186     */
61187     if( p->pHaving && !pGroupBy ){
61188       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
61189       return WRC_Abort;
61190     }
61191   
61192     /* Add the expression list to the name-context before parsing the
61193     ** other expressions in the SELECT statement. This is so that
61194     ** expressions in the WHERE clause (etc.) can refer to expressions by
61195     ** aliases in the result set.
61196     **
61197     ** Minor point: If this is the case, then the expression will be
61198     ** re-evaluated for each reference to it.
61199     */
61200     sNC.pEList = p->pEList;
61201     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
61202        sqlite3ResolveExprNames(&sNC, p->pHaving)
61203     ){
61204       return WRC_Abort;
61205     }
61206
61207     /* The ORDER BY and GROUP BY clauses may not refer to terms in
61208     ** outer queries 
61209     */
61210     sNC.pNext = 0;
61211     sNC.allowAgg = 1;
61212
61213     /* Process the ORDER BY clause for singleton SELECT statements.
61214     ** The ORDER BY clause for compounds SELECT statements is handled
61215     ** below, after all of the result-sets for all of the elements of
61216     ** the compound have been resolved.
61217     */
61218     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
61219       return WRC_Abort;
61220     }
61221     if( db->mallocFailed ){
61222       return WRC_Abort;
61223     }
61224   
61225     /* Resolve the GROUP BY clause.  At the same time, make sure 
61226     ** the GROUP BY clause does not contain aggregate functions.
61227     */
61228     if( pGroupBy ){
61229       struct ExprList_item *pItem;
61230     
61231       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
61232         return WRC_Abort;
61233       }
61234       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
61235         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
61236           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
61237               "the GROUP BY clause");
61238           return WRC_Abort;
61239         }
61240       }
61241     }
61242
61243     /* Advance to the next term of the compound
61244     */
61245     p = p->pPrior;
61246     nCompound++;
61247   }
61248
61249   /* Resolve the ORDER BY on a compound SELECT after all terms of
61250   ** the compound have been resolved.
61251   */
61252   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
61253     return WRC_Abort;
61254   }
61255
61256   return WRC_Prune;
61257 }
61258
61259 /*
61260 ** This routine walks an expression tree and resolves references to
61261 ** table columns and result-set columns.  At the same time, do error
61262 ** checking on function usage and set a flag if any aggregate functions
61263 ** are seen.
61264 **
61265 ** To resolve table columns references we look for nodes (or subtrees) of the 
61266 ** form X.Y.Z or Y.Z or just Z where
61267 **
61268 **      X:   The name of a database.  Ex:  "main" or "temp" or
61269 **           the symbolic name assigned to an ATTACH-ed database.
61270 **
61271 **      Y:   The name of a table in a FROM clause.  Or in a trigger
61272 **           one of the special names "old" or "new".
61273 **
61274 **      Z:   The name of a column in table Y.
61275 **
61276 ** The node at the root of the subtree is modified as follows:
61277 **
61278 **    Expr.op        Changed to TK_COLUMN
61279 **    Expr.pTab      Points to the Table object for X.Y
61280 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
61281 **    Expr.iTable    The VDBE cursor number for X.Y
61282 **
61283 **
61284 ** To resolve result-set references, look for expression nodes of the
61285 ** form Z (with no X and Y prefix) where the Z matches the right-hand
61286 ** size of an AS clause in the result-set of a SELECT.  The Z expression
61287 ** is replaced by a copy of the left-hand side of the result-set expression.
61288 ** Table-name and function resolution occurs on the substituted expression
61289 ** tree.  For example, in:
61290 **
61291 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
61292 **
61293 ** The "x" term of the order by is replaced by "a+b" to render:
61294 **
61295 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
61296 **
61297 ** Function calls are checked to make sure that the function is 
61298 ** defined and that the correct number of arguments are specified.
61299 ** If the function is an aggregate function, then the pNC->hasAgg is
61300 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
61301 ** If an expression contains aggregate functions then the EP_Agg
61302 ** property on the expression is set.
61303 **
61304 ** An error message is left in pParse if anything is amiss.  The number
61305 ** if errors is returned.
61306 */
61307 SQLITE_PRIVATE int sqlite3ResolveExprNames( 
61308   NameContext *pNC,       /* Namespace to resolve expressions in. */
61309   Expr *pExpr             /* The expression to be analyzed. */
61310 ){
61311   int savedHasAgg;
61312   Walker w;
61313
61314   if( pExpr==0 ) return 0;
61315 #if SQLITE_MAX_EXPR_DEPTH>0
61316   {
61317     Parse *pParse = pNC->pParse;
61318     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
61319       return 1;
61320     }
61321     pParse->nHeight += pExpr->nHeight;
61322   }
61323 #endif
61324   savedHasAgg = pNC->hasAgg;
61325   pNC->hasAgg = 0;
61326   w.xExprCallback = resolveExprStep;
61327   w.xSelectCallback = resolveSelectStep;
61328   w.pParse = pNC->pParse;
61329   w.u.pNC = pNC;
61330   sqlite3WalkExpr(&w, pExpr);
61331 #if SQLITE_MAX_EXPR_DEPTH>0
61332   pNC->pParse->nHeight -= pExpr->nHeight;
61333 #endif
61334   if( pNC->nErr>0 || w.pParse->nErr>0 ){
61335     ExprSetProperty(pExpr, EP_Error);
61336   }
61337   if( pNC->hasAgg ){
61338     ExprSetProperty(pExpr, EP_Agg);
61339   }else if( savedHasAgg ){
61340     pNC->hasAgg = 1;
61341   }
61342   return ExprHasProperty(pExpr, EP_Error);
61343 }
61344
61345
61346 /*
61347 ** Resolve all names in all expressions of a SELECT and in all
61348 ** decendents of the SELECT, including compounds off of p->pPrior,
61349 ** subqueries in expressions, and subqueries used as FROM clause
61350 ** terms.
61351 **
61352 ** See sqlite3ResolveExprNames() for a description of the kinds of
61353 ** transformations that occur.
61354 **
61355 ** All SELECT statements should have been expanded using
61356 ** sqlite3SelectExpand() prior to invoking this routine.
61357 */
61358 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
61359   Parse *pParse,         /* The parser context */
61360   Select *p,             /* The SELECT statement being coded. */
61361   NameContext *pOuterNC  /* Name context for parent SELECT statement */
61362 ){
61363   Walker w;
61364
61365   assert( p!=0 );
61366   w.xExprCallback = resolveExprStep;
61367   w.xSelectCallback = resolveSelectStep;
61368   w.pParse = pParse;
61369   w.u.pNC = pOuterNC;
61370   sqlite3WalkSelect(&w, p);
61371 }
61372
61373 /************** End of resolve.c *********************************************/
61374 /************** Begin file expr.c ********************************************/
61375 /*
61376 ** 2001 September 15
61377 **
61378 ** The author disclaims copyright to this source code.  In place of
61379 ** a legal notice, here is a blessing:
61380 **
61381 **    May you do good and not evil.
61382 **    May you find forgiveness for yourself and forgive others.
61383 **    May you share freely, never taking more than you give.
61384 **
61385 *************************************************************************
61386 ** This file contains routines used for analyzing expressions and
61387 ** for generating VDBE code that evaluates expressions in SQLite.
61388 */
61389
61390 /*
61391 ** Return the 'affinity' of the expression pExpr if any.
61392 **
61393 ** If pExpr is a column, a reference to a column via an 'AS' alias,
61394 ** or a sub-select with a column as the return value, then the 
61395 ** affinity of that column is returned. Otherwise, 0x00 is returned,
61396 ** indicating no affinity for the expression.
61397 **
61398 ** i.e. the WHERE clause expresssions in the following statements all
61399 ** have an affinity:
61400 **
61401 ** CREATE TABLE t1(a);
61402 ** SELECT * FROM t1 WHERE a;
61403 ** SELECT a AS b FROM t1 WHERE b;
61404 ** SELECT * FROM t1 WHERE (select a from t1);
61405 */
61406 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
61407   int op = pExpr->op;
61408   if( op==TK_SELECT ){
61409     assert( pExpr->flags&EP_xIsSelect );
61410     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
61411   }
61412 #ifndef SQLITE_OMIT_CAST
61413   if( op==TK_CAST ){
61414     assert( !ExprHasProperty(pExpr, EP_IntValue) );
61415     return sqlite3AffinityType(pExpr->u.zToken);
61416   }
61417 #endif
61418   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
61419    && pExpr->pTab!=0
61420   ){
61421     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
61422     ** a TK_COLUMN but was previously evaluated and cached in a register */
61423     int j = pExpr->iColumn;
61424     if( j<0 ) return SQLITE_AFF_INTEGER;
61425     assert( pExpr->pTab && j<pExpr->pTab->nCol );
61426     return pExpr->pTab->aCol[j].affinity;
61427   }
61428   return pExpr->affinity;
61429 }
61430
61431 /*
61432 ** Set the collating sequence for expression pExpr to be the collating
61433 ** sequence named by pToken.   Return a pointer to the revised expression.
61434 ** The collating sequence is marked as "explicit" using the EP_ExpCollate
61435 ** flag.  An explicit collating sequence will override implicit
61436 ** collating sequences.
61437 */
61438 SQLITE_PRIVATE Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){
61439   char *zColl = 0;            /* Dequoted name of collation sequence */
61440   CollSeq *pColl;
61441   sqlite3 *db = pParse->db;
61442   zColl = sqlite3NameFromToken(db, pCollName);
61443   if( pExpr && zColl ){
61444     pColl = sqlite3LocateCollSeq(pParse, zColl);
61445     if( pColl ){
61446       pExpr->pColl = pColl;
61447       pExpr->flags |= EP_ExpCollate;
61448     }
61449   }
61450   sqlite3DbFree(db, zColl);
61451   return pExpr;
61452 }
61453
61454 /*
61455 ** Return the default collation sequence for the expression pExpr. If
61456 ** there is no default collation type, return 0.
61457 */
61458 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
61459   CollSeq *pColl = 0;
61460   Expr *p = pExpr;
61461   while( ALWAYS(p) ){
61462     int op;
61463     pColl = p->pColl;
61464     if( pColl ) break;
61465     op = p->op;
61466     if( p->pTab!=0 && (
61467         op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
61468     )){
61469       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
61470       ** a TK_COLUMN but was previously evaluated and cached in a register */
61471       const char *zColl;
61472       int j = p->iColumn;
61473       if( j>=0 ){
61474         sqlite3 *db = pParse->db;
61475         zColl = p->pTab->aCol[j].zColl;
61476         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
61477         pExpr->pColl = pColl;
61478       }
61479       break;
61480     }
61481     if( op!=TK_CAST && op!=TK_UPLUS ){
61482       break;
61483     }
61484     p = p->pLeft;
61485   }
61486   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
61487     pColl = 0;
61488   }
61489   return pColl;
61490 }
61491
61492 /*
61493 ** pExpr is an operand of a comparison operator.  aff2 is the
61494 ** type affinity of the other operand.  This routine returns the
61495 ** type affinity that should be used for the comparison operator.
61496 */
61497 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
61498   char aff1 = sqlite3ExprAffinity(pExpr);
61499   if( aff1 && aff2 ){
61500     /* Both sides of the comparison are columns. If one has numeric
61501     ** affinity, use that. Otherwise use no affinity.
61502     */
61503     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
61504       return SQLITE_AFF_NUMERIC;
61505     }else{
61506       return SQLITE_AFF_NONE;
61507     }
61508   }else if( !aff1 && !aff2 ){
61509     /* Neither side of the comparison is a column.  Compare the
61510     ** results directly.
61511     */
61512     return SQLITE_AFF_NONE;
61513   }else{
61514     /* One side is a column, the other is not. Use the columns affinity. */
61515     assert( aff1==0 || aff2==0 );
61516     return (aff1 + aff2);
61517   }
61518 }
61519
61520 /*
61521 ** pExpr is a comparison operator.  Return the type affinity that should
61522 ** be applied to both operands prior to doing the comparison.
61523 */
61524 static char comparisonAffinity(Expr *pExpr){
61525   char aff;
61526   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
61527           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
61528           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
61529   assert( pExpr->pLeft );
61530   aff = sqlite3ExprAffinity(pExpr->pLeft);
61531   if( pExpr->pRight ){
61532     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
61533   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
61534     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
61535   }else if( !aff ){
61536     aff = SQLITE_AFF_NONE;
61537   }
61538   return aff;
61539 }
61540
61541 /*
61542 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
61543 ** idx_affinity is the affinity of an indexed column. Return true
61544 ** if the index with affinity idx_affinity may be used to implement
61545 ** the comparison in pExpr.
61546 */
61547 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
61548   char aff = comparisonAffinity(pExpr);
61549   switch( aff ){
61550     case SQLITE_AFF_NONE:
61551       return 1;
61552     case SQLITE_AFF_TEXT:
61553       return idx_affinity==SQLITE_AFF_TEXT;
61554     default:
61555       return sqlite3IsNumericAffinity(idx_affinity);
61556   }
61557 }
61558
61559 /*
61560 ** Return the P5 value that should be used for a binary comparison
61561 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
61562 */
61563 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
61564   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
61565   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
61566   return aff;
61567 }
61568
61569 /*
61570 ** Return a pointer to the collation sequence that should be used by
61571 ** a binary comparison operator comparing pLeft and pRight.
61572 **
61573 ** If the left hand expression has a collating sequence type, then it is
61574 ** used. Otherwise the collation sequence for the right hand expression
61575 ** is used, or the default (BINARY) if neither expression has a collating
61576 ** type.
61577 **
61578 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
61579 ** it is not considered.
61580 */
61581 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
61582   Parse *pParse, 
61583   Expr *pLeft, 
61584   Expr *pRight
61585 ){
61586   CollSeq *pColl;
61587   assert( pLeft );
61588   if( pLeft->flags & EP_ExpCollate ){
61589     assert( pLeft->pColl );
61590     pColl = pLeft->pColl;
61591   }else if( pRight && pRight->flags & EP_ExpCollate ){
61592     assert( pRight->pColl );
61593     pColl = pRight->pColl;
61594   }else{
61595     pColl = sqlite3ExprCollSeq(pParse, pLeft);
61596     if( !pColl ){
61597       pColl = sqlite3ExprCollSeq(pParse, pRight);
61598     }
61599   }
61600   return pColl;
61601 }
61602
61603 /*
61604 ** Generate code for a comparison operator.
61605 */
61606 static int codeCompare(
61607   Parse *pParse,    /* The parsing (and code generating) context */
61608   Expr *pLeft,      /* The left operand */
61609   Expr *pRight,     /* The right operand */
61610   int opcode,       /* The comparison opcode */
61611   int in1, int in2, /* Register holding operands */
61612   int dest,         /* Jump here if true.  */
61613   int jumpIfNull    /* If true, jump if either operand is NULL */
61614 ){
61615   int p5;
61616   int addr;
61617   CollSeq *p4;
61618
61619   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
61620   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
61621   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
61622                            (void*)p4, P4_COLLSEQ);
61623   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
61624   return addr;
61625 }
61626
61627 #if SQLITE_MAX_EXPR_DEPTH>0
61628 /*
61629 ** Check that argument nHeight is less than or equal to the maximum
61630 ** expression depth allowed. If it is not, leave an error message in
61631 ** pParse.
61632 */
61633 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
61634   int rc = SQLITE_OK;
61635   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
61636   if( nHeight>mxHeight ){
61637     sqlite3ErrorMsg(pParse, 
61638        "Expression tree is too large (maximum depth %d)", mxHeight
61639     );
61640     rc = SQLITE_ERROR;
61641   }
61642   return rc;
61643 }
61644
61645 /* The following three functions, heightOfExpr(), heightOfExprList()
61646 ** and heightOfSelect(), are used to determine the maximum height
61647 ** of any expression tree referenced by the structure passed as the
61648 ** first argument.
61649 **
61650 ** If this maximum height is greater than the current value pointed
61651 ** to by pnHeight, the second parameter, then set *pnHeight to that
61652 ** value.
61653 */
61654 static void heightOfExpr(Expr *p, int *pnHeight){
61655   if( p ){
61656     if( p->nHeight>*pnHeight ){
61657       *pnHeight = p->nHeight;
61658     }
61659   }
61660 }
61661 static void heightOfExprList(ExprList *p, int *pnHeight){
61662   if( p ){
61663     int i;
61664     for(i=0; i<p->nExpr; i++){
61665       heightOfExpr(p->a[i].pExpr, pnHeight);
61666     }
61667   }
61668 }
61669 static void heightOfSelect(Select *p, int *pnHeight){
61670   if( p ){
61671     heightOfExpr(p->pWhere, pnHeight);
61672     heightOfExpr(p->pHaving, pnHeight);
61673     heightOfExpr(p->pLimit, pnHeight);
61674     heightOfExpr(p->pOffset, pnHeight);
61675     heightOfExprList(p->pEList, pnHeight);
61676     heightOfExprList(p->pGroupBy, pnHeight);
61677     heightOfExprList(p->pOrderBy, pnHeight);
61678     heightOfSelect(p->pPrior, pnHeight);
61679   }
61680 }
61681
61682 /*
61683 ** Set the Expr.nHeight variable in the structure passed as an 
61684 ** argument. An expression with no children, Expr.pList or 
61685 ** Expr.pSelect member has a height of 1. Any other expression
61686 ** has a height equal to the maximum height of any other 
61687 ** referenced Expr plus one.
61688 */
61689 static void exprSetHeight(Expr *p){
61690   int nHeight = 0;
61691   heightOfExpr(p->pLeft, &nHeight);
61692   heightOfExpr(p->pRight, &nHeight);
61693   if( ExprHasProperty(p, EP_xIsSelect) ){
61694     heightOfSelect(p->x.pSelect, &nHeight);
61695   }else{
61696     heightOfExprList(p->x.pList, &nHeight);
61697   }
61698   p->nHeight = nHeight + 1;
61699 }
61700
61701 /*
61702 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
61703 ** the height is greater than the maximum allowed expression depth,
61704 ** leave an error in pParse.
61705 */
61706 SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
61707   exprSetHeight(p);
61708   sqlite3ExprCheckHeight(pParse, p->nHeight);
61709 }
61710
61711 /*
61712 ** Return the maximum height of any expression tree referenced
61713 ** by the select statement passed as an argument.
61714 */
61715 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
61716   int nHeight = 0;
61717   heightOfSelect(p, &nHeight);
61718   return nHeight;
61719 }
61720 #else
61721   #define exprSetHeight(y)
61722 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
61723
61724 /*
61725 ** This routine is the core allocator for Expr nodes.
61726 **
61727 ** Construct a new expression node and return a pointer to it.  Memory
61728 ** for this node and for the pToken argument is a single allocation
61729 ** obtained from sqlite3DbMalloc().  The calling function
61730 ** is responsible for making sure the node eventually gets freed.
61731 **
61732 ** If dequote is true, then the token (if it exists) is dequoted.
61733 ** If dequote is false, no dequoting is performance.  The deQuote
61734 ** parameter is ignored if pToken is NULL or if the token does not
61735 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
61736 ** then the EP_DblQuoted flag is set on the expression node.
61737 **
61738 ** Special case:  If op==TK_INTEGER and pToken points to a string that
61739 ** can be translated into a 32-bit integer, then the token is not
61740 ** stored in u.zToken.  Instead, the integer values is written
61741 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
61742 ** is allocated to hold the integer text and the dequote flag is ignored.
61743 */
61744 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
61745   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
61746   int op,                 /* Expression opcode */
61747   const Token *pToken,    /* Token argument.  Might be NULL */
61748   int dequote             /* True to dequote */
61749 ){
61750   Expr *pNew;
61751   int nExtra = 0;
61752   int iValue = 0;
61753
61754   if( pToken ){
61755     if( op!=TK_INTEGER || pToken->z==0
61756           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
61757       nExtra = pToken->n+1;
61758     }
61759   }
61760   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
61761   if( pNew ){
61762     pNew->op = (u8)op;
61763     pNew->iAgg = -1;
61764     if( pToken ){
61765       if( nExtra==0 ){
61766         pNew->flags |= EP_IntValue;
61767         pNew->u.iValue = iValue;
61768       }else{
61769         int c;
61770         pNew->u.zToken = (char*)&pNew[1];
61771         memcpy(pNew->u.zToken, pToken->z, pToken->n);
61772         pNew->u.zToken[pToken->n] = 0;
61773         if( dequote && nExtra>=3 
61774              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
61775           sqlite3Dequote(pNew->u.zToken);
61776           if( c=='"' ) pNew->flags |= EP_DblQuoted;
61777         }
61778       }
61779     }
61780 #if SQLITE_MAX_EXPR_DEPTH>0
61781     pNew->nHeight = 1;
61782 #endif  
61783   }
61784   return pNew;
61785 }
61786
61787 /*
61788 ** Allocate a new expression node from a zero-terminated token that has
61789 ** already been dequoted.
61790 */
61791 SQLITE_PRIVATE Expr *sqlite3Expr(
61792   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
61793   int op,                 /* Expression opcode */
61794   const char *zToken      /* Token argument.  Might be NULL */
61795 ){
61796   Token x;
61797   x.z = zToken;
61798   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
61799   return sqlite3ExprAlloc(db, op, &x, 0);
61800 }
61801
61802 /*
61803 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
61804 **
61805 ** If pRoot==NULL that means that a memory allocation error has occurred.
61806 ** In that case, delete the subtrees pLeft and pRight.
61807 */
61808 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
61809   sqlite3 *db,
61810   Expr *pRoot,
61811   Expr *pLeft,
61812   Expr *pRight
61813 ){
61814   if( pRoot==0 ){
61815     assert( db->mallocFailed );
61816     sqlite3ExprDelete(db, pLeft);
61817     sqlite3ExprDelete(db, pRight);
61818   }else{
61819     if( pRight ){
61820       pRoot->pRight = pRight;
61821       if( pRight->flags & EP_ExpCollate ){
61822         pRoot->flags |= EP_ExpCollate;
61823         pRoot->pColl = pRight->pColl;
61824       }
61825     }
61826     if( pLeft ){
61827       pRoot->pLeft = pLeft;
61828       if( pLeft->flags & EP_ExpCollate ){
61829         pRoot->flags |= EP_ExpCollate;
61830         pRoot->pColl = pLeft->pColl;
61831       }
61832     }
61833     exprSetHeight(pRoot);
61834   }
61835 }
61836
61837 /*
61838 ** Allocate a Expr node which joins as many as two subtrees.
61839 **
61840 ** One or both of the subtrees can be NULL.  Return a pointer to the new
61841 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
61842 ** free the subtrees and return NULL.
61843 */
61844 SQLITE_PRIVATE Expr *sqlite3PExpr(
61845   Parse *pParse,          /* Parsing context */
61846   int op,                 /* Expression opcode */
61847   Expr *pLeft,            /* Left operand */
61848   Expr *pRight,           /* Right operand */
61849   const Token *pToken     /* Argument token */
61850 ){
61851   Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
61852   sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
61853   return p;
61854 }
61855
61856 /*
61857 ** Join two expressions using an AND operator.  If either expression is
61858 ** NULL, then just return the other expression.
61859 */
61860 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
61861   if( pLeft==0 ){
61862     return pRight;
61863   }else if( pRight==0 ){
61864     return pLeft;
61865   }else{
61866     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
61867     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
61868     return pNew;
61869   }
61870 }
61871
61872 /*
61873 ** Construct a new expression node for a function with multiple
61874 ** arguments.
61875 */
61876 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
61877   Expr *pNew;
61878   sqlite3 *db = pParse->db;
61879   assert( pToken );
61880   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
61881   if( pNew==0 ){
61882     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
61883     return 0;
61884   }
61885   pNew->x.pList = pList;
61886   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
61887   sqlite3ExprSetHeight(pParse, pNew);
61888   return pNew;
61889 }
61890
61891 /*
61892 ** Assign a variable number to an expression that encodes a wildcard
61893 ** in the original SQL statement.  
61894 **
61895 ** Wildcards consisting of a single "?" are assigned the next sequential
61896 ** variable number.
61897 **
61898 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
61899 ** sure "nnn" is not too be to avoid a denial of service attack when
61900 ** the SQL statement comes from an external source.
61901 **
61902 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
61903 ** as the previous instance of the same wildcard.  Or if this is the first
61904 ** instance of the wildcard, the next sequenial variable number is
61905 ** assigned.
61906 */
61907 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
61908   sqlite3 *db = pParse->db;
61909   const char *z;
61910
61911   if( pExpr==0 ) return;
61912   assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
61913   z = pExpr->u.zToken;
61914   assert( z!=0 );
61915   assert( z[0]!=0 );
61916   if( z[1]==0 ){
61917     /* Wildcard of the form "?".  Assign the next variable number */
61918     assert( z[0]=='?' );
61919     pExpr->iColumn = (ynVar)(++pParse->nVar);
61920   }else if( z[0]=='?' ){
61921     /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
61922     ** use it as the variable number */
61923     int i = atoi((char*)&z[1]);
61924     pExpr->iColumn = (ynVar)i;
61925     testcase( i==0 );
61926     testcase( i==1 );
61927     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
61928     testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
61929     if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
61930       sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
61931           db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
61932     }
61933     if( i>pParse->nVar ){
61934       pParse->nVar = i;
61935     }
61936   }else{
61937     /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
61938     ** number as the prior appearance of the same name, or if the name
61939     ** has never appeared before, reuse the same variable number
61940     */
61941     int i;
61942     u32 n;
61943     n = sqlite3Strlen30(z);
61944     for(i=0; i<pParse->nVarExpr; i++){
61945       Expr *pE = pParse->apVarExpr[i];
61946       assert( pE!=0 );
61947       if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){
61948         pExpr->iColumn = pE->iColumn;
61949         break;
61950       }
61951     }
61952     if( i>=pParse->nVarExpr ){
61953       pExpr->iColumn = (ynVar)(++pParse->nVar);
61954       if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
61955         pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
61956         pParse->apVarExpr =
61957             sqlite3DbReallocOrFree(
61958               db,
61959               pParse->apVarExpr,
61960               pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
61961             );
61962       }
61963       if( !db->mallocFailed ){
61964         assert( pParse->apVarExpr!=0 );
61965         pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
61966       }
61967     }
61968   } 
61969   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
61970     sqlite3ErrorMsg(pParse, "too many SQL variables");
61971   }
61972 }
61973
61974 /*
61975 ** Recursively delete an expression tree.
61976 */
61977 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
61978   if( p==0 ) return;
61979   if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
61980     sqlite3ExprDelete(db, p->pLeft);
61981     sqlite3ExprDelete(db, p->pRight);
61982     if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
61983       sqlite3DbFree(db, p->u.zToken);
61984     }
61985     if( ExprHasProperty(p, EP_xIsSelect) ){
61986       sqlite3SelectDelete(db, p->x.pSelect);
61987     }else{
61988       sqlite3ExprListDelete(db, p->x.pList);
61989     }
61990   }
61991   if( !ExprHasProperty(p, EP_Static) ){
61992     sqlite3DbFree(db, p);
61993   }
61994 }
61995
61996 /*
61997 ** Return the number of bytes allocated for the expression structure 
61998 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
61999 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
62000 */
62001 static int exprStructSize(Expr *p){
62002   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
62003   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
62004   return EXPR_FULLSIZE;
62005 }
62006
62007 /*
62008 ** The dupedExpr*Size() routines each return the number of bytes required
62009 ** to store a copy of an expression or expression tree.  They differ in
62010 ** how much of the tree is measured.
62011 **
62012 **     dupedExprStructSize()     Size of only the Expr structure 
62013 **     dupedExprNodeSize()       Size of Expr + space for token
62014 **     dupedExprSize()           Expr + token + subtree components
62015 **
62016 ***************************************************************************
62017 **
62018 ** The dupedExprStructSize() function returns two values OR-ed together:  
62019 ** (1) the space required for a copy of the Expr structure only and 
62020 ** (2) the EP_xxx flags that indicate what the structure size should be.
62021 ** The return values is always one of:
62022 **
62023 **      EXPR_FULLSIZE
62024 **      EXPR_REDUCEDSIZE   | EP_Reduced
62025 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
62026 **
62027 ** The size of the structure can be found by masking the return value
62028 ** of this routine with 0xfff.  The flags can be found by masking the
62029 ** return value with EP_Reduced|EP_TokenOnly.
62030 **
62031 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
62032 ** (unreduced) Expr objects as they or originally constructed by the parser.
62033 ** During expression analysis, extra information is computed and moved into
62034 ** later parts of teh Expr object and that extra information might get chopped
62035 ** off if the expression is reduced.  Note also that it does not work to
62036 ** make a EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
62037 ** to reduce a pristine expression tree from the parser.  The implementation
62038 ** of dupedExprStructSize() contain multiple assert() statements that attempt
62039 ** to enforce this constraint.
62040 */
62041 static int dupedExprStructSize(Expr *p, int flags){
62042   int nSize;
62043   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
62044   if( 0==(flags&EXPRDUP_REDUCE) ){
62045     nSize = EXPR_FULLSIZE;
62046   }else{
62047     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
62048     assert( !ExprHasProperty(p, EP_FromJoin) ); 
62049     assert( (p->flags2 & EP2_MallocedToken)==0 );
62050     assert( (p->flags2 & EP2_Irreducible)==0 );
62051     if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
62052       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
62053     }else{
62054       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
62055     }
62056   }
62057   return nSize;
62058 }
62059
62060 /*
62061 ** This function returns the space in bytes required to store the copy 
62062 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
62063 ** string is defined.)
62064 */
62065 static int dupedExprNodeSize(Expr *p, int flags){
62066   int nByte = dupedExprStructSize(p, flags) & 0xfff;
62067   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
62068     nByte += sqlite3Strlen30(p->u.zToken)+1;
62069   }
62070   return ROUND8(nByte);
62071 }
62072
62073 /*
62074 ** Return the number of bytes required to create a duplicate of the 
62075 ** expression passed as the first argument. The second argument is a
62076 ** mask containing EXPRDUP_XXX flags.
62077 **
62078 ** The value returned includes space to create a copy of the Expr struct
62079 ** itself and the buffer referred to by Expr.u.zToken, if any.
62080 **
62081 ** If the EXPRDUP_REDUCE flag is set, then the return value includes 
62082 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
62083 ** and Expr.pRight variables (but not for any structures pointed to or 
62084 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
62085 */
62086 static int dupedExprSize(Expr *p, int flags){
62087   int nByte = 0;
62088   if( p ){
62089     nByte = dupedExprNodeSize(p, flags);
62090     if( flags&EXPRDUP_REDUCE ){
62091       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
62092     }
62093   }
62094   return nByte;
62095 }
62096
62097 /*
62098 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
62099 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
62100 ** to store the copy of expression p, the copies of p->u.zToken
62101 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
62102 ** if any. Before returning, *pzBuffer is set to the first byte passed the
62103 ** portion of the buffer copied into by this function.
62104 */
62105 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
62106   Expr *pNew = 0;                      /* Value to return */
62107   if( p ){
62108     const int isReduced = (flags&EXPRDUP_REDUCE);
62109     u8 *zAlloc;
62110     u32 staticFlag = 0;
62111
62112     assert( pzBuffer==0 || isReduced );
62113
62114     /* Figure out where to write the new Expr structure. */
62115     if( pzBuffer ){
62116       zAlloc = *pzBuffer;
62117       staticFlag = EP_Static;
62118     }else{
62119       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
62120     }
62121     pNew = (Expr *)zAlloc;
62122
62123     if( pNew ){
62124       /* Set nNewSize to the size allocated for the structure pointed to
62125       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
62126       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
62127       ** by the copy of the p->u.zToken string (if any).
62128       */
62129       const unsigned nStructSize = dupedExprStructSize(p, flags);
62130       const int nNewSize = nStructSize & 0xfff;
62131       int nToken;
62132       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
62133         nToken = sqlite3Strlen30(p->u.zToken) + 1;
62134       }else{
62135         nToken = 0;
62136       }
62137       if( isReduced ){
62138         assert( ExprHasProperty(p, EP_Reduced)==0 );
62139         memcpy(zAlloc, p, nNewSize);
62140       }else{
62141         int nSize = exprStructSize(p);
62142         memcpy(zAlloc, p, nSize);
62143         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
62144       }
62145
62146       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
62147       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
62148       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
62149       pNew->flags |= staticFlag;
62150
62151       /* Copy the p->u.zToken string, if any. */
62152       if( nToken ){
62153         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
62154         memcpy(zToken, p->u.zToken, nToken);
62155       }
62156
62157       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
62158         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
62159         if( ExprHasProperty(p, EP_xIsSelect) ){
62160           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
62161         }else{
62162           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
62163         }
62164       }
62165
62166       /* Fill in pNew->pLeft and pNew->pRight. */
62167       if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
62168         zAlloc += dupedExprNodeSize(p, flags);
62169         if( ExprHasProperty(pNew, EP_Reduced) ){
62170           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
62171           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
62172         }
62173         if( pzBuffer ){
62174           *pzBuffer = zAlloc;
62175         }
62176       }else{
62177         pNew->flags2 = 0;
62178         if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
62179           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
62180           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
62181         }
62182       }
62183
62184     }
62185   }
62186   return pNew;
62187 }
62188
62189 /*
62190 ** The following group of routines make deep copies of expressions,
62191 ** expression lists, ID lists, and select statements.  The copies can
62192 ** be deleted (by being passed to their respective ...Delete() routines)
62193 ** without effecting the originals.
62194 **
62195 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
62196 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
62197 ** by subsequent calls to sqlite*ListAppend() routines.
62198 **
62199 ** Any tables that the SrcList might point to are not duplicated.
62200 **
62201 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
62202 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
62203 ** truncated version of the usual Expr structure that will be stored as
62204 ** part of the in-memory representation of the database schema.
62205 */
62206 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
62207   return exprDup(db, p, flags, 0);
62208 }
62209 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
62210   ExprList *pNew;
62211   struct ExprList_item *pItem, *pOldItem;
62212   int i;
62213   if( p==0 ) return 0;
62214   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
62215   if( pNew==0 ) return 0;
62216   pNew->iECursor = 0;
62217   pNew->nExpr = pNew->nAlloc = p->nExpr;
62218   pNew->a = pItem = sqlite3DbMallocRaw(db,  p->nExpr*sizeof(p->a[0]) );
62219   if( pItem==0 ){
62220     sqlite3DbFree(db, pNew);
62221     return 0;
62222   } 
62223   pOldItem = p->a;
62224   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
62225     Expr *pOldExpr = pOldItem->pExpr;
62226     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
62227     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
62228     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
62229     pItem->sortOrder = pOldItem->sortOrder;
62230     pItem->done = 0;
62231     pItem->iCol = pOldItem->iCol;
62232     pItem->iAlias = pOldItem->iAlias;
62233   }
62234   return pNew;
62235 }
62236
62237 /*
62238 ** If cursors, triggers, views and subqueries are all omitted from
62239 ** the build, then none of the following routines, except for 
62240 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
62241 ** called with a NULL argument.
62242 */
62243 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
62244  || !defined(SQLITE_OMIT_SUBQUERY)
62245 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
62246   SrcList *pNew;
62247   int i;
62248   int nByte;
62249   if( p==0 ) return 0;
62250   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
62251   pNew = sqlite3DbMallocRaw(db, nByte );
62252   if( pNew==0 ) return 0;
62253   pNew->nSrc = pNew->nAlloc = p->nSrc;
62254   for(i=0; i<p->nSrc; i++){
62255     struct SrcList_item *pNewItem = &pNew->a[i];
62256     struct SrcList_item *pOldItem = &p->a[i];
62257     Table *pTab;
62258     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
62259     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
62260     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
62261     pNewItem->jointype = pOldItem->jointype;
62262     pNewItem->iCursor = pOldItem->iCursor;
62263     pNewItem->isPopulated = pOldItem->isPopulated;
62264     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
62265     pNewItem->notIndexed = pOldItem->notIndexed;
62266     pNewItem->pIndex = pOldItem->pIndex;
62267     pTab = pNewItem->pTab = pOldItem->pTab;
62268     if( pTab ){
62269       pTab->nRef++;
62270     }
62271     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
62272     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
62273     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
62274     pNewItem->colUsed = pOldItem->colUsed;
62275   }
62276   return pNew;
62277 }
62278 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
62279   IdList *pNew;
62280   int i;
62281   if( p==0 ) return 0;
62282   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
62283   if( pNew==0 ) return 0;
62284   pNew->nId = pNew->nAlloc = p->nId;
62285   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
62286   if( pNew->a==0 ){
62287     sqlite3DbFree(db, pNew);
62288     return 0;
62289   }
62290   for(i=0; i<p->nId; i++){
62291     struct IdList_item *pNewItem = &pNew->a[i];
62292     struct IdList_item *pOldItem = &p->a[i];
62293     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
62294     pNewItem->idx = pOldItem->idx;
62295   }
62296   return pNew;
62297 }
62298 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
62299   Select *pNew;
62300   if( p==0 ) return 0;
62301   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
62302   if( pNew==0 ) return 0;
62303   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
62304   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
62305   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
62306   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
62307   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
62308   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
62309   pNew->op = p->op;
62310   pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
62311   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
62312   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
62313   pNew->iLimit = 0;
62314   pNew->iOffset = 0;
62315   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
62316   pNew->pRightmost = 0;
62317   pNew->addrOpenEphm[0] = -1;
62318   pNew->addrOpenEphm[1] = -1;
62319   pNew->addrOpenEphm[2] = -1;
62320   return pNew;
62321 }
62322 #else
62323 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
62324   assert( p==0 );
62325   return 0;
62326 }
62327 #endif
62328
62329
62330 /*
62331 ** Add a new element to the end of an expression list.  If pList is
62332 ** initially NULL, then create a new expression list.
62333 **
62334 ** If a memory allocation error occurs, the entire list is freed and
62335 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
62336 ** that the new entry was successfully appended.
62337 */
62338 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
62339   Parse *pParse,          /* Parsing context */
62340   ExprList *pList,        /* List to which to append. Might be NULL */
62341   Expr *pExpr             /* Expression to be appended. Might be NULL */
62342 ){
62343   sqlite3 *db = pParse->db;
62344   if( pList==0 ){
62345     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
62346     if( pList==0 ){
62347       goto no_mem;
62348     }
62349     assert( pList->nAlloc==0 );
62350   }
62351   if( pList->nAlloc<=pList->nExpr ){
62352     struct ExprList_item *a;
62353     int n = pList->nAlloc*2 + 4;
62354     a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
62355     if( a==0 ){
62356       goto no_mem;
62357     }
62358     pList->a = a;
62359     pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
62360   }
62361   assert( pList->a!=0 );
62362   if( 1 ){
62363     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
62364     memset(pItem, 0, sizeof(*pItem));
62365     pItem->pExpr = pExpr;
62366   }
62367   return pList;
62368
62369 no_mem:     
62370   /* Avoid leaking memory if malloc has failed. */
62371   sqlite3ExprDelete(db, pExpr);
62372   sqlite3ExprListDelete(db, pList);
62373   return 0;
62374 }
62375
62376 /*
62377 ** Set the ExprList.a[].zName element of the most recently added item
62378 ** on the expression list.
62379 **
62380 ** pList might be NULL following an OOM error.  But pName should never be
62381 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
62382 ** is set.
62383 */
62384 SQLITE_PRIVATE void sqlite3ExprListSetName(
62385   Parse *pParse,          /* Parsing context */
62386   ExprList *pList,        /* List to which to add the span. */
62387   Token *pName,           /* Name to be added */
62388   int dequote             /* True to cause the name to be dequoted */
62389 ){
62390   assert( pList!=0 || pParse->db->mallocFailed!=0 );
62391   if( pList ){
62392     struct ExprList_item *pItem;
62393     assert( pList->nExpr>0 );
62394     pItem = &pList->a[pList->nExpr-1];
62395     assert( pItem->zName==0 );
62396     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
62397     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
62398   }
62399 }
62400
62401 /*
62402 ** Set the ExprList.a[].zSpan element of the most recently added item
62403 ** on the expression list.
62404 **
62405 ** pList might be NULL following an OOM error.  But pSpan should never be
62406 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
62407 ** is set.
62408 */
62409 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
62410   Parse *pParse,          /* Parsing context */
62411   ExprList *pList,        /* List to which to add the span. */
62412   ExprSpan *pSpan         /* The span to be added */
62413 ){
62414   sqlite3 *db = pParse->db;
62415   assert( pList!=0 || db->mallocFailed!=0 );
62416   if( pList ){
62417     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
62418     assert( pList->nExpr>0 );
62419     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
62420     sqlite3DbFree(db, pItem->zSpan);
62421     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
62422                                     (int)(pSpan->zEnd - pSpan->zStart));
62423   }
62424 }
62425
62426 /*
62427 ** If the expression list pEList contains more than iLimit elements,
62428 ** leave an error message in pParse.
62429 */
62430 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
62431   Parse *pParse,
62432   ExprList *pEList,
62433   const char *zObject
62434 ){
62435   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
62436   testcase( pEList && pEList->nExpr==mx );
62437   testcase( pEList && pEList->nExpr==mx+1 );
62438   if( pEList && pEList->nExpr>mx ){
62439     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
62440   }
62441 }
62442
62443 /*
62444 ** Delete an entire expression list.
62445 */
62446 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
62447   int i;
62448   struct ExprList_item *pItem;
62449   if( pList==0 ) return;
62450   assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
62451   assert( pList->nExpr<=pList->nAlloc );
62452   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
62453     sqlite3ExprDelete(db, pItem->pExpr);
62454     sqlite3DbFree(db, pItem->zName);
62455     sqlite3DbFree(db, pItem->zSpan);
62456   }
62457   sqlite3DbFree(db, pList->a);
62458   sqlite3DbFree(db, pList);
62459 }
62460
62461 /*
62462 ** These routines are Walker callbacks.  Walker.u.pi is a pointer
62463 ** to an integer.  These routines are checking an expression to see
62464 ** if it is a constant.  Set *Walker.u.pi to 0 if the expression is
62465 ** not constant.
62466 **
62467 ** These callback routines are used to implement the following:
62468 **
62469 **     sqlite3ExprIsConstant()
62470 **     sqlite3ExprIsConstantNotJoin()
62471 **     sqlite3ExprIsConstantOrFunction()
62472 **
62473 */
62474 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
62475
62476   /* If pWalker->u.i is 3 then any term of the expression that comes from
62477   ** the ON or USING clauses of a join disqualifies the expression
62478   ** from being considered constant. */
62479   if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
62480     pWalker->u.i = 0;
62481     return WRC_Abort;
62482   }
62483
62484   switch( pExpr->op ){
62485     /* Consider functions to be constant if all their arguments are constant
62486     ** and pWalker->u.i==2 */
62487     case TK_FUNCTION:
62488       if( pWalker->u.i==2 ) return 0;
62489       /* Fall through */
62490     case TK_ID:
62491     case TK_COLUMN:
62492     case TK_AGG_FUNCTION:
62493     case TK_AGG_COLUMN:
62494       testcase( pExpr->op==TK_ID );
62495       testcase( pExpr->op==TK_COLUMN );
62496       testcase( pExpr->op==TK_AGG_FUNCTION );
62497       testcase( pExpr->op==TK_AGG_COLUMN );
62498       pWalker->u.i = 0;
62499       return WRC_Abort;
62500     default:
62501       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
62502       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
62503       return WRC_Continue;
62504   }
62505 }
62506 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
62507   UNUSED_PARAMETER(NotUsed);
62508   pWalker->u.i = 0;
62509   return WRC_Abort;
62510 }
62511 static int exprIsConst(Expr *p, int initFlag){
62512   Walker w;
62513   w.u.i = initFlag;
62514   w.xExprCallback = exprNodeIsConstant;
62515   w.xSelectCallback = selectNodeIsConstant;
62516   sqlite3WalkExpr(&w, p);
62517   return w.u.i;
62518 }
62519
62520 /*
62521 ** Walk an expression tree.  Return 1 if the expression is constant
62522 ** and 0 if it involves variables or function calls.
62523 **
62524 ** For the purposes of this function, a double-quoted string (ex: "abc")
62525 ** is considered a variable but a single-quoted string (ex: 'abc') is
62526 ** a constant.
62527 */
62528 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
62529   return exprIsConst(p, 1);
62530 }
62531
62532 /*
62533 ** Walk an expression tree.  Return 1 if the expression is constant
62534 ** that does no originate from the ON or USING clauses of a join.
62535 ** Return 0 if it involves variables or function calls or terms from
62536 ** an ON or USING clause.
62537 */
62538 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
62539   return exprIsConst(p, 3);
62540 }
62541
62542 /*
62543 ** Walk an expression tree.  Return 1 if the expression is constant
62544 ** or a function call with constant arguments.  Return and 0 if there
62545 ** are any variables.
62546 **
62547 ** For the purposes of this function, a double-quoted string (ex: "abc")
62548 ** is considered a variable but a single-quoted string (ex: 'abc') is
62549 ** a constant.
62550 */
62551 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p){
62552   return exprIsConst(p, 2);
62553 }
62554
62555 /*
62556 ** If the expression p codes a constant integer that is small enough
62557 ** to fit in a 32-bit integer, return 1 and put the value of the integer
62558 ** in *pValue.  If the expression is not an integer or if it is too big
62559 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
62560 */
62561 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
62562   int rc = 0;
62563   if( p->flags & EP_IntValue ){
62564     *pValue = p->u.iValue;
62565     return 1;
62566   }
62567   switch( p->op ){
62568     case TK_INTEGER: {
62569       rc = sqlite3GetInt32(p->u.zToken, pValue);
62570       assert( rc==0 );
62571       break;
62572     }
62573     case TK_UPLUS: {
62574       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
62575       break;
62576     }
62577     case TK_UMINUS: {
62578       int v;
62579       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
62580         *pValue = -v;
62581         rc = 1;
62582       }
62583       break;
62584     }
62585     default: break;
62586   }
62587   if( rc ){
62588     assert( ExprHasAnyProperty(p, EP_Reduced|EP_TokenOnly)
62589                || (p->flags2 & EP2_MallocedToken)==0 );
62590     p->op = TK_INTEGER;
62591     p->flags |= EP_IntValue;
62592     p->u.iValue = *pValue;
62593   }
62594   return rc;
62595 }
62596
62597 /*
62598 ** Return FALSE if there is no chance that the expression can be NULL.
62599 **
62600 ** If the expression might be NULL or if the expression is too complex
62601 ** to tell return TRUE.  
62602 **
62603 ** This routine is used as an optimization, to skip OP_IsNull opcodes
62604 ** when we know that a value cannot be NULL.  Hence, a false positive
62605 ** (returning TRUE when in fact the expression can never be NULL) might
62606 ** be a small performance hit but is otherwise harmless.  On the other
62607 ** hand, a false negative (returning FALSE when the result could be NULL)
62608 ** will likely result in an incorrect answer.  So when in doubt, return
62609 ** TRUE.
62610 */
62611 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
62612   u8 op;
62613   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
62614   op = p->op;
62615   if( op==TK_REGISTER ) op = p->op2;
62616   switch( op ){
62617     case TK_INTEGER:
62618     case TK_STRING:
62619     case TK_FLOAT:
62620     case TK_BLOB:
62621       return 0;
62622     default:
62623       return 1;
62624   }
62625 }
62626
62627 /*
62628 ** Generate an OP_IsNull instruction that tests register iReg and jumps
62629 ** to location iDest if the value in iReg is NULL.  The value in iReg 
62630 ** was computed by pExpr.  If we can look at pExpr at compile-time and
62631 ** determine that it can never generate a NULL, then the OP_IsNull operation
62632 ** can be omitted.
62633 */
62634 SQLITE_PRIVATE void sqlite3ExprCodeIsNullJump(
62635   Vdbe *v,            /* The VDBE under construction */
62636   const Expr *pExpr,  /* Only generate OP_IsNull if this expr can be NULL */
62637   int iReg,           /* Test the value in this register for NULL */
62638   int iDest           /* Jump here if the value is null */
62639 ){
62640   if( sqlite3ExprCanBeNull(pExpr) ){
62641     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
62642   }
62643 }
62644
62645 /*
62646 ** Return TRUE if the given expression is a constant which would be
62647 ** unchanged by OP_Affinity with the affinity given in the second
62648 ** argument.
62649 **
62650 ** This routine is used to determine if the OP_Affinity operation
62651 ** can be omitted.  When in doubt return FALSE.  A false negative
62652 ** is harmless.  A false positive, however, can result in the wrong
62653 ** answer.
62654 */
62655 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
62656   u8 op;
62657   if( aff==SQLITE_AFF_NONE ) return 1;
62658   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
62659   op = p->op;
62660   if( op==TK_REGISTER ) op = p->op2;
62661   switch( op ){
62662     case TK_INTEGER: {
62663       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
62664     }
62665     case TK_FLOAT: {
62666       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
62667     }
62668     case TK_STRING: {
62669       return aff==SQLITE_AFF_TEXT;
62670     }
62671     case TK_BLOB: {
62672       return 1;
62673     }
62674     case TK_COLUMN: {
62675       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
62676       return p->iColumn<0
62677           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
62678     }
62679     default: {
62680       return 0;
62681     }
62682   }
62683 }
62684
62685 /*
62686 ** Return TRUE if the given string is a row-id column name.
62687 */
62688 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
62689   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
62690   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
62691   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
62692   return 0;
62693 }
62694
62695 /*
62696 ** Return true if we are able to the IN operator optimization on a
62697 ** query of the form
62698 **
62699 **       x IN (SELECT ...)
62700 **
62701 ** Where the SELECT... clause is as specified by the parameter to this
62702 ** routine.
62703 **
62704 ** The Select object passed in has already been preprocessed and no
62705 ** errors have been found.
62706 */
62707 #ifndef SQLITE_OMIT_SUBQUERY
62708 static int isCandidateForInOpt(Select *p){
62709   SrcList *pSrc;
62710   ExprList *pEList;
62711   Table *pTab;
62712   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
62713   if( p->pPrior ) return 0;              /* Not a compound SELECT */
62714   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
62715     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
62716     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
62717     return 0; /* No DISTINCT keyword and no aggregate functions */
62718   }
62719   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
62720   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
62721   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
62722   if( p->pWhere ) return 0;              /* Has no WHERE clause */
62723   pSrc = p->pSrc;
62724   assert( pSrc!=0 );
62725   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
62726   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
62727   pTab = pSrc->a[0].pTab;
62728   if( NEVER(pTab==0) ) return 0;
62729   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
62730   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
62731   pEList = p->pEList;
62732   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
62733   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
62734   return 1;
62735 }
62736 #endif /* SQLITE_OMIT_SUBQUERY */
62737
62738 /*
62739 ** This function is used by the implementation of the IN (...) operator.
62740 ** It's job is to find or create a b-tree structure that may be used
62741 ** either to test for membership of the (...) set or to iterate through
62742 ** its members, skipping duplicates.
62743 **
62744 ** The index of the cursor opened on the b-tree (database table, database index 
62745 ** or ephermal table) is stored in pX->iTable before this function returns.
62746 ** The returned value of this function indicates the b-tree type, as follows:
62747 **
62748 **   IN_INDEX_ROWID - The cursor was opened on a database table.
62749 **   IN_INDEX_INDEX - The cursor was opened on a database index.
62750 **   IN_INDEX_EPH -   The cursor was opened on a specially created and
62751 **                    populated epheremal table.
62752 **
62753 ** An existing b-tree may only be used if the SELECT is of the simple
62754 ** form:
62755 **
62756 **     SELECT <column> FROM <table>
62757 **
62758 ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
62759 ** through the set members, skipping any duplicates. In this case an
62760 ** epheremal table must be used unless the selected <column> is guaranteed
62761 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
62762 ** has a UNIQUE constraint or UNIQUE index.
62763 **
62764 ** If the prNotFound parameter is not 0, then the b-tree will be used 
62765 ** for fast set membership tests. In this case an epheremal table must 
62766 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
62767 ** be found with <column> as its left-most column.
62768 **
62769 ** When the b-tree is being used for membership tests, the calling function
62770 ** needs to know whether or not the structure contains an SQL NULL 
62771 ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
62772 ** If there is any chance that the (...) might contain a NULL value at
62773 ** runtime, then a register is allocated and the register number written
62774 ** to *prNotFound. If there is no chance that the (...) contains a
62775 ** NULL value, then *prNotFound is left unchanged.
62776 **
62777 ** If a register is allocated and its location stored in *prNotFound, then
62778 ** its initial value is NULL.  If the (...) does not remain constant
62779 ** for the duration of the query (i.e. the SELECT within the (...)
62780 ** is a correlated subquery) then the value of the allocated register is
62781 ** reset to NULL each time the subquery is rerun. This allows the
62782 ** caller to use vdbe code equivalent to the following:
62783 **
62784 **   if( register==NULL ){
62785 **     has_null = <test if data structure contains null>
62786 **     register = 1
62787 **   }
62788 **
62789 ** in order to avoid running the <test if data structure contains null>
62790 ** test more often than is necessary.
62791 */
62792 #ifndef SQLITE_OMIT_SUBQUERY
62793 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
62794   Select *p;                            /* SELECT to the right of IN operator */
62795   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
62796   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
62797   int mustBeUnique = (prNotFound==0);   /* True if RHS must be unique */
62798
62799   assert( pX->op==TK_IN );
62800
62801   /* Check to see if an existing table or index can be used to
62802   ** satisfy the query.  This is preferable to generating a new 
62803   ** ephemeral table.
62804   */
62805   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
62806   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
62807     sqlite3 *db = pParse->db;              /* Database connection */
62808     Expr *pExpr = p->pEList->a[0].pExpr;   /* Expression <column> */
62809     int iCol = pExpr->iColumn;             /* Index of column <column> */
62810     Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
62811     Table *pTab = p->pSrc->a[0].pTab;      /* Table <table>. */
62812     int iDb;                               /* Database idx for pTab */
62813    
62814     /* Code an OP_VerifyCookie and OP_TableLock for <table>. */
62815     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
62816     sqlite3CodeVerifySchema(pParse, iDb);
62817     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
62818
62819     /* This function is only called from two places. In both cases the vdbe
62820     ** has already been allocated. So assume sqlite3GetVdbe() is always
62821     ** successful here.
62822     */
62823     assert(v);
62824     if( iCol<0 ){
62825       int iMem = ++pParse->nMem;
62826       int iAddr;
62827
62828       iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
62829       sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
62830
62831       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
62832       eType = IN_INDEX_ROWID;
62833
62834       sqlite3VdbeJumpHere(v, iAddr);
62835     }else{
62836       Index *pIdx;                         /* Iterator variable */
62837
62838       /* The collation sequence used by the comparison. If an index is to
62839       ** be used in place of a temp-table, it must be ordered according
62840       ** to this collation sequence.  */
62841       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
62842
62843       /* Check that the affinity that will be used to perform the 
62844       ** comparison is the same as the affinity of the column. If
62845       ** it is not, it is not possible to use any index.
62846       */
62847       char aff = comparisonAffinity(pX);
62848       int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
62849
62850       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
62851         if( (pIdx->aiColumn[0]==iCol)
62852          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
62853          && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
62854         ){
62855           int iMem = ++pParse->nMem;
62856           int iAddr;
62857           char *pKey;
62858   
62859           pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
62860           iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
62861           sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
62862   
62863           sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
62864                                pKey,P4_KEYINFO_HANDOFF);
62865           VdbeComment((v, "%s", pIdx->zName));
62866           eType = IN_INDEX_INDEX;
62867
62868           sqlite3VdbeJumpHere(v, iAddr);
62869           if( prNotFound && !pTab->aCol[iCol].notNull ){
62870             *prNotFound = ++pParse->nMem;
62871           }
62872         }
62873       }
62874     }
62875   }
62876
62877   if( eType==0 ){
62878     /* Could not found an existing table or index to use as the RHS b-tree.
62879     ** We will have to generate an ephemeral table to do the job.
62880     */
62881     int rMayHaveNull = 0;
62882     eType = IN_INDEX_EPH;
62883     if( prNotFound ){
62884       *prNotFound = rMayHaveNull = ++pParse->nMem;
62885     }else if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
62886       eType = IN_INDEX_ROWID;
62887     }
62888     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
62889   }else{
62890     pX->iTable = iTab;
62891   }
62892   return eType;
62893 }
62894 #endif
62895
62896 /*
62897 ** Generate code for scalar subqueries used as an expression
62898 ** and IN operators.  Examples:
62899 **
62900 **     (SELECT a FROM b)          -- subquery
62901 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
62902 **     x IN (4,5,11)              -- IN operator with list on right-hand side
62903 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
62904 **
62905 ** The pExpr parameter describes the expression that contains the IN
62906 ** operator or subquery.
62907 **
62908 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
62909 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
62910 ** to some integer key column of a table B-Tree. In this case, use an
62911 ** intkey B-Tree to store the set of IN(...) values instead of the usual
62912 ** (slower) variable length keys B-Tree.
62913 **
62914 ** If rMayHaveNull is non-zero, that means that the operation is an IN
62915 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
62916 ** Furthermore, the IN is in a WHERE clause and that we really want
62917 ** to iterate over the RHS of the IN operator in order to quickly locate
62918 ** all corresponding LHS elements.  All this routine does is initialize
62919 ** the register given by rMayHaveNull to NULL.  Calling routines will take
62920 ** care of changing this register value to non-NULL if the RHS is NULL-free.
62921 **
62922 ** If rMayHaveNull is zero, that means that the subquery is being used
62923 ** for membership testing only.  There is no need to initialize any
62924 ** registers to indicate the presense or absence of NULLs on the RHS.
62925 **
62926 ** For a SELECT or EXISTS operator, return the register that holds the
62927 ** result.  For IN operators or if an error occurs, the return value is 0.
62928 */
62929 #ifndef SQLITE_OMIT_SUBQUERY
62930 SQLITE_PRIVATE int sqlite3CodeSubselect(
62931   Parse *pParse,          /* Parsing context */
62932   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
62933   int rMayHaveNull,       /* Register that records whether NULLs exist in RHS */
62934   int isRowid             /* If true, LHS of IN operator is a rowid */
62935 ){
62936   int testAddr = 0;                       /* One-time test address */
62937   int rReg = 0;                           /* Register storing resulting */
62938   Vdbe *v = sqlite3GetVdbe(pParse);
62939   if( NEVER(v==0) ) return 0;
62940   sqlite3ExprCachePush(pParse);
62941
62942   /* This code must be run in its entirety every time it is encountered
62943   ** if any of the following is true:
62944   **
62945   **    *  The right-hand side is a correlated subquery
62946   **    *  The right-hand side is an expression list containing variables
62947   **    *  We are inside a trigger
62948   **
62949   ** If all of the above are false, then we can run this code just once
62950   ** save the results, and reuse the same result on subsequent invocations.
62951   */
62952   if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
62953     int mem = ++pParse->nMem;
62954     sqlite3VdbeAddOp1(v, OP_If, mem);
62955     testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
62956     assert( testAddr>0 || pParse->db->mallocFailed );
62957   }
62958
62959   switch( pExpr->op ){
62960     case TK_IN: {
62961       char affinity;
62962       KeyInfo keyInfo;
62963       int addr;        /* Address of OP_OpenEphemeral instruction */
62964       Expr *pLeft = pExpr->pLeft;
62965
62966       if( rMayHaveNull ){
62967         sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
62968       }
62969
62970       affinity = sqlite3ExprAffinity(pLeft);
62971
62972       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
62973       ** expression it is handled the same way.  An ephemeral table is 
62974       ** filled with single-field index keys representing the results
62975       ** from the SELECT or the <exprlist>.
62976       **
62977       ** If the 'x' expression is a column value, or the SELECT...
62978       ** statement returns a column value, then the affinity of that
62979       ** column is used to build the index keys. If both 'x' and the
62980       ** SELECT... statement are columns, then numeric affinity is used
62981       ** if either column has NUMERIC or INTEGER affinity. If neither
62982       ** 'x' nor the SELECT... statement are columns, then numeric affinity
62983       ** is used.
62984       */
62985       pExpr->iTable = pParse->nTab++;
62986       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
62987       memset(&keyInfo, 0, sizeof(keyInfo));
62988       keyInfo.nField = 1;
62989
62990       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
62991         /* Case 1:     expr IN (SELECT ...)
62992         **
62993         ** Generate code to write the results of the select into the temporary
62994         ** table allocated and opened above.
62995         */
62996         SelectDest dest;
62997         ExprList *pEList;
62998
62999         assert( !isRowid );
63000         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
63001         dest.affinity = (u8)affinity;
63002         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
63003         if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
63004           return 0;
63005         }
63006         pEList = pExpr->x.pSelect->pEList;
63007         if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){ 
63008           keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
63009               pEList->a[0].pExpr);
63010         }
63011       }else if( pExpr->x.pList!=0 ){
63012         /* Case 2:     expr IN (exprlist)
63013         **
63014         ** For each expression, build an index key from the evaluation and
63015         ** store it in the temporary table. If <expr> is a column, then use
63016         ** that columns affinity when building index keys. If <expr> is not
63017         ** a column, use numeric affinity.
63018         */
63019         int i;
63020         ExprList *pList = pExpr->x.pList;
63021         struct ExprList_item *pItem;
63022         int r1, r2, r3;
63023
63024         if( !affinity ){
63025           affinity = SQLITE_AFF_NONE;
63026         }
63027         keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
63028
63029         /* Loop through each expression in <exprlist>. */
63030         r1 = sqlite3GetTempReg(pParse);
63031         r2 = sqlite3GetTempReg(pParse);
63032         sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
63033         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
63034           Expr *pE2 = pItem->pExpr;
63035           int iValToIns;
63036
63037           /* If the expression is not constant then we will need to
63038           ** disable the test that was generated above that makes sure
63039           ** this code only executes once.  Because for a non-constant
63040           ** expression we need to rerun this code each time.
63041           */
63042           if( testAddr && !sqlite3ExprIsConstant(pE2) ){
63043             sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
63044             testAddr = 0;
63045           }
63046
63047           /* Evaluate the expression and insert it into the temp table */
63048           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
63049             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
63050           }else{
63051             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
63052             if( isRowid ){
63053               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
63054                                 sqlite3VdbeCurrentAddr(v)+2);
63055               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
63056             }else{
63057               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
63058               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
63059               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
63060             }
63061           }
63062         }
63063         sqlite3ReleaseTempReg(pParse, r1);
63064         sqlite3ReleaseTempReg(pParse, r2);
63065       }
63066       if( !isRowid ){
63067         sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
63068       }
63069       break;
63070     }
63071
63072     case TK_EXISTS:
63073     case TK_SELECT:
63074     default: {
63075       /* If this has to be a scalar SELECT.  Generate code to put the
63076       ** value of this select in a memory cell and record the number
63077       ** of the memory cell in iColumn.  If this is an EXISTS, write
63078       ** an integer 0 (not exists) or 1 (exists) into a memory cell
63079       ** and record that memory cell in iColumn.
63080       */
63081       static const Token one = { "1", 1 };  /* Token for literal value 1 */
63082       Select *pSel;                         /* SELECT statement to encode */
63083       SelectDest dest;                      /* How to deal with SELECt result */
63084
63085       testcase( pExpr->op==TK_EXISTS );
63086       testcase( pExpr->op==TK_SELECT );
63087       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
63088
63089       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
63090       pSel = pExpr->x.pSelect;
63091       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
63092       if( pExpr->op==TK_SELECT ){
63093         dest.eDest = SRT_Mem;
63094         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
63095         VdbeComment((v, "Init subquery result"));
63096       }else{
63097         dest.eDest = SRT_Exists;
63098         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
63099         VdbeComment((v, "Init EXISTS result"));
63100       }
63101       sqlite3ExprDelete(pParse->db, pSel->pLimit);
63102       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
63103       if( sqlite3Select(pParse, pSel, &dest) ){
63104         return 0;
63105       }
63106       rReg = dest.iParm;
63107       ExprSetIrreducible(pExpr);
63108       break;
63109     }
63110   }
63111
63112   if( testAddr ){
63113     sqlite3VdbeJumpHere(v, testAddr-1);
63114   }
63115   sqlite3ExprCachePop(pParse, 1);
63116
63117   return rReg;
63118 }
63119 #endif /* SQLITE_OMIT_SUBQUERY */
63120
63121 #ifndef SQLITE_OMIT_SUBQUERY
63122 /*
63123 ** Generate code for an IN expression.
63124 **
63125 **      x IN (SELECT ...)
63126 **      x IN (value, value, ...)
63127 **
63128 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
63129 ** is an array of zero or more values.  The expression is true if the LHS is
63130 ** contained within the RHS.  The value of the expression is unknown (NULL)
63131 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
63132 ** RHS contains one or more NULL values.
63133 **
63134 ** This routine generates code will jump to destIfFalse if the LHS is not 
63135 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
63136 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
63137 ** within the RHS then fall through.
63138 */
63139 static void sqlite3ExprCodeIN(
63140   Parse *pParse,        /* Parsing and code generating context */
63141   Expr *pExpr,          /* The IN expression */
63142   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
63143   int destIfNull        /* Jump here if the results are unknown due to NULLs */
63144 ){
63145   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
63146   char affinity;        /* Comparison affinity to use */
63147   int eType;            /* Type of the RHS */
63148   int r1;               /* Temporary use register */
63149   Vdbe *v;              /* Statement under construction */
63150
63151   /* Compute the RHS.   After this step, the table with cursor
63152   ** pExpr->iTable will contains the values that make up the RHS.
63153   */
63154   v = pParse->pVdbe;
63155   assert( v!=0 );       /* OOM detected prior to this routine */
63156   VdbeNoopComment((v, "begin IN expr"));
63157   eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
63158
63159   /* Figure out the affinity to use to create a key from the results
63160   ** of the expression. affinityStr stores a static string suitable for
63161   ** P4 of OP_MakeRecord.
63162   */
63163   affinity = comparisonAffinity(pExpr);
63164
63165   /* Code the LHS, the <expr> from "<expr> IN (...)".
63166   */
63167   sqlite3ExprCachePush(pParse);
63168   r1 = sqlite3GetTempReg(pParse);
63169   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
63170   sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
63171
63172
63173   if( eType==IN_INDEX_ROWID ){
63174     /* In this case, the RHS is the ROWID of table b-tree
63175     */
63176     sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
63177     sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
63178   }else{
63179     /* In this case, the RHS is an index b-tree.
63180     */
63181     sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
63182
63183     /* If the set membership test fails, then the result of the 
63184     ** "x IN (...)" expression must be either 0 or NULL. If the set
63185     ** contains no NULL values, then the result is 0. If the set 
63186     ** contains one or more NULL values, then the result of the
63187     ** expression is also NULL.
63188     */
63189     if( rRhsHasNull==0 || destIfFalse==destIfNull ){
63190       /* This branch runs if it is known at compile time that the RHS
63191       ** cannot contain NULL values. This happens as the result
63192       ** of a "NOT NULL" constraint in the database schema.
63193       **
63194       ** Also run this branch if NULL is equivalent to FALSE
63195       ** for this particular IN operator.
63196       */
63197       sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
63198
63199     }else{
63200       /* In this branch, the RHS of the IN might contain a NULL and
63201       ** the presence of a NULL on the RHS makes a difference in the
63202       ** outcome.
63203       */
63204       int j1, j2, j3;
63205
63206       /* First check to see if the LHS is contained in the RHS.  If so,
63207       ** then the presence of NULLs in the RHS does not matter, so jump
63208       ** over all of the code that follows.
63209       */
63210       j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
63211
63212       /* Here we begin generating code that runs if the LHS is not
63213       ** contained within the RHS.  Generate additional code that
63214       ** tests the RHS for NULLs.  If the RHS contains a NULL then
63215       ** jump to destIfNull.  If there are no NULLs in the RHS then
63216       ** jump to destIfFalse.
63217       */
63218       j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
63219       j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
63220       sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
63221       sqlite3VdbeJumpHere(v, j3);
63222       sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
63223       sqlite3VdbeJumpHere(v, j2);
63224
63225       /* Jump to the appropriate target depending on whether or not
63226       ** the RHS contains a NULL
63227       */
63228       sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
63229       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
63230
63231       /* The OP_Found at the top of this branch jumps here when true, 
63232       ** causing the overall IN expression evaluation to fall through.
63233       */
63234       sqlite3VdbeJumpHere(v, j1);
63235     }
63236   }
63237   sqlite3ReleaseTempReg(pParse, r1);
63238   sqlite3ExprCachePop(pParse, 1);
63239   VdbeComment((v, "end IN expr"));
63240 }
63241 #endif /* SQLITE_OMIT_SUBQUERY */
63242
63243 /*
63244 ** Duplicate an 8-byte value
63245 */
63246 static char *dup8bytes(Vdbe *v, const char *in){
63247   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
63248   if( out ){
63249     memcpy(out, in, 8);
63250   }
63251   return out;
63252 }
63253
63254 #ifndef SQLITE_OMIT_FLOATING_POINT
63255 /*
63256 ** Generate an instruction that will put the floating point
63257 ** value described by z[0..n-1] into register iMem.
63258 **
63259 ** The z[] string will probably not be zero-terminated.  But the 
63260 ** z[n] character is guaranteed to be something that does not look
63261 ** like the continuation of the number.
63262 */
63263 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
63264   if( ALWAYS(z!=0) ){
63265     double value;
63266     char *zV;
63267     sqlite3AtoF(z, &value);
63268     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
63269     if( negateFlag ) value = -value;
63270     zV = dup8bytes(v, (char*)&value);
63271     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
63272   }
63273 }
63274 #endif
63275
63276
63277 /*
63278 ** Generate an instruction that will put the integer describe by
63279 ** text z[0..n-1] into register iMem.
63280 **
63281 ** The z[] string will probably not be zero-terminated.  But the 
63282 ** z[n] character is guaranteed to be something that does not look
63283 ** like the continuation of the number.
63284 */
63285 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
63286   Vdbe *v = pParse->pVdbe;
63287   if( pExpr->flags & EP_IntValue ){
63288     int i = pExpr->u.iValue;
63289     if( negFlag ) i = -i;
63290     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
63291   }else{
63292     const char *z = pExpr->u.zToken;
63293     assert( z!=0 );
63294     if( sqlite3FitsIn64Bits(z, negFlag) ){
63295       i64 value;
63296       char *zV;
63297       sqlite3Atoi64(z, &value);
63298       if( negFlag ) value = -value;
63299       zV = dup8bytes(v, (char*)&value);
63300       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
63301     }else{
63302 #ifdef SQLITE_OMIT_FLOATING_POINT
63303       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
63304 #else
63305       codeReal(v, z, negFlag, iMem);
63306 #endif
63307     }
63308   }
63309 }
63310
63311 /*
63312 ** Clear a cache entry.
63313 */
63314 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
63315   if( p->tempReg ){
63316     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
63317       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
63318     }
63319     p->tempReg = 0;
63320   }
63321 }
63322
63323
63324 /*
63325 ** Record in the column cache that a particular column from a
63326 ** particular table is stored in a particular register.
63327 */
63328 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
63329   int i;
63330   int minLru;
63331   int idxLru;
63332   struct yColCache *p;
63333
63334   assert( iReg>0 );  /* Register numbers are always positive */
63335   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
63336
63337   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
63338   ** for testing only - to verify that SQLite always gets the same answer
63339   ** with and without the column cache.
63340   */
63341   if( pParse->db->flags & SQLITE_ColumnCache ) return;
63342
63343   /* First replace any existing entry.
63344   **
63345   ** Actually, the way the column cache is currently used, we are guaranteed
63346   ** that the object will never already be in cache.  Verify this guarantee.
63347   */
63348 #ifndef NDEBUG
63349   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
63350 #if 0 /* This code wold remove the entry from the cache if it existed */
63351     if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
63352       cacheEntryClear(pParse, p);
63353       p->iLevel = pParse->iCacheLevel;
63354       p->iReg = iReg;
63355       p->lru = pParse->iCacheCnt++;
63356       return;
63357     }
63358 #endif
63359     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
63360   }
63361 #endif
63362
63363   /* Find an empty slot and replace it */
63364   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
63365     if( p->iReg==0 ){
63366       p->iLevel = pParse->iCacheLevel;
63367       p->iTable = iTab;
63368       p->iColumn = iCol;
63369       p->iReg = iReg;
63370       p->tempReg = 0;
63371       p->lru = pParse->iCacheCnt++;
63372       return;
63373     }
63374   }
63375
63376   /* Replace the last recently used */
63377   minLru = 0x7fffffff;
63378   idxLru = -1;
63379   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
63380     if( p->lru<minLru ){
63381       idxLru = i;
63382       minLru = p->lru;
63383     }
63384   }
63385   if( ALWAYS(idxLru>=0) ){
63386     p = &pParse->aColCache[idxLru];
63387     p->iLevel = pParse->iCacheLevel;
63388     p->iTable = iTab;
63389     p->iColumn = iCol;
63390     p->iReg = iReg;
63391     p->tempReg = 0;
63392     p->lru = pParse->iCacheCnt++;
63393     return;
63394   }
63395 }
63396
63397 /*
63398 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
63399 ** Purge the range of registers from the column cache.
63400 */
63401 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
63402   int i;
63403   int iLast = iReg + nReg - 1;
63404   struct yColCache *p;
63405   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
63406     int r = p->iReg;
63407     if( r>=iReg && r<=iLast ){
63408       cacheEntryClear(pParse, p);
63409       p->iReg = 0;
63410     }
63411   }
63412 }
63413
63414 /*
63415 ** Remember the current column cache context.  Any new entries added
63416 ** added to the column cache after this call are removed when the
63417 ** corresponding pop occurs.
63418 */
63419 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
63420   pParse->iCacheLevel++;
63421 }
63422
63423 /*
63424 ** Remove from the column cache any entries that were added since the
63425 ** the previous N Push operations.  In other words, restore the cache
63426 ** to the state it was in N Pushes ago.
63427 */
63428 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse, int N){
63429   int i;
63430   struct yColCache *p;
63431   assert( N>0 );
63432   assert( pParse->iCacheLevel>=N );
63433   pParse->iCacheLevel -= N;
63434   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
63435     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
63436       cacheEntryClear(pParse, p);
63437       p->iReg = 0;
63438     }
63439   }
63440 }
63441
63442 /*
63443 ** When a cached column is reused, make sure that its register is
63444 ** no longer available as a temp register.  ticket #3879:  that same
63445 ** register might be in the cache in multiple places, so be sure to
63446 ** get them all.
63447 */
63448 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
63449   int i;
63450   struct yColCache *p;
63451   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
63452     if( p->iReg==iReg ){
63453       p->tempReg = 0;
63454     }
63455   }
63456 }
63457
63458 /*
63459 ** Generate code that will extract the iColumn-th column from
63460 ** table pTab and store the column value in a register.  An effort
63461 ** is made to store the column value in register iReg, but this is
63462 ** not guaranteed.  The location of the column value is returned.
63463 **
63464 ** There must be an open cursor to pTab in iTable when this routine
63465 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
63466 */
63467 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
63468   Parse *pParse,   /* Parsing and code generating context */
63469   Table *pTab,     /* Description of the table we are reading from */
63470   int iColumn,     /* Index of the table column */
63471   int iTable,      /* The cursor pointing to the table */
63472   int iReg         /* Store results here */
63473 ){
63474   Vdbe *v = pParse->pVdbe;
63475   int i;
63476   struct yColCache *p;
63477
63478   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
63479     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
63480       p->lru = pParse->iCacheCnt++;
63481       sqlite3ExprCachePinRegister(pParse, p->iReg);
63482       return p->iReg;
63483     }
63484   }  
63485   assert( v!=0 );
63486   if( iColumn<0 ){
63487     sqlite3VdbeAddOp2(v, OP_Rowid, iTable, iReg);
63488   }else if( ALWAYS(pTab!=0) ){
63489     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
63490     sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
63491     sqlite3ColumnDefault(v, pTab, iColumn, iReg);
63492   }
63493   sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
63494   return iReg;
63495 }
63496
63497 /*
63498 ** Clear all column cache entries.
63499 */
63500 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
63501   int i;
63502   struct yColCache *p;
63503
63504   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
63505     if( p->iReg ){
63506       cacheEntryClear(pParse, p);
63507       p->iReg = 0;
63508     }
63509   }
63510 }
63511
63512 /*
63513 ** Record the fact that an affinity change has occurred on iCount
63514 ** registers starting with iStart.
63515 */
63516 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
63517   sqlite3ExprCacheRemove(pParse, iStart, iCount);
63518 }
63519
63520 /*
63521 ** Generate code to move content from registers iFrom...iFrom+nReg-1
63522 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
63523 */
63524 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
63525   int i;
63526   struct yColCache *p;
63527   if( NEVER(iFrom==iTo) ) return;
63528   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
63529   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
63530     int x = p->iReg;
63531     if( x>=iFrom && x<iFrom+nReg ){
63532       p->iReg += iTo-iFrom;
63533     }
63534   }
63535 }
63536
63537 /*
63538 ** Generate code to copy content from registers iFrom...iFrom+nReg-1
63539 ** over to iTo..iTo+nReg-1.
63540 */
63541 SQLITE_PRIVATE void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
63542   int i;
63543   if( NEVER(iFrom==iTo) ) return;
63544   for(i=0; i<nReg; i++){
63545     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
63546   }
63547 }
63548
63549 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
63550 /*
63551 ** Return true if any register in the range iFrom..iTo (inclusive)
63552 ** is used as part of the column cache.
63553 **
63554 ** This routine is used within assert() and testcase() macros only
63555 ** and does not appear in a normal build.
63556 */
63557 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
63558   int i;
63559   struct yColCache *p;
63560   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
63561     int r = p->iReg;
63562     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
63563   }
63564   return 0;
63565 }
63566 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
63567
63568 /*
63569 ** If the last instruction coded is an ephemeral copy of any of
63570 ** the registers in the nReg registers beginning with iReg, then
63571 ** convert the last instruction from OP_SCopy to OP_Copy.
63572 */
63573 SQLITE_PRIVATE void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
63574   VdbeOp *pOp;
63575   Vdbe *v;
63576
63577   assert( pParse->db->mallocFailed==0 );
63578   v = pParse->pVdbe;
63579   assert( v!=0 );
63580   pOp = sqlite3VdbeGetOp(v, -1);
63581   assert( pOp!=0 );
63582   if( pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
63583     pOp->opcode = OP_Copy;
63584   }
63585 }
63586
63587 /*
63588 ** Generate code to store the value of the iAlias-th alias in register
63589 ** target.  The first time this is called, pExpr is evaluated to compute
63590 ** the value of the alias.  The value is stored in an auxiliary register
63591 ** and the number of that register is returned.  On subsequent calls,
63592 ** the register number is returned without generating any code.
63593 **
63594 ** Note that in order for this to work, code must be generated in the
63595 ** same order that it is executed.
63596 **
63597 ** Aliases are numbered starting with 1.  So iAlias is in the range
63598 ** of 1 to pParse->nAlias inclusive.  
63599 **
63600 ** pParse->aAlias[iAlias-1] records the register number where the value
63601 ** of the iAlias-th alias is stored.  If zero, that means that the
63602 ** alias has not yet been computed.
63603 */
63604 static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
63605 #if 0
63606   sqlite3 *db = pParse->db;
63607   int iReg;
63608   if( pParse->nAliasAlloc<pParse->nAlias ){
63609     pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
63610                                  sizeof(pParse->aAlias[0])*pParse->nAlias );
63611     testcase( db->mallocFailed && pParse->nAliasAlloc>0 );
63612     if( db->mallocFailed ) return 0;
63613     memset(&pParse->aAlias[pParse->nAliasAlloc], 0,
63614            (pParse->nAlias-pParse->nAliasAlloc)*sizeof(pParse->aAlias[0]));
63615     pParse->nAliasAlloc = pParse->nAlias;
63616   }
63617   assert( iAlias>0 && iAlias<=pParse->nAlias );
63618   iReg = pParse->aAlias[iAlias-1];
63619   if( iReg==0 ){
63620     if( pParse->iCacheLevel>0 ){
63621       iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
63622     }else{
63623       iReg = ++pParse->nMem;
63624       sqlite3ExprCode(pParse, pExpr, iReg);
63625       pParse->aAlias[iAlias-1] = iReg;
63626     }
63627   }
63628   return iReg;
63629 #else
63630   UNUSED_PARAMETER(iAlias);
63631   return sqlite3ExprCodeTarget(pParse, pExpr, target);
63632 #endif
63633 }
63634
63635 /*
63636 ** Generate code into the current Vdbe to evaluate the given
63637 ** expression.  Attempt to store the results in register "target".
63638 ** Return the register where results are stored.
63639 **
63640 ** With this routine, there is no guarantee that results will
63641 ** be stored in target.  The result might be stored in some other
63642 ** register if it is convenient to do so.  The calling function
63643 ** must check the return code and move the results to the desired
63644 ** register.
63645 */
63646 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
63647   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
63648   int op;                   /* The opcode being coded */
63649   int inReg = target;       /* Results stored in register inReg */
63650   int regFree1 = 0;         /* If non-zero free this temporary register */
63651   int regFree2 = 0;         /* If non-zero free this temporary register */
63652   int r1, r2, r3, r4;       /* Various register numbers */
63653   sqlite3 *db = pParse->db; /* The database connection */
63654
63655   assert( target>0 && target<=pParse->nMem );
63656   if( v==0 ){
63657     assert( pParse->db->mallocFailed );
63658     return 0;
63659   }
63660
63661   if( pExpr==0 ){
63662     op = TK_NULL;
63663   }else{
63664     op = pExpr->op;
63665   }
63666   switch( op ){
63667     case TK_AGG_COLUMN: {
63668       AggInfo *pAggInfo = pExpr->pAggInfo;
63669       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
63670       if( !pAggInfo->directMode ){
63671         assert( pCol->iMem>0 );
63672         inReg = pCol->iMem;
63673         break;
63674       }else if( pAggInfo->useSortingIdx ){
63675         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
63676                               pCol->iSorterColumn, target);
63677         break;
63678       }
63679       /* Otherwise, fall thru into the TK_COLUMN case */
63680     }
63681     case TK_COLUMN: {
63682       if( pExpr->iTable<0 ){
63683         /* This only happens when coding check constraints */
63684         assert( pParse->ckBase>0 );
63685         inReg = pExpr->iColumn + pParse->ckBase;
63686       }else{
63687         inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
63688                                  pExpr->iColumn, pExpr->iTable, target);
63689       }
63690       break;
63691     }
63692     case TK_INTEGER: {
63693       codeInteger(pParse, pExpr, 0, target);
63694       break;
63695     }
63696 #ifndef SQLITE_OMIT_FLOATING_POINT
63697     case TK_FLOAT: {
63698       assert( !ExprHasProperty(pExpr, EP_IntValue) );
63699       codeReal(v, pExpr->u.zToken, 0, target);
63700       break;
63701     }
63702 #endif
63703     case TK_STRING: {
63704       assert( !ExprHasProperty(pExpr, EP_IntValue) );
63705       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
63706       break;
63707     }
63708     case TK_NULL: {
63709       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
63710       break;
63711     }
63712 #ifndef SQLITE_OMIT_BLOB_LITERAL
63713     case TK_BLOB: {
63714       int n;
63715       const char *z;
63716       char *zBlob;
63717       assert( !ExprHasProperty(pExpr, EP_IntValue) );
63718       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
63719       assert( pExpr->u.zToken[1]=='\'' );
63720       z = &pExpr->u.zToken[2];
63721       n = sqlite3Strlen30(z) - 1;
63722       assert( z[n]=='\'' );
63723       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
63724       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
63725       break;
63726     }
63727 #endif
63728     case TK_VARIABLE: {
63729       VdbeOp *pOp;
63730       assert( !ExprHasProperty(pExpr, EP_IntValue) );
63731       assert( pExpr->u.zToken!=0 );
63732       assert( pExpr->u.zToken[0]!=0 );
63733       if( pExpr->u.zToken[1]==0
63734          && (pOp = sqlite3VdbeGetOp(v, -1))->opcode==OP_Variable
63735          && pOp->p1+pOp->p3==pExpr->iColumn
63736          && pOp->p2+pOp->p3==target
63737          && pOp->p4.z==0
63738       ){
63739         /* If the previous instruction was a copy of the previous unnamed
63740         ** parameter into the previous register, then simply increment the
63741         ** repeat count on the prior instruction rather than making a new
63742         ** instruction.
63743         */
63744         pOp->p3++;
63745       }else{
63746         sqlite3VdbeAddOp3(v, OP_Variable, pExpr->iColumn, target, 1);
63747         if( pExpr->u.zToken[1]!=0 ){
63748           sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, 0);
63749         }
63750       }
63751       break;
63752     }
63753     case TK_REGISTER: {
63754       inReg = pExpr->iTable;
63755       break;
63756     }
63757     case TK_AS: {
63758       inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target);
63759       break;
63760     }
63761 #ifndef SQLITE_OMIT_CAST
63762     case TK_CAST: {
63763       /* Expressions of the form:   CAST(pLeft AS token) */
63764       int aff, to_op;
63765       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
63766       assert( !ExprHasProperty(pExpr, EP_IntValue) );
63767       aff = sqlite3AffinityType(pExpr->u.zToken);
63768       to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
63769       assert( to_op==OP_ToText    || aff!=SQLITE_AFF_TEXT    );
63770       assert( to_op==OP_ToBlob    || aff!=SQLITE_AFF_NONE    );
63771       assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
63772       assert( to_op==OP_ToInt     || aff!=SQLITE_AFF_INTEGER );
63773       assert( to_op==OP_ToReal    || aff!=SQLITE_AFF_REAL    );
63774       testcase( to_op==OP_ToText );
63775       testcase( to_op==OP_ToBlob );
63776       testcase( to_op==OP_ToNumeric );
63777       testcase( to_op==OP_ToInt );
63778       testcase( to_op==OP_ToReal );
63779       if( inReg!=target ){
63780         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
63781         inReg = target;
63782       }
63783       sqlite3VdbeAddOp1(v, to_op, inReg);
63784       testcase( usedAsColumnCache(pParse, inReg, inReg) );
63785       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
63786       break;
63787     }
63788 #endif /* SQLITE_OMIT_CAST */
63789     case TK_LT:
63790     case TK_LE:
63791     case TK_GT:
63792     case TK_GE:
63793     case TK_NE:
63794     case TK_EQ: {
63795       assert( TK_LT==OP_Lt );
63796       assert( TK_LE==OP_Le );
63797       assert( TK_GT==OP_Gt );
63798       assert( TK_GE==OP_Ge );
63799       assert( TK_EQ==OP_Eq );
63800       assert( TK_NE==OP_Ne );
63801       testcase( op==TK_LT );
63802       testcase( op==TK_LE );
63803       testcase( op==TK_GT );
63804       testcase( op==TK_GE );
63805       testcase( op==TK_EQ );
63806       testcase( op==TK_NE );
63807       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63808       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63809       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
63810                   r1, r2, inReg, SQLITE_STOREP2);
63811       testcase( regFree1==0 );
63812       testcase( regFree2==0 );
63813       break;
63814     }
63815     case TK_IS:
63816     case TK_ISNOT: {
63817       testcase( op==TK_IS );
63818       testcase( op==TK_ISNOT );
63819       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63820       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63821       op = (op==TK_IS) ? TK_EQ : TK_NE;
63822       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
63823                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
63824       testcase( regFree1==0 );
63825       testcase( regFree2==0 );
63826       break;
63827     }
63828     case TK_AND:
63829     case TK_OR:
63830     case TK_PLUS:
63831     case TK_STAR:
63832     case TK_MINUS:
63833     case TK_REM:
63834     case TK_BITAND:
63835     case TK_BITOR:
63836     case TK_SLASH:
63837     case TK_LSHIFT:
63838     case TK_RSHIFT: 
63839     case TK_CONCAT: {
63840       assert( TK_AND==OP_And );
63841       assert( TK_OR==OP_Or );
63842       assert( TK_PLUS==OP_Add );
63843       assert( TK_MINUS==OP_Subtract );
63844       assert( TK_REM==OP_Remainder );
63845       assert( TK_BITAND==OP_BitAnd );
63846       assert( TK_BITOR==OP_BitOr );
63847       assert( TK_SLASH==OP_Divide );
63848       assert( TK_LSHIFT==OP_ShiftLeft );
63849       assert( TK_RSHIFT==OP_ShiftRight );
63850       assert( TK_CONCAT==OP_Concat );
63851       testcase( op==TK_AND );
63852       testcase( op==TK_OR );
63853       testcase( op==TK_PLUS );
63854       testcase( op==TK_MINUS );
63855       testcase( op==TK_REM );
63856       testcase( op==TK_BITAND );
63857       testcase( op==TK_BITOR );
63858       testcase( op==TK_SLASH );
63859       testcase( op==TK_LSHIFT );
63860       testcase( op==TK_RSHIFT );
63861       testcase( op==TK_CONCAT );
63862       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63863       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
63864       sqlite3VdbeAddOp3(v, op, r2, r1, target);
63865       testcase( regFree1==0 );
63866       testcase( regFree2==0 );
63867       break;
63868     }
63869     case TK_UMINUS: {
63870       Expr *pLeft = pExpr->pLeft;
63871       assert( pLeft );
63872       if( pLeft->op==TK_INTEGER ){
63873         codeInteger(pParse, pLeft, 1, target);
63874 #ifndef SQLITE_OMIT_FLOATING_POINT
63875       }else if( pLeft->op==TK_FLOAT ){
63876         assert( !ExprHasProperty(pExpr, EP_IntValue) );
63877         codeReal(v, pLeft->u.zToken, 1, target);
63878 #endif
63879       }else{
63880         regFree1 = r1 = sqlite3GetTempReg(pParse);
63881         sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
63882         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
63883         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
63884         testcase( regFree2==0 );
63885       }
63886       inReg = target;
63887       break;
63888     }
63889     case TK_BITNOT:
63890     case TK_NOT: {
63891       assert( TK_BITNOT==OP_BitNot );
63892       assert( TK_NOT==OP_Not );
63893       testcase( op==TK_BITNOT );
63894       testcase( op==TK_NOT );
63895       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63896       testcase( regFree1==0 );
63897       inReg = target;
63898       sqlite3VdbeAddOp2(v, op, r1, inReg);
63899       break;
63900     }
63901     case TK_ISNULL:
63902     case TK_NOTNULL: {
63903       int addr;
63904       assert( TK_ISNULL==OP_IsNull );
63905       assert( TK_NOTNULL==OP_NotNull );
63906       testcase( op==TK_ISNULL );
63907       testcase( op==TK_NOTNULL );
63908       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
63909       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
63910       testcase( regFree1==0 );
63911       addr = sqlite3VdbeAddOp1(v, op, r1);
63912       sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
63913       sqlite3VdbeJumpHere(v, addr);
63914       break;
63915     }
63916     case TK_AGG_FUNCTION: {
63917       AggInfo *pInfo = pExpr->pAggInfo;
63918       if( pInfo==0 ){
63919         assert( !ExprHasProperty(pExpr, EP_IntValue) );
63920         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
63921       }else{
63922         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
63923       }
63924       break;
63925     }
63926     case TK_CONST_FUNC:
63927     case TK_FUNCTION: {
63928       ExprList *pFarg;       /* List of function arguments */
63929       int nFarg;             /* Number of function arguments */
63930       FuncDef *pDef;         /* The function definition object */
63931       int nId;               /* Length of the function name in bytes */
63932       const char *zId;       /* The function name */
63933       int constMask = 0;     /* Mask of function arguments that are constant */
63934       int i;                 /* Loop counter */
63935       u8 enc = ENC(db);      /* The text encoding used by this database */
63936       CollSeq *pColl = 0;    /* A collating sequence */
63937
63938       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
63939       testcase( op==TK_CONST_FUNC );
63940       testcase( op==TK_FUNCTION );
63941       if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
63942         pFarg = 0;
63943       }else{
63944         pFarg = pExpr->x.pList;
63945       }
63946       nFarg = pFarg ? pFarg->nExpr : 0;
63947       assert( !ExprHasProperty(pExpr, EP_IntValue) );
63948       zId = pExpr->u.zToken;
63949       nId = sqlite3Strlen30(zId);
63950       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
63951       if( pDef==0 ){
63952         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
63953         break;
63954       }
63955
63956       /* Attempt a direct implementation of the built-in COALESCE() and
63957       ** IFNULL() functions.  This avoids unnecessary evalation of
63958       ** arguments past the first non-NULL argument.
63959       */
63960       if( pDef->flags & SQLITE_FUNC_COALESCE ){
63961         int endCoalesce = sqlite3VdbeMakeLabel(v);
63962         assert( nFarg>=2 );
63963         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
63964         for(i=1; i<nFarg; i++){
63965           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
63966           sqlite3ExprCacheRemove(pParse, target, 1);
63967           sqlite3ExprCachePush(pParse);
63968           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
63969           sqlite3ExprCachePop(pParse, 1);
63970         }
63971         sqlite3VdbeResolveLabel(v, endCoalesce);
63972         break;
63973       }
63974
63975
63976       if( pFarg ){
63977         r1 = sqlite3GetTempRange(pParse, nFarg);
63978         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
63979         sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
63980         sqlite3ExprCachePop(pParse, 1);   /* Ticket 2ea2425d34be */
63981       }else{
63982         r1 = 0;
63983       }
63984 #ifndef SQLITE_OMIT_VIRTUALTABLE
63985       /* Possibly overload the function if the first argument is
63986       ** a virtual table column.
63987       **
63988       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
63989       ** second argument, not the first, as the argument to test to
63990       ** see if it is a column in a virtual table.  This is done because
63991       ** the left operand of infix functions (the operand we want to
63992       ** control overloading) ends up as the second argument to the
63993       ** function.  The expression "A glob B" is equivalent to 
63994       ** "glob(B,A).  We want to use the A in "A glob B" to test
63995       ** for function overloading.  But we use the B term in "glob(B,A)".
63996       */
63997       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
63998         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
63999       }else if( nFarg>0 ){
64000         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
64001       }
64002 #endif
64003       for(i=0; i<nFarg; i++){
64004         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
64005           constMask |= (1<<i);
64006         }
64007         if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
64008           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
64009         }
64010       }
64011       if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
64012         if( !pColl ) pColl = db->pDfltColl; 
64013         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
64014       }
64015       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
64016                         (char*)pDef, P4_FUNCDEF);
64017       sqlite3VdbeChangeP5(v, (u8)nFarg);
64018       if( nFarg ){
64019         sqlite3ReleaseTempRange(pParse, r1, nFarg);
64020       }
64021       break;
64022     }
64023 #ifndef SQLITE_OMIT_SUBQUERY
64024     case TK_EXISTS:
64025     case TK_SELECT: {
64026       testcase( op==TK_EXISTS );
64027       testcase( op==TK_SELECT );
64028       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
64029       break;
64030     }
64031     case TK_IN: {
64032       int destIfFalse = sqlite3VdbeMakeLabel(v);
64033       int destIfNull = sqlite3VdbeMakeLabel(v);
64034       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
64035       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
64036       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
64037       sqlite3VdbeResolveLabel(v, destIfFalse);
64038       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
64039       sqlite3VdbeResolveLabel(v, destIfNull);
64040       break;
64041     }
64042 #endif /* SQLITE_OMIT_SUBQUERY */
64043
64044
64045     /*
64046     **    x BETWEEN y AND z
64047     **
64048     ** This is equivalent to
64049     **
64050     **    x>=y AND x<=z
64051     **
64052     ** X is stored in pExpr->pLeft.
64053     ** Y is stored in pExpr->pList->a[0].pExpr.
64054     ** Z is stored in pExpr->pList->a[1].pExpr.
64055     */
64056     case TK_BETWEEN: {
64057       Expr *pLeft = pExpr->pLeft;
64058       struct ExprList_item *pLItem = pExpr->x.pList->a;
64059       Expr *pRight = pLItem->pExpr;
64060
64061       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
64062       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
64063       testcase( regFree1==0 );
64064       testcase( regFree2==0 );
64065       r3 = sqlite3GetTempReg(pParse);
64066       r4 = sqlite3GetTempReg(pParse);
64067       codeCompare(pParse, pLeft, pRight, OP_Ge,
64068                   r1, r2, r3, SQLITE_STOREP2);
64069       pLItem++;
64070       pRight = pLItem->pExpr;
64071       sqlite3ReleaseTempReg(pParse, regFree2);
64072       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
64073       testcase( regFree2==0 );
64074       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
64075       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
64076       sqlite3ReleaseTempReg(pParse, r3);
64077       sqlite3ReleaseTempReg(pParse, r4);
64078       break;
64079     }
64080     case TK_UPLUS: {
64081       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
64082       break;
64083     }
64084
64085     case TK_TRIGGER: {
64086       /* If the opcode is TK_TRIGGER, then the expression is a reference
64087       ** to a column in the new.* or old.* pseudo-tables available to
64088       ** trigger programs. In this case Expr.iTable is set to 1 for the
64089       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
64090       ** is set to the column of the pseudo-table to read, or to -1 to
64091       ** read the rowid field.
64092       **
64093       ** The expression is implemented using an OP_Param opcode. The p1
64094       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
64095       ** to reference another column of the old.* pseudo-table, where 
64096       ** i is the index of the column. For a new.rowid reference, p1 is
64097       ** set to (n+1), where n is the number of columns in each pseudo-table.
64098       ** For a reference to any other column in the new.* pseudo-table, p1
64099       ** is set to (n+2+i), where n and i are as defined previously. For
64100       ** example, if the table on which triggers are being fired is
64101       ** declared as:
64102       **
64103       **   CREATE TABLE t1(a, b);
64104       **
64105       ** Then p1 is interpreted as follows:
64106       **
64107       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
64108       **   p1==1   ->    old.a         p1==4   ->    new.a
64109       **   p1==2   ->    old.b         p1==5   ->    new.b       
64110       */
64111       Table *pTab = pExpr->pTab;
64112       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
64113
64114       assert( pExpr->iTable==0 || pExpr->iTable==1 );
64115       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
64116       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
64117       assert( p1>=0 && p1<(pTab->nCol*2+2) );
64118
64119       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
64120       VdbeComment((v, "%s.%s -> $%d",
64121         (pExpr->iTable ? "new" : "old"),
64122         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
64123         target
64124       ));
64125
64126 #ifndef SQLITE_OMIT_FLOATING_POINT
64127       /* If the column has REAL affinity, it may currently be stored as an
64128       ** integer. Use OP_RealAffinity to make sure it is really real.  */
64129       if( pExpr->iColumn>=0 
64130        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
64131       ){
64132         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
64133       }
64134 #endif
64135       break;
64136     }
64137
64138
64139     /*
64140     ** Form A:
64141     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
64142     **
64143     ** Form B:
64144     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
64145     **
64146     ** Form A is can be transformed into the equivalent form B as follows:
64147     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
64148     **        WHEN x=eN THEN rN ELSE y END
64149     **
64150     ** X (if it exists) is in pExpr->pLeft.
64151     ** Y is in pExpr->pRight.  The Y is also optional.  If there is no
64152     ** ELSE clause and no other term matches, then the result of the
64153     ** exprssion is NULL.
64154     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
64155     **
64156     ** The result of the expression is the Ri for the first matching Ei,
64157     ** or if there is no matching Ei, the ELSE term Y, or if there is
64158     ** no ELSE term, NULL.
64159     */
64160     default: assert( op==TK_CASE ); {
64161       int endLabel;                     /* GOTO label for end of CASE stmt */
64162       int nextCase;                     /* GOTO label for next WHEN clause */
64163       int nExpr;                        /* 2x number of WHEN terms */
64164       int i;                            /* Loop counter */
64165       ExprList *pEList;                 /* List of WHEN terms */
64166       struct ExprList_item *aListelem;  /* Array of WHEN terms */
64167       Expr opCompare;                   /* The X==Ei expression */
64168       Expr cacheX;                      /* Cached expression X */
64169       Expr *pX;                         /* The X expression */
64170       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
64171       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
64172
64173       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
64174       assert((pExpr->x.pList->nExpr % 2) == 0);
64175       assert(pExpr->x.pList->nExpr > 0);
64176       pEList = pExpr->x.pList;
64177       aListelem = pEList->a;
64178       nExpr = pEList->nExpr;
64179       endLabel = sqlite3VdbeMakeLabel(v);
64180       if( (pX = pExpr->pLeft)!=0 ){
64181         cacheX = *pX;
64182         testcase( pX->op==TK_COLUMN );
64183         testcase( pX->op==TK_REGISTER );
64184         cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
64185         testcase( regFree1==0 );
64186         cacheX.op = TK_REGISTER;
64187         opCompare.op = TK_EQ;
64188         opCompare.pLeft = &cacheX;
64189         pTest = &opCompare;
64190       }
64191       for(i=0; i<nExpr; i=i+2){
64192         sqlite3ExprCachePush(pParse);
64193         if( pX ){
64194           assert( pTest!=0 );
64195           opCompare.pRight = aListelem[i].pExpr;
64196         }else{
64197           pTest = aListelem[i].pExpr;
64198         }
64199         nextCase = sqlite3VdbeMakeLabel(v);
64200         testcase( pTest->op==TK_COLUMN );
64201         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
64202         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
64203         testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
64204         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
64205         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
64206         sqlite3ExprCachePop(pParse, 1);
64207         sqlite3VdbeResolveLabel(v, nextCase);
64208       }
64209       if( pExpr->pRight ){
64210         sqlite3ExprCachePush(pParse);
64211         sqlite3ExprCode(pParse, pExpr->pRight, target);
64212         sqlite3ExprCachePop(pParse, 1);
64213       }else{
64214         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
64215       }
64216       assert( db->mallocFailed || pParse->nErr>0 
64217            || pParse->iCacheLevel==iCacheLevel );
64218       sqlite3VdbeResolveLabel(v, endLabel);
64219       break;
64220     }
64221 #ifndef SQLITE_OMIT_TRIGGER
64222     case TK_RAISE: {
64223       assert( pExpr->affinity==OE_Rollback 
64224            || pExpr->affinity==OE_Abort
64225            || pExpr->affinity==OE_Fail
64226            || pExpr->affinity==OE_Ignore
64227       );
64228       if( !pParse->pTriggerTab ){
64229         sqlite3ErrorMsg(pParse,
64230                        "RAISE() may only be used within a trigger-program");
64231         return 0;
64232       }
64233       if( pExpr->affinity==OE_Abort ){
64234         sqlite3MayAbort(pParse);
64235       }
64236       assert( !ExprHasProperty(pExpr, EP_IntValue) );
64237       if( pExpr->affinity==OE_Ignore ){
64238         sqlite3VdbeAddOp4(
64239             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
64240       }else{
64241         sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
64242       }
64243
64244       break;
64245     }
64246 #endif
64247   }
64248   sqlite3ReleaseTempReg(pParse, regFree1);
64249   sqlite3ReleaseTempReg(pParse, regFree2);
64250   return inReg;
64251 }
64252
64253 /*
64254 ** Generate code to evaluate an expression and store the results
64255 ** into a register.  Return the register number where the results
64256 ** are stored.
64257 **
64258 ** If the register is a temporary register that can be deallocated,
64259 ** then write its number into *pReg.  If the result register is not
64260 ** a temporary, then set *pReg to zero.
64261 */
64262 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
64263   int r1 = sqlite3GetTempReg(pParse);
64264   int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
64265   if( r2==r1 ){
64266     *pReg = r1;
64267   }else{
64268     sqlite3ReleaseTempReg(pParse, r1);
64269     *pReg = 0;
64270   }
64271   return r2;
64272 }
64273
64274 /*
64275 ** Generate code that will evaluate expression pExpr and store the
64276 ** results in register target.  The results are guaranteed to appear
64277 ** in register target.
64278 */
64279 SQLITE_PRIVATE int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
64280   int inReg;
64281
64282   assert( target>0 && target<=pParse->nMem );
64283   inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
64284   assert( pParse->pVdbe || pParse->db->mallocFailed );
64285   if( inReg!=target && pParse->pVdbe ){
64286     sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
64287   }
64288   return target;
64289 }
64290
64291 /*
64292 ** Generate code that evalutes the given expression and puts the result
64293 ** in register target.
64294 **
64295 ** Also make a copy of the expression results into another "cache" register
64296 ** and modify the expression so that the next time it is evaluated,
64297 ** the result is a copy of the cache register.
64298 **
64299 ** This routine is used for expressions that are used multiple 
64300 ** times.  They are evaluated once and the results of the expression
64301 ** are reused.
64302 */
64303 SQLITE_PRIVATE int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
64304   Vdbe *v = pParse->pVdbe;
64305   int inReg;
64306   inReg = sqlite3ExprCode(pParse, pExpr, target);
64307   assert( target>0 );
64308   /* This routine is called for terms to INSERT or UPDATE.  And the only
64309   ** other place where expressions can be converted into TK_REGISTER is
64310   ** in WHERE clause processing.  So as currently implemented, there is
64311   ** no way for a TK_REGISTER to exist here.  But it seems prudent to
64312   ** keep the ALWAYS() in case the conditions above change with future
64313   ** modifications or enhancements. */
64314   if( ALWAYS(pExpr->op!=TK_REGISTER) ){  
64315     int iMem;
64316     iMem = ++pParse->nMem;
64317     sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
64318     pExpr->iTable = iMem;
64319     pExpr->op2 = pExpr->op;
64320     pExpr->op = TK_REGISTER;
64321   }
64322   return inReg;
64323 }
64324
64325 /*
64326 ** Return TRUE if pExpr is an constant expression that is appropriate
64327 ** for factoring out of a loop.  Appropriate expressions are:
64328 **
64329 **    *  Any expression that evaluates to two or more opcodes.
64330 **
64331 **    *  Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null, 
64332 **       or OP_Variable that does not need to be placed in a 
64333 **       specific register.
64334 **
64335 ** There is no point in factoring out single-instruction constant
64336 ** expressions that need to be placed in a particular register.  
64337 ** We could factor them out, but then we would end up adding an
64338 ** OP_SCopy instruction to move the value into the correct register
64339 ** later.  We might as well just use the original instruction and
64340 ** avoid the OP_SCopy.
64341 */
64342 static int isAppropriateForFactoring(Expr *p){
64343   if( !sqlite3ExprIsConstantNotJoin(p) ){
64344     return 0;  /* Only constant expressions are appropriate for factoring */
64345   }
64346   if( (p->flags & EP_FixedDest)==0 ){
64347     return 1;  /* Any constant without a fixed destination is appropriate */
64348   }
64349   while( p->op==TK_UPLUS ) p = p->pLeft;
64350   switch( p->op ){
64351 #ifndef SQLITE_OMIT_BLOB_LITERAL
64352     case TK_BLOB:
64353 #endif
64354     case TK_VARIABLE:
64355     case TK_INTEGER:
64356     case TK_FLOAT:
64357     case TK_NULL:
64358     case TK_STRING: {
64359       testcase( p->op==TK_BLOB );
64360       testcase( p->op==TK_VARIABLE );
64361       testcase( p->op==TK_INTEGER );
64362       testcase( p->op==TK_FLOAT );
64363       testcase( p->op==TK_NULL );
64364       testcase( p->op==TK_STRING );
64365       /* Single-instruction constants with a fixed destination are
64366       ** better done in-line.  If we factor them, they will just end
64367       ** up generating an OP_SCopy to move the value to the destination
64368       ** register. */
64369       return 0;
64370     }
64371     case TK_UMINUS: {
64372       if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
64373         return 0;
64374       }
64375       break;
64376     }
64377     default: {
64378       break;
64379     }
64380   }
64381   return 1;
64382 }
64383
64384 /*
64385 ** If pExpr is a constant expression that is appropriate for
64386 ** factoring out of a loop, then evaluate the expression
64387 ** into a register and convert the expression into a TK_REGISTER
64388 ** expression.
64389 */
64390 static int evalConstExpr(Walker *pWalker, Expr *pExpr){
64391   Parse *pParse = pWalker->pParse;
64392   switch( pExpr->op ){
64393     case TK_IN:
64394     case TK_REGISTER: {
64395       return WRC_Prune;
64396     }
64397     case TK_FUNCTION:
64398     case TK_AGG_FUNCTION:
64399     case TK_CONST_FUNC: {
64400       /* The arguments to a function have a fixed destination.
64401       ** Mark them this way to avoid generated unneeded OP_SCopy
64402       ** instructions. 
64403       */
64404       ExprList *pList = pExpr->x.pList;
64405       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
64406       if( pList ){
64407         int i = pList->nExpr;
64408         struct ExprList_item *pItem = pList->a;
64409         for(; i>0; i--, pItem++){
64410           if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
64411         }
64412       }
64413       break;
64414     }
64415   }
64416   if( isAppropriateForFactoring(pExpr) ){
64417     int r1 = ++pParse->nMem;
64418     int r2;
64419     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
64420     if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
64421     pExpr->op2 = pExpr->op;
64422     pExpr->op = TK_REGISTER;
64423     pExpr->iTable = r2;
64424     return WRC_Prune;
64425   }
64426   return WRC_Continue;
64427 }
64428
64429 /*
64430 ** Preevaluate constant subexpressions within pExpr and store the
64431 ** results in registers.  Modify pExpr so that the constant subexpresions
64432 ** are TK_REGISTER opcodes that refer to the precomputed values.
64433 */
64434 SQLITE_PRIVATE void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
64435   Walker w;
64436   w.xExprCallback = evalConstExpr;
64437   w.xSelectCallback = 0;
64438   w.pParse = pParse;
64439   sqlite3WalkExpr(&w, pExpr);
64440 }
64441
64442
64443 /*
64444 ** Generate code that pushes the value of every element of the given
64445 ** expression list into a sequence of registers beginning at target.
64446 **
64447 ** Return the number of elements evaluated.
64448 */
64449 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
64450   Parse *pParse,     /* Parsing context */
64451   ExprList *pList,   /* The expression list to be coded */
64452   int target,        /* Where to write results */
64453   int doHardCopy     /* Make a hard copy of every element */
64454 ){
64455   struct ExprList_item *pItem;
64456   int i, n;
64457   assert( pList!=0 );
64458   assert( target>0 );
64459   n = pList->nExpr;
64460   for(pItem=pList->a, i=0; i<n; i++, pItem++){
64461     if( pItem->iAlias ){
64462       int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i);
64463       Vdbe *v = sqlite3GetVdbe(pParse);
64464       if( iReg!=target+i ){
64465         sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
64466       }
64467     }else{
64468       sqlite3ExprCode(pParse, pItem->pExpr, target+i);
64469     }
64470     if( doHardCopy && !pParse->db->mallocFailed ){
64471       sqlite3ExprHardCopy(pParse, target, n);
64472     }
64473   }
64474   return n;
64475 }
64476
64477 /*
64478 ** Generate code for a BETWEEN operator.
64479 **
64480 **    x BETWEEN y AND z
64481 **
64482 ** The above is equivalent to 
64483 **
64484 **    x>=y AND x<=z
64485 **
64486 ** Code it as such, taking care to do the common subexpression
64487 ** elementation of x.
64488 */
64489 static void exprCodeBetween(
64490   Parse *pParse,    /* Parsing and code generating context */
64491   Expr *pExpr,      /* The BETWEEN expression */
64492   int dest,         /* Jump here if the jump is taken */
64493   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
64494   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
64495 ){
64496   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
64497   Expr compLeft;    /* The  x>=y  term */
64498   Expr compRight;   /* The  x<=z  term */
64499   Expr exprX;       /* The  x  subexpression */
64500   int regFree1 = 0; /* Temporary use register */
64501
64502   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
64503   exprX = *pExpr->pLeft;
64504   exprAnd.op = TK_AND;
64505   exprAnd.pLeft = &compLeft;
64506   exprAnd.pRight = &compRight;
64507   compLeft.op = TK_GE;
64508   compLeft.pLeft = &exprX;
64509   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
64510   compRight.op = TK_LE;
64511   compRight.pLeft = &exprX;
64512   compRight.pRight = pExpr->x.pList->a[1].pExpr;
64513   exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
64514   exprX.op = TK_REGISTER;
64515   if( jumpIfTrue ){
64516     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
64517   }else{
64518     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
64519   }
64520   sqlite3ReleaseTempReg(pParse, regFree1);
64521
64522   /* Ensure adequate test coverage */
64523   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
64524   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
64525   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
64526   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
64527   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
64528   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
64529   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
64530   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
64531 }
64532
64533 /*
64534 ** Generate code for a boolean expression such that a jump is made
64535 ** to the label "dest" if the expression is true but execution
64536 ** continues straight thru if the expression is false.
64537 **
64538 ** If the expression evaluates to NULL (neither true nor false), then
64539 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
64540 **
64541 ** This code depends on the fact that certain token values (ex: TK_EQ)
64542 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
64543 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
64544 ** the make process cause these values to align.  Assert()s in the code
64545 ** below verify that the numbers are aligned correctly.
64546 */
64547 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
64548   Vdbe *v = pParse->pVdbe;
64549   int op = 0;
64550   int regFree1 = 0;
64551   int regFree2 = 0;
64552   int r1, r2;
64553
64554   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
64555   if( NEVER(v==0) )     return;  /* Existance of VDBE checked by caller */
64556   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
64557   op = pExpr->op;
64558   switch( op ){
64559     case TK_AND: {
64560       int d2 = sqlite3VdbeMakeLabel(v);
64561       testcase( jumpIfNull==0 );
64562       sqlite3ExprCachePush(pParse);
64563       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
64564       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
64565       sqlite3VdbeResolveLabel(v, d2);
64566       sqlite3ExprCachePop(pParse, 1);
64567       break;
64568     }
64569     case TK_OR: {
64570       testcase( jumpIfNull==0 );
64571       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
64572       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
64573       break;
64574     }
64575     case TK_NOT: {
64576       testcase( jumpIfNull==0 );
64577       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
64578       break;
64579     }
64580     case TK_LT:
64581     case TK_LE:
64582     case TK_GT:
64583     case TK_GE:
64584     case TK_NE:
64585     case TK_EQ: {
64586       assert( TK_LT==OP_Lt );
64587       assert( TK_LE==OP_Le );
64588       assert( TK_GT==OP_Gt );
64589       assert( TK_GE==OP_Ge );
64590       assert( TK_EQ==OP_Eq );
64591       assert( TK_NE==OP_Ne );
64592       testcase( op==TK_LT );
64593       testcase( op==TK_LE );
64594       testcase( op==TK_GT );
64595       testcase( op==TK_GE );
64596       testcase( op==TK_EQ );
64597       testcase( op==TK_NE );
64598       testcase( jumpIfNull==0 );
64599       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
64600       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
64601       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
64602                   r1, r2, dest, jumpIfNull);
64603       testcase( regFree1==0 );
64604       testcase( regFree2==0 );
64605       break;
64606     }
64607     case TK_IS:
64608     case TK_ISNOT: {
64609       testcase( op==TK_IS );
64610       testcase( op==TK_ISNOT );
64611       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
64612       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
64613       op = (op==TK_IS) ? TK_EQ : TK_NE;
64614       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
64615                   r1, r2, dest, SQLITE_NULLEQ);
64616       testcase( regFree1==0 );
64617       testcase( regFree2==0 );
64618       break;
64619     }
64620     case TK_ISNULL:
64621     case TK_NOTNULL: {
64622       assert( TK_ISNULL==OP_IsNull );
64623       assert( TK_NOTNULL==OP_NotNull );
64624       testcase( op==TK_ISNULL );
64625       testcase( op==TK_NOTNULL );
64626       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
64627       sqlite3VdbeAddOp2(v, op, r1, dest);
64628       testcase( regFree1==0 );
64629       break;
64630     }
64631     case TK_BETWEEN: {
64632       testcase( jumpIfNull==0 );
64633       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
64634       break;
64635     }
64636     case TK_IN: {
64637       int destIfFalse = sqlite3VdbeMakeLabel(v);
64638       int destIfNull = jumpIfNull ? dest : destIfFalse;
64639       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
64640       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
64641       sqlite3VdbeResolveLabel(v, destIfFalse);
64642       break;
64643     }
64644     default: {
64645       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
64646       sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
64647       testcase( regFree1==0 );
64648       testcase( jumpIfNull==0 );
64649       break;
64650     }
64651   }
64652   sqlite3ReleaseTempReg(pParse, regFree1);
64653   sqlite3ReleaseTempReg(pParse, regFree2);  
64654 }
64655
64656 /*
64657 ** Generate code for a boolean expression such that a jump is made
64658 ** to the label "dest" if the expression is false but execution
64659 ** continues straight thru if the expression is true.
64660 **
64661 ** If the expression evaluates to NULL (neither true nor false) then
64662 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
64663 ** is 0.
64664 */
64665 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
64666   Vdbe *v = pParse->pVdbe;
64667   int op = 0;
64668   int regFree1 = 0;
64669   int regFree2 = 0;
64670   int r1, r2;
64671
64672   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
64673   if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
64674   if( pExpr==0 )    return;
64675
64676   /* The value of pExpr->op and op are related as follows:
64677   **
64678   **       pExpr->op            op
64679   **       ---------          ----------
64680   **       TK_ISNULL          OP_NotNull
64681   **       TK_NOTNULL         OP_IsNull
64682   **       TK_NE              OP_Eq
64683   **       TK_EQ              OP_Ne
64684   **       TK_GT              OP_Le
64685   **       TK_LE              OP_Gt
64686   **       TK_GE              OP_Lt
64687   **       TK_LT              OP_Ge
64688   **
64689   ** For other values of pExpr->op, op is undefined and unused.
64690   ** The value of TK_ and OP_ constants are arranged such that we
64691   ** can compute the mapping above using the following expression.
64692   ** Assert()s verify that the computation is correct.
64693   */
64694   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
64695
64696   /* Verify correct alignment of TK_ and OP_ constants
64697   */
64698   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
64699   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
64700   assert( pExpr->op!=TK_NE || op==OP_Eq );
64701   assert( pExpr->op!=TK_EQ || op==OP_Ne );
64702   assert( pExpr->op!=TK_LT || op==OP_Ge );
64703   assert( pExpr->op!=TK_LE || op==OP_Gt );
64704   assert( pExpr->op!=TK_GT || op==OP_Le );
64705   assert( pExpr->op!=TK_GE || op==OP_Lt );
64706
64707   switch( pExpr->op ){
64708     case TK_AND: {
64709       testcase( jumpIfNull==0 );
64710       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
64711       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
64712       break;
64713     }
64714     case TK_OR: {
64715       int d2 = sqlite3VdbeMakeLabel(v);
64716       testcase( jumpIfNull==0 );
64717       sqlite3ExprCachePush(pParse);
64718       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
64719       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
64720       sqlite3VdbeResolveLabel(v, d2);
64721       sqlite3ExprCachePop(pParse, 1);
64722       break;
64723     }
64724     case TK_NOT: {
64725       testcase( jumpIfNull==0 );
64726       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
64727       break;
64728     }
64729     case TK_LT:
64730     case TK_LE:
64731     case TK_GT:
64732     case TK_GE:
64733     case TK_NE:
64734     case TK_EQ: {
64735       testcase( op==TK_LT );
64736       testcase( op==TK_LE );
64737       testcase( op==TK_GT );
64738       testcase( op==TK_GE );
64739       testcase( op==TK_EQ );
64740       testcase( op==TK_NE );
64741       testcase( jumpIfNull==0 );
64742       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
64743       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
64744       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
64745                   r1, r2, dest, jumpIfNull);
64746       testcase( regFree1==0 );
64747       testcase( regFree2==0 );
64748       break;
64749     }
64750     case TK_IS:
64751     case TK_ISNOT: {
64752       testcase( pExpr->op==TK_IS );
64753       testcase( pExpr->op==TK_ISNOT );
64754       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
64755       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
64756       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
64757       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
64758                   r1, r2, dest, SQLITE_NULLEQ);
64759       testcase( regFree1==0 );
64760       testcase( regFree2==0 );
64761       break;
64762     }
64763     case TK_ISNULL:
64764     case TK_NOTNULL: {
64765       testcase( op==TK_ISNULL );
64766       testcase( op==TK_NOTNULL );
64767       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
64768       sqlite3VdbeAddOp2(v, op, r1, dest);
64769       testcase( regFree1==0 );
64770       break;
64771     }
64772     case TK_BETWEEN: {
64773       testcase( jumpIfNull==0 );
64774       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
64775       break;
64776     }
64777     case TK_IN: {
64778       if( jumpIfNull ){
64779         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
64780       }else{
64781         int destIfNull = sqlite3VdbeMakeLabel(v);
64782         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
64783         sqlite3VdbeResolveLabel(v, destIfNull);
64784       }
64785       break;
64786     }
64787     default: {
64788       r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
64789       sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
64790       testcase( regFree1==0 );
64791       testcase( jumpIfNull==0 );
64792       break;
64793     }
64794   }
64795   sqlite3ReleaseTempReg(pParse, regFree1);
64796   sqlite3ReleaseTempReg(pParse, regFree2);
64797 }
64798
64799 /*
64800 ** Do a deep comparison of two expression trees.  Return 0 if the two
64801 ** expressions are completely identical.  Return 1 if they differ only
64802 ** by a COLLATE operator at the top level.  Return 2 if there are differences
64803 ** other than the top-level COLLATE operator.
64804 **
64805 ** Sometimes this routine will return 2 even if the two expressions
64806 ** really are equivalent.  If we cannot prove that the expressions are
64807 ** identical, we return 2 just to be safe.  So if this routine
64808 ** returns 2, then you do not really know for certain if the two
64809 ** expressions are the same.  But if you get a 0 or 1 return, then you
64810 ** can be sure the expressions are the same.  In the places where
64811 ** this routine is used, it does not hurt to get an extra 2 - that
64812 ** just might result in some slightly slower code.  But returning
64813 ** an incorrect 0 or 1 could lead to a malfunction.
64814 */
64815 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB){
64816   int i;
64817   if( pA==0||pB==0 ){
64818     return pB==pA ? 0 : 2;
64819   }
64820   assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
64821   assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
64822   if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
64823     return 2;
64824   }
64825   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
64826   if( pA->op!=pB->op ) return 2;
64827   if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
64828   if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
64829
64830   if( pA->x.pList && pB->x.pList ){
64831     if( pA->x.pList->nExpr!=pB->x.pList->nExpr ) return 2;
64832     for(i=0; i<pA->x.pList->nExpr; i++){
64833       Expr *pExprA = pA->x.pList->a[i].pExpr;
64834       Expr *pExprB = pB->x.pList->a[i].pExpr;
64835       if( sqlite3ExprCompare(pExprA, pExprB) ) return 2;
64836     }
64837   }else if( pA->x.pList || pB->x.pList ){
64838     return 2;
64839   }
64840
64841   if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
64842   if( ExprHasProperty(pA, EP_IntValue) ){
64843     if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
64844       return 2;
64845     }
64846   }else if( pA->op!=TK_COLUMN && pA->u.zToken ){
64847     if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
64848     if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
64849       return 2;
64850     }
64851   }
64852   if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
64853   if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
64854   return 0;
64855 }
64856
64857
64858 /*
64859 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
64860 ** the new element.  Return a negative number if malloc fails.
64861 */
64862 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
64863   int i;
64864   pInfo->aCol = sqlite3ArrayAllocate(
64865        db,
64866        pInfo->aCol,
64867        sizeof(pInfo->aCol[0]),
64868        3,
64869        &pInfo->nColumn,
64870        &pInfo->nColumnAlloc,
64871        &i
64872   );
64873   return i;
64874 }    
64875
64876 /*
64877 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
64878 ** the new element.  Return a negative number if malloc fails.
64879 */
64880 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
64881   int i;
64882   pInfo->aFunc = sqlite3ArrayAllocate(
64883        db, 
64884        pInfo->aFunc,
64885        sizeof(pInfo->aFunc[0]),
64886        3,
64887        &pInfo->nFunc,
64888        &pInfo->nFuncAlloc,
64889        &i
64890   );
64891   return i;
64892 }    
64893
64894 /*
64895 ** This is the xExprCallback for a tree walker.  It is used to
64896 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
64897 ** for additional information.
64898 */
64899 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
64900   int i;
64901   NameContext *pNC = pWalker->u.pNC;
64902   Parse *pParse = pNC->pParse;
64903   SrcList *pSrcList = pNC->pSrcList;
64904   AggInfo *pAggInfo = pNC->pAggInfo;
64905
64906   switch( pExpr->op ){
64907     case TK_AGG_COLUMN:
64908     case TK_COLUMN: {
64909       testcase( pExpr->op==TK_AGG_COLUMN );
64910       testcase( pExpr->op==TK_COLUMN );
64911       /* Check to see if the column is in one of the tables in the FROM
64912       ** clause of the aggregate query */
64913       if( ALWAYS(pSrcList!=0) ){
64914         struct SrcList_item *pItem = pSrcList->a;
64915         for(i=0; i<pSrcList->nSrc; i++, pItem++){
64916           struct AggInfo_col *pCol;
64917           assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
64918           if( pExpr->iTable==pItem->iCursor ){
64919             /* If we reach this point, it means that pExpr refers to a table
64920             ** that is in the FROM clause of the aggregate query.  
64921             **
64922             ** Make an entry for the column in pAggInfo->aCol[] if there
64923             ** is not an entry there already.
64924             */
64925             int k;
64926             pCol = pAggInfo->aCol;
64927             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
64928               if( pCol->iTable==pExpr->iTable &&
64929                   pCol->iColumn==pExpr->iColumn ){
64930                 break;
64931               }
64932             }
64933             if( (k>=pAggInfo->nColumn)
64934              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
64935             ){
64936               pCol = &pAggInfo->aCol[k];
64937               pCol->pTab = pExpr->pTab;
64938               pCol->iTable = pExpr->iTable;
64939               pCol->iColumn = pExpr->iColumn;
64940               pCol->iMem = ++pParse->nMem;
64941               pCol->iSorterColumn = -1;
64942               pCol->pExpr = pExpr;
64943               if( pAggInfo->pGroupBy ){
64944                 int j, n;
64945                 ExprList *pGB = pAggInfo->pGroupBy;
64946                 struct ExprList_item *pTerm = pGB->a;
64947                 n = pGB->nExpr;
64948                 for(j=0; j<n; j++, pTerm++){
64949                   Expr *pE = pTerm->pExpr;
64950                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
64951                       pE->iColumn==pExpr->iColumn ){
64952                     pCol->iSorterColumn = j;
64953                     break;
64954                   }
64955                 }
64956               }
64957               if( pCol->iSorterColumn<0 ){
64958                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
64959               }
64960             }
64961             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
64962             ** because it was there before or because we just created it).
64963             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
64964             ** pAggInfo->aCol[] entry.
64965             */
64966             ExprSetIrreducible(pExpr);
64967             pExpr->pAggInfo = pAggInfo;
64968             pExpr->op = TK_AGG_COLUMN;
64969             pExpr->iAgg = (i16)k;
64970             break;
64971           } /* endif pExpr->iTable==pItem->iCursor */
64972         } /* end loop over pSrcList */
64973       }
64974       return WRC_Prune;
64975     }
64976     case TK_AGG_FUNCTION: {
64977       /* The pNC->nDepth==0 test causes aggregate functions in subqueries
64978       ** to be ignored */
64979       if( pNC->nDepth==0 ){
64980         /* Check to see if pExpr is a duplicate of another aggregate 
64981         ** function that is already in the pAggInfo structure
64982         */
64983         struct AggInfo_func *pItem = pAggInfo->aFunc;
64984         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
64985           if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
64986             break;
64987           }
64988         }
64989         if( i>=pAggInfo->nFunc ){
64990           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
64991           */
64992           u8 enc = ENC(pParse->db);
64993           i = addAggInfoFunc(pParse->db, pAggInfo);
64994           if( i>=0 ){
64995             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
64996             pItem = &pAggInfo->aFunc[i];
64997             pItem->pExpr = pExpr;
64998             pItem->iMem = ++pParse->nMem;
64999             assert( !ExprHasProperty(pExpr, EP_IntValue) );
65000             pItem->pFunc = sqlite3FindFunction(pParse->db,
65001                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
65002                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
65003             if( pExpr->flags & EP_Distinct ){
65004               pItem->iDistinct = pParse->nTab++;
65005             }else{
65006               pItem->iDistinct = -1;
65007             }
65008           }
65009         }
65010         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
65011         */
65012         assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
65013         ExprSetIrreducible(pExpr);
65014         pExpr->iAgg = (i16)i;
65015         pExpr->pAggInfo = pAggInfo;
65016         return WRC_Prune;
65017       }
65018     }
65019   }
65020   return WRC_Continue;
65021 }
65022 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
65023   NameContext *pNC = pWalker->u.pNC;
65024   if( pNC->nDepth==0 ){
65025     pNC->nDepth++;
65026     sqlite3WalkSelect(pWalker, pSelect);
65027     pNC->nDepth--;
65028     return WRC_Prune;
65029   }else{
65030     return WRC_Continue;
65031   }
65032 }
65033
65034 /*
65035 ** Analyze the given expression looking for aggregate functions and
65036 ** for variables that need to be added to the pParse->aAgg[] array.
65037 ** Make additional entries to the pParse->aAgg[] array as necessary.
65038 **
65039 ** This routine should only be called after the expression has been
65040 ** analyzed by sqlite3ResolveExprNames().
65041 */
65042 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
65043   Walker w;
65044   w.xExprCallback = analyzeAggregate;
65045   w.xSelectCallback = analyzeAggregatesInSelect;
65046   w.u.pNC = pNC;
65047   assert( pNC->pSrcList!=0 );
65048   sqlite3WalkExpr(&w, pExpr);
65049 }
65050
65051 /*
65052 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
65053 ** expression list.  Return the number of errors.
65054 **
65055 ** If an error is found, the analysis is cut short.
65056 */
65057 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
65058   struct ExprList_item *pItem;
65059   int i;
65060   if( pList ){
65061     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
65062       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
65063     }
65064   }
65065 }
65066
65067 /*
65068 ** Allocate a single new register for use to hold some intermediate result.
65069 */
65070 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
65071   if( pParse->nTempReg==0 ){
65072     return ++pParse->nMem;
65073   }
65074   return pParse->aTempReg[--pParse->nTempReg];
65075 }
65076
65077 /*
65078 ** Deallocate a register, making available for reuse for some other
65079 ** purpose.
65080 **
65081 ** If a register is currently being used by the column cache, then
65082 ** the dallocation is deferred until the column cache line that uses
65083 ** the register becomes stale.
65084 */
65085 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
65086   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
65087     int i;
65088     struct yColCache *p;
65089     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
65090       if( p->iReg==iReg ){
65091         p->tempReg = 1;
65092         return;
65093       }
65094     }
65095     pParse->aTempReg[pParse->nTempReg++] = iReg;
65096   }
65097 }
65098
65099 /*
65100 ** Allocate or deallocate a block of nReg consecutive registers
65101 */
65102 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
65103   int i, n;
65104   i = pParse->iRangeReg;
65105   n = pParse->nRangeReg;
65106   if( nReg<=n ){
65107     assert( !usedAsColumnCache(pParse, i, i+n-1) );
65108     pParse->iRangeReg += nReg;
65109     pParse->nRangeReg -= nReg;
65110   }else{
65111     i = pParse->nMem+1;
65112     pParse->nMem += nReg;
65113   }
65114   return i;
65115 }
65116 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
65117   sqlite3ExprCacheRemove(pParse, iReg, nReg);
65118   if( nReg>pParse->nRangeReg ){
65119     pParse->nRangeReg = nReg;
65120     pParse->iRangeReg = iReg;
65121   }
65122 }
65123
65124 /************** End of expr.c ************************************************/
65125 /************** Begin file alter.c *******************************************/
65126 /*
65127 ** 2005 February 15
65128 **
65129 ** The author disclaims copyright to this source code.  In place of
65130 ** a legal notice, here is a blessing:
65131 **
65132 **    May you do good and not evil.
65133 **    May you find forgiveness for yourself and forgive others.
65134 **    May you share freely, never taking more than you give.
65135 **
65136 *************************************************************************
65137 ** This file contains C code routines that used to generate VDBE code
65138 ** that implements the ALTER TABLE command.
65139 */
65140
65141 /*
65142 ** The code in this file only exists if we are not omitting the
65143 ** ALTER TABLE logic from the build.
65144 */
65145 #ifndef SQLITE_OMIT_ALTERTABLE
65146
65147
65148 /*
65149 ** This function is used by SQL generated to implement the 
65150 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
65151 ** CREATE INDEX command. The second is a table name. The table name in 
65152 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
65153 ** argument and the result returned. Examples:
65154 **
65155 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
65156 **     -> 'CREATE TABLE def(a, b, c)'
65157 **
65158 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
65159 **     -> 'CREATE INDEX i ON def(a, b, c)'
65160 */
65161 static void renameTableFunc(
65162   sqlite3_context *context,
65163   int NotUsed,
65164   sqlite3_value **argv
65165 ){
65166   unsigned char const *zSql = sqlite3_value_text(argv[0]);
65167   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
65168
65169   int token;
65170   Token tname;
65171   unsigned char const *zCsr = zSql;
65172   int len = 0;
65173   char *zRet;
65174
65175   sqlite3 *db = sqlite3_context_db_handle(context);
65176
65177   UNUSED_PARAMETER(NotUsed);
65178
65179   /* The principle used to locate the table name in the CREATE TABLE 
65180   ** statement is that the table name is the first non-space token that
65181   ** is immediately followed by a TK_LP or TK_USING token.
65182   */
65183   if( zSql ){
65184     do {
65185       if( !*zCsr ){
65186         /* Ran out of input before finding an opening bracket. Return NULL. */
65187         return;
65188       }
65189
65190       /* Store the token that zCsr points to in tname. */
65191       tname.z = (char*)zCsr;
65192       tname.n = len;
65193
65194       /* Advance zCsr to the next token. Store that token type in 'token',
65195       ** and its length in 'len' (to be used next iteration of this loop).
65196       */
65197       do {
65198         zCsr += len;
65199         len = sqlite3GetToken(zCsr, &token);
65200       } while( token==TK_SPACE );
65201       assert( len>0 );
65202     } while( token!=TK_LP && token!=TK_USING );
65203
65204     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
65205        zTableName, tname.z+tname.n);
65206     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
65207   }
65208 }
65209
65210 /*
65211 ** This C function implements an SQL user function that is used by SQL code
65212 ** generated by the ALTER TABLE ... RENAME command to modify the definition
65213 ** of any foreign key constraints that use the table being renamed as the 
65214 ** parent table. It is passed three arguments:
65215 **
65216 **   1) The complete text of the CREATE TABLE statement being modified,
65217 **   2) The old name of the table being renamed, and
65218 **   3) The new name of the table being renamed.
65219 **
65220 ** It returns the new CREATE TABLE statement. For example:
65221 **
65222 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
65223 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
65224 */
65225 #ifndef SQLITE_OMIT_FOREIGN_KEY
65226 static void renameParentFunc(
65227   sqlite3_context *context,
65228   int NotUsed,
65229   sqlite3_value **argv
65230 ){
65231   sqlite3 *db = sqlite3_context_db_handle(context);
65232   char *zOutput = 0;
65233   char *zResult;
65234   unsigned char const *zInput = sqlite3_value_text(argv[0]);
65235   unsigned char const *zOld = sqlite3_value_text(argv[1]);
65236   unsigned char const *zNew = sqlite3_value_text(argv[2]);
65237
65238   unsigned const char *z;         /* Pointer to token */
65239   int n;                          /* Length of token z */
65240   int token;                      /* Type of token */
65241
65242   UNUSED_PARAMETER(NotUsed);
65243   for(z=zInput; *z; z=z+n){
65244     n = sqlite3GetToken(z, &token);
65245     if( token==TK_REFERENCES ){
65246       char *zParent;
65247       do {
65248         z += n;
65249         n = sqlite3GetToken(z, &token);
65250       }while( token==TK_SPACE );
65251
65252       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
65253       if( zParent==0 ) break;
65254       sqlite3Dequote(zParent);
65255       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
65256         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", 
65257             (zOutput?zOutput:""), z-zInput, zInput, (const char *)zNew
65258         );
65259         sqlite3DbFree(db, zOutput);
65260         zOutput = zOut;
65261         zInput = &z[n];
65262       }
65263       sqlite3DbFree(db, zParent);
65264     }
65265   }
65266
65267   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
65268   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
65269   sqlite3DbFree(db, zOutput);
65270 }
65271 #endif
65272
65273 #ifndef SQLITE_OMIT_TRIGGER
65274 /* This function is used by SQL generated to implement the
65275 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
65276 ** statement. The second is a table name. The table name in the CREATE 
65277 ** TRIGGER statement is replaced with the third argument and the result 
65278 ** returned. This is analagous to renameTableFunc() above, except for CREATE
65279 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
65280 */
65281 static void renameTriggerFunc(
65282   sqlite3_context *context,
65283   int NotUsed,
65284   sqlite3_value **argv
65285 ){
65286   unsigned char const *zSql = sqlite3_value_text(argv[0]);
65287   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
65288
65289   int token;
65290   Token tname;
65291   int dist = 3;
65292   unsigned char const *zCsr = zSql;
65293   int len = 0;
65294   char *zRet;
65295   sqlite3 *db = sqlite3_context_db_handle(context);
65296
65297   UNUSED_PARAMETER(NotUsed);
65298
65299   /* The principle used to locate the table name in the CREATE TRIGGER 
65300   ** statement is that the table name is the first token that is immediatedly
65301   ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
65302   ** of TK_WHEN, TK_BEGIN or TK_FOR.
65303   */
65304   if( zSql ){
65305     do {
65306
65307       if( !*zCsr ){
65308         /* Ran out of input before finding the table name. Return NULL. */
65309         return;
65310       }
65311
65312       /* Store the token that zCsr points to in tname. */
65313       tname.z = (char*)zCsr;
65314       tname.n = len;
65315
65316       /* Advance zCsr to the next token. Store that token type in 'token',
65317       ** and its length in 'len' (to be used next iteration of this loop).
65318       */
65319       do {
65320         zCsr += len;
65321         len = sqlite3GetToken(zCsr, &token);
65322       }while( token==TK_SPACE );
65323       assert( len>0 );
65324
65325       /* Variable 'dist' stores the number of tokens read since the most
65326       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
65327       ** token is read and 'dist' equals 2, the condition stated above
65328       ** to be met.
65329       **
65330       ** Note that ON cannot be a database, table or column name, so
65331       ** there is no need to worry about syntax like 
65332       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
65333       */
65334       dist++;
65335       if( token==TK_DOT || token==TK_ON ){
65336         dist = 0;
65337       }
65338     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
65339
65340     /* Variable tname now contains the token that is the old table-name
65341     ** in the CREATE TRIGGER statement.
65342     */
65343     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", ((u8*)tname.z) - zSql, zSql, 
65344        zTableName, tname.z+tname.n);
65345     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
65346   }
65347 }
65348 #endif   /* !SQLITE_OMIT_TRIGGER */
65349
65350 /*
65351 ** Register built-in functions used to help implement ALTER TABLE
65352 */
65353 SQLITE_PRIVATE void sqlite3AlterFunctions(sqlite3 *db){
65354   sqlite3CreateFunc(db, "sqlite_rename_table", 2, SQLITE_UTF8, 0,
65355                          renameTableFunc, 0, 0);
65356 #ifndef SQLITE_OMIT_TRIGGER
65357   sqlite3CreateFunc(db, "sqlite_rename_trigger", 2, SQLITE_UTF8, 0,
65358                          renameTriggerFunc, 0, 0);
65359 #endif
65360 #ifndef SQLITE_OMIT_FOREIGN_KEY
65361   sqlite3CreateFunc(db, "sqlite_rename_parent", 3, SQLITE_UTF8, 0,
65362                          renameParentFunc, 0, 0);
65363 #endif
65364 }
65365
65366 /*
65367 ** This function is used to create the text of expressions of the form:
65368 **
65369 **   name=<constant1> OR name=<constant2> OR ...
65370 **
65371 ** If argument zWhere is NULL, then a pointer string containing the text 
65372 ** "name=<constant>" is returned, where <constant> is the quoted version
65373 ** of the string passed as argument zConstant. The returned buffer is
65374 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
65375 ** caller to ensure that it is eventually freed.
65376 **
65377 ** If argument zWhere is not NULL, then the string returned is 
65378 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
65379 ** In this case zWhere is passed to sqlite3DbFree() before returning.
65380 ** 
65381 */
65382 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
65383   char *zNew;
65384   if( !zWhere ){
65385     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
65386   }else{
65387     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
65388     sqlite3DbFree(db, zWhere);
65389   }
65390   return zNew;
65391 }
65392
65393 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
65394 /*
65395 ** Generate the text of a WHERE expression which can be used to select all
65396 ** tables that have foreign key constraints that refer to table pTab (i.e.
65397 ** constraints for which pTab is the parent table) from the sqlite_master
65398 ** table.
65399 */
65400 static char *whereForeignKeys(Parse *pParse, Table *pTab){
65401   FKey *p;
65402   char *zWhere = 0;
65403   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
65404     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
65405   }
65406   return zWhere;
65407 }
65408 #endif
65409
65410 /*
65411 ** Generate the text of a WHERE expression which can be used to select all
65412 ** temporary triggers on table pTab from the sqlite_temp_master table. If
65413 ** table pTab has no temporary triggers, or is itself stored in the 
65414 ** temporary database, NULL is returned.
65415 */
65416 static char *whereTempTriggers(Parse *pParse, Table *pTab){
65417   Trigger *pTrig;
65418   char *zWhere = 0;
65419   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
65420
65421   /* If the table is not located in the temp-db (in which case NULL is 
65422   ** returned, loop through the tables list of triggers. For each trigger
65423   ** that is not part of the temp-db schema, add a clause to the WHERE 
65424   ** expression being built up in zWhere.
65425   */
65426   if( pTab->pSchema!=pTempSchema ){
65427     sqlite3 *db = pParse->db;
65428     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
65429       if( pTrig->pSchema==pTempSchema ){
65430         zWhere = whereOrName(db, zWhere, pTrig->zName);
65431       }
65432     }
65433   }
65434   return zWhere;
65435 }
65436
65437 /*
65438 ** Generate code to drop and reload the internal representation of table
65439 ** pTab from the database, including triggers and temporary triggers.
65440 ** Argument zName is the name of the table in the database schema at
65441 ** the time the generated code is executed. This can be different from
65442 ** pTab->zName if this function is being called to code part of an 
65443 ** "ALTER TABLE RENAME TO" statement.
65444 */
65445 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
65446   Vdbe *v;
65447   char *zWhere;
65448   int iDb;                   /* Index of database containing pTab */
65449 #ifndef SQLITE_OMIT_TRIGGER
65450   Trigger *pTrig;
65451 #endif
65452
65453   v = sqlite3GetVdbe(pParse);
65454   if( NEVER(v==0) ) return;
65455   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
65456   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
65457   assert( iDb>=0 );
65458
65459 #ifndef SQLITE_OMIT_TRIGGER
65460   /* Drop any table triggers from the internal schema. */
65461   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
65462     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
65463     assert( iTrigDb==iDb || iTrigDb==1 );
65464     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
65465   }
65466 #endif
65467
65468   /* Drop the table and index from the internal schema.  */
65469   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
65470
65471   /* Reload the table, index and permanent trigger schemas. */
65472   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
65473   if( !zWhere ) return;
65474   sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC);
65475
65476 #ifndef SQLITE_OMIT_TRIGGER
65477   /* Now, if the table is not stored in the temp database, reload any temp 
65478   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
65479   */
65480   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
65481     sqlite3VdbeAddOp4(v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC);
65482   }
65483 #endif
65484 }
65485
65486 /*
65487 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
65488 ** command. 
65489 */
65490 SQLITE_PRIVATE void sqlite3AlterRenameTable(
65491   Parse *pParse,            /* Parser context. */
65492   SrcList *pSrc,            /* The table to rename. */
65493   Token *pName              /* The new table name. */
65494 ){
65495   int iDb;                  /* Database that contains the table */
65496   char *zDb;                /* Name of database iDb */
65497   Table *pTab;              /* Table being renamed */
65498   char *zName = 0;          /* NULL-terminated version of pName */ 
65499   sqlite3 *db = pParse->db; /* Database connection */
65500   int nTabName;             /* Number of UTF-8 characters in zTabName */
65501   const char *zTabName;     /* Original name of the table */
65502   Vdbe *v;
65503 #ifndef SQLITE_OMIT_TRIGGER
65504   char *zWhere = 0;         /* Where clause to locate temp triggers */
65505 #endif
65506   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
65507   
65508   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
65509   assert( pSrc->nSrc==1 );
65510   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
65511
65512   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
65513   if( !pTab ) goto exit_rename_table;
65514   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
65515   zDb = db->aDb[iDb].zName;
65516
65517   /* Get a NULL terminated version of the new table name. */
65518   zName = sqlite3NameFromToken(db, pName);
65519   if( !zName ) goto exit_rename_table;
65520
65521   /* Check that a table or index named 'zName' does not already exist
65522   ** in database iDb. If so, this is an error.
65523   */
65524   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
65525     sqlite3ErrorMsg(pParse, 
65526         "there is already another table or index with this name: %s", zName);
65527     goto exit_rename_table;
65528   }
65529
65530   /* Make sure it is not a system table being altered, or a reserved name
65531   ** that the table is being renamed to.
65532   */
65533   if( sqlite3Strlen30(pTab->zName)>6 
65534    && 0==sqlite3StrNICmp(pTab->zName, "sqlite_", 7)
65535   ){
65536     sqlite3ErrorMsg(pParse, "table %s may not be altered", pTab->zName);
65537     goto exit_rename_table;
65538   }
65539   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
65540     goto exit_rename_table;
65541   }
65542
65543 #ifndef SQLITE_OMIT_VIEW
65544   if( pTab->pSelect ){
65545     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
65546     goto exit_rename_table;
65547   }
65548 #endif
65549
65550 #ifndef SQLITE_OMIT_AUTHORIZATION
65551   /* Invoke the authorization callback. */
65552   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
65553     goto exit_rename_table;
65554   }
65555 #endif
65556
65557 #ifndef SQLITE_OMIT_VIRTUALTABLE
65558   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
65559     goto exit_rename_table;
65560   }
65561   if( IsVirtual(pTab) ){
65562     pVTab = sqlite3GetVTable(db, pTab);
65563     if( pVTab->pVtab->pModule->xRename==0 ){
65564       pVTab = 0;
65565     }
65566   }
65567 #endif
65568
65569   /* Begin a transaction and code the VerifyCookie for database iDb. 
65570   ** Then modify the schema cookie (since the ALTER TABLE modifies the
65571   ** schema). Open a statement transaction if the table is a virtual
65572   ** table.
65573   */
65574   v = sqlite3GetVdbe(pParse);
65575   if( v==0 ){
65576     goto exit_rename_table;
65577   }
65578   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
65579   sqlite3ChangeCookie(pParse, iDb);
65580
65581   /* If this is a virtual table, invoke the xRename() function if
65582   ** one is defined. The xRename() callback will modify the names
65583   ** of any resources used by the v-table implementation (including other
65584   ** SQLite tables) that are identified by the name of the virtual table.
65585   */
65586 #ifndef SQLITE_OMIT_VIRTUALTABLE
65587   if( pVTab ){
65588     int i = ++pParse->nMem;
65589     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
65590     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
65591     sqlite3MayAbort(pParse);
65592   }
65593 #endif
65594
65595   /* figure out how many UTF-8 characters are in zName */
65596   zTabName = pTab->zName;
65597   nTabName = sqlite3Utf8CharLen(zTabName, -1);
65598
65599 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
65600   if( db->flags&SQLITE_ForeignKeys ){
65601     /* If foreign-key support is enabled, rewrite the CREATE TABLE 
65602     ** statements corresponding to all child tables of foreign key constraints
65603     ** for which the renamed table is the parent table.  */
65604     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
65605       sqlite3NestedParse(pParse, 
65606           "UPDATE \"%w\".%s SET "
65607               "sql = sqlite_rename_parent(sql, %Q, %Q) "
65608               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
65609       sqlite3DbFree(db, zWhere);
65610     }
65611   }
65612 #endif
65613
65614   /* Modify the sqlite_master table to use the new table name. */
65615   sqlite3NestedParse(pParse,
65616       "UPDATE %Q.%s SET "
65617 #ifdef SQLITE_OMIT_TRIGGER
65618           "sql = sqlite_rename_table(sql, %Q), "
65619 #else
65620           "sql = CASE "
65621             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
65622             "ELSE sqlite_rename_table(sql, %Q) END, "
65623 #endif
65624           "tbl_name = %Q, "
65625           "name = CASE "
65626             "WHEN type='table' THEN %Q "
65627             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
65628              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
65629             "ELSE name END "
65630       "WHERE tbl_name=%Q AND "
65631           "(type='table' OR type='index' OR type='trigger');", 
65632       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
65633 #ifndef SQLITE_OMIT_TRIGGER
65634       zName,
65635 #endif
65636       zName, nTabName, zTabName
65637   );
65638
65639 #ifndef SQLITE_OMIT_AUTOINCREMENT
65640   /* If the sqlite_sequence table exists in this database, then update 
65641   ** it with the new table name.
65642   */
65643   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
65644     sqlite3NestedParse(pParse,
65645         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
65646         zDb, zName, pTab->zName);
65647   }
65648 #endif
65649
65650 #ifndef SQLITE_OMIT_TRIGGER
65651   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
65652   ** table. Don't do this if the table being ALTERed is itself located in
65653   ** the temp database.
65654   */
65655   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
65656     sqlite3NestedParse(pParse, 
65657         "UPDATE sqlite_temp_master SET "
65658             "sql = sqlite_rename_trigger(sql, %Q), "
65659             "tbl_name = %Q "
65660             "WHERE %s;", zName, zName, zWhere);
65661     sqlite3DbFree(db, zWhere);
65662   }
65663 #endif
65664
65665 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
65666   if( db->flags&SQLITE_ForeignKeys ){
65667     FKey *p;
65668     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
65669       Table *pFrom = p->pFrom;
65670       if( pFrom!=pTab ){
65671         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
65672       }
65673     }
65674   }
65675 #endif
65676
65677   /* Drop and reload the internal table schema. */
65678   reloadTableSchema(pParse, pTab, zName);
65679
65680 exit_rename_table:
65681   sqlite3SrcListDelete(db, pSrc);
65682   sqlite3DbFree(db, zName);
65683 }
65684
65685
65686 /*
65687 ** Generate code to make sure the file format number is at least minFormat.
65688 ** The generated code will increase the file format number if necessary.
65689 */
65690 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
65691   Vdbe *v;
65692   v = sqlite3GetVdbe(pParse);
65693   /* The VDBE should have been allocated before this routine is called.
65694   ** If that allocation failed, we would have quit before reaching this
65695   ** point */
65696   if( ALWAYS(v) ){
65697     int r1 = sqlite3GetTempReg(pParse);
65698     int r2 = sqlite3GetTempReg(pParse);
65699     int j1;
65700     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
65701     sqlite3VdbeUsesBtree(v, iDb);
65702     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
65703     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
65704     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
65705     sqlite3VdbeJumpHere(v, j1);
65706     sqlite3ReleaseTempReg(pParse, r1);
65707     sqlite3ReleaseTempReg(pParse, r2);
65708   }
65709 }
65710
65711 /*
65712 ** This function is called after an "ALTER TABLE ... ADD" statement
65713 ** has been parsed. Argument pColDef contains the text of the new
65714 ** column definition.
65715 **
65716 ** The Table structure pParse->pNewTable was extended to include
65717 ** the new column during parsing.
65718 */
65719 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
65720   Table *pNew;              /* Copy of pParse->pNewTable */
65721   Table *pTab;              /* Table being altered */
65722   int iDb;                  /* Database number */
65723   const char *zDb;          /* Database name */
65724   const char *zTab;         /* Table name */
65725   char *zCol;               /* Null-terminated column definition */
65726   Column *pCol;             /* The new column */
65727   Expr *pDflt;              /* Default value for the new column */
65728   sqlite3 *db;              /* The database connection; */
65729
65730   db = pParse->db;
65731   if( pParse->nErr || db->mallocFailed ) return;
65732   pNew = pParse->pNewTable;
65733   assert( pNew );
65734
65735   assert( sqlite3BtreeHoldsAllMutexes(db) );
65736   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
65737   zDb = db->aDb[iDb].zName;
65738   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
65739   pCol = &pNew->aCol[pNew->nCol-1];
65740   pDflt = pCol->pDflt;
65741   pTab = sqlite3FindTable(db, zTab, zDb);
65742   assert( pTab );
65743
65744 #ifndef SQLITE_OMIT_AUTHORIZATION
65745   /* Invoke the authorization callback. */
65746   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
65747     return;
65748   }
65749 #endif
65750
65751   /* If the default value for the new column was specified with a 
65752   ** literal NULL, then set pDflt to 0. This simplifies checking
65753   ** for an SQL NULL default below.
65754   */
65755   if( pDflt && pDflt->op==TK_NULL ){
65756     pDflt = 0;
65757   }
65758
65759   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
65760   ** If there is a NOT NULL constraint, then the default value for the
65761   ** column must not be NULL.
65762   */
65763   if( pCol->isPrimKey ){
65764     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
65765     return;
65766   }
65767   if( pNew->pIndex ){
65768     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
65769     return;
65770   }
65771   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
65772     sqlite3ErrorMsg(pParse, 
65773         "Cannot add a REFERENCES column with non-NULL default value");
65774     return;
65775   }
65776   if( pCol->notNull && !pDflt ){
65777     sqlite3ErrorMsg(pParse, 
65778         "Cannot add a NOT NULL column with default value NULL");
65779     return;
65780   }
65781
65782   /* Ensure the default expression is something that sqlite3ValueFromExpr()
65783   ** can handle (i.e. not CURRENT_TIME etc.)
65784   */
65785   if( pDflt ){
65786     sqlite3_value *pVal;
65787     if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
65788       db->mallocFailed = 1;
65789       return;
65790     }
65791     if( !pVal ){
65792       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
65793       return;
65794     }
65795     sqlite3ValueFree(pVal);
65796   }
65797
65798   /* Modify the CREATE TABLE statement. */
65799   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
65800   if( zCol ){
65801     char *zEnd = &zCol[pColDef->n-1];
65802     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
65803       *zEnd-- = '\0';
65804     }
65805     sqlite3NestedParse(pParse, 
65806         "UPDATE \"%w\".%s SET "
65807           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
65808         "WHERE type = 'table' AND name = %Q", 
65809       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
65810       zTab
65811     );
65812     sqlite3DbFree(db, zCol);
65813   }
65814
65815   /* If the default value of the new column is NULL, then set the file
65816   ** format to 2. If the default value of the new column is not NULL,
65817   ** the file format becomes 3.
65818   */
65819   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
65820
65821   /* Reload the schema of the modified table. */
65822   reloadTableSchema(pParse, pTab, pTab->zName);
65823 }
65824
65825 /*
65826 ** This function is called by the parser after the table-name in
65827 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
65828 ** pSrc is the full-name of the table being altered.
65829 **
65830 ** This routine makes a (partial) copy of the Table structure
65831 ** for the table being altered and sets Parse.pNewTable to point
65832 ** to it. Routines called by the parser as the column definition
65833 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
65834 ** the copy. The copy of the Table structure is deleted by tokenize.c 
65835 ** after parsing is finished.
65836 **
65837 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
65838 ** coding the "ALTER TABLE ... ADD" statement.
65839 */
65840 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
65841   Table *pNew;
65842   Table *pTab;
65843   Vdbe *v;
65844   int iDb;
65845   int i;
65846   int nAlloc;
65847   sqlite3 *db = pParse->db;
65848
65849   /* Look up the table being altered. */
65850   assert( pParse->pNewTable==0 );
65851   assert( sqlite3BtreeHoldsAllMutexes(db) );
65852   if( db->mallocFailed ) goto exit_begin_add_column;
65853   pTab = sqlite3LocateTable(pParse, 0, pSrc->a[0].zName, pSrc->a[0].zDatabase);
65854   if( !pTab ) goto exit_begin_add_column;
65855
65856 #ifndef SQLITE_OMIT_VIRTUALTABLE
65857   if( IsVirtual(pTab) ){
65858     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
65859     goto exit_begin_add_column;
65860   }
65861 #endif
65862
65863   /* Make sure this is not an attempt to ALTER a view. */
65864   if( pTab->pSelect ){
65865     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
65866     goto exit_begin_add_column;
65867   }
65868
65869   assert( pTab->addColOffset>0 );
65870   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
65871
65872   /* Put a copy of the Table struct in Parse.pNewTable for the
65873   ** sqlite3AddColumn() function and friends to modify.  But modify
65874   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
65875   ** prefix, we insure that the name will not collide with an existing
65876   ** table because user table are not allowed to have the "sqlite_"
65877   ** prefix on their name.
65878   */
65879   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
65880   if( !pNew ) goto exit_begin_add_column;
65881   pParse->pNewTable = pNew;
65882   pNew->nRef = 1;
65883   pNew->dbMem = pTab->dbMem;
65884   pNew->nCol = pTab->nCol;
65885   assert( pNew->nCol>0 );
65886   nAlloc = (((pNew->nCol-1)/8)*8)+8;
65887   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
65888   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
65889   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
65890   if( !pNew->aCol || !pNew->zName ){
65891     db->mallocFailed = 1;
65892     goto exit_begin_add_column;
65893   }
65894   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
65895   for(i=0; i<pNew->nCol; i++){
65896     Column *pCol = &pNew->aCol[i];
65897     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
65898     pCol->zColl = 0;
65899     pCol->zType = 0;
65900     pCol->pDflt = 0;
65901     pCol->zDflt = 0;
65902   }
65903   pNew->pSchema = db->aDb[iDb].pSchema;
65904   pNew->addColOffset = pTab->addColOffset;
65905   pNew->nRef = 1;
65906
65907   /* Begin a transaction and increment the schema cookie.  */
65908   sqlite3BeginWriteOperation(pParse, 0, iDb);
65909   v = sqlite3GetVdbe(pParse);
65910   if( !v ) goto exit_begin_add_column;
65911   sqlite3ChangeCookie(pParse, iDb);
65912
65913 exit_begin_add_column:
65914   sqlite3SrcListDelete(db, pSrc);
65915   return;
65916 }
65917 #endif  /* SQLITE_ALTER_TABLE */
65918
65919 /************** End of alter.c ***********************************************/
65920 /************** Begin file analyze.c *****************************************/
65921 /*
65922 ** 2005 July 8
65923 **
65924 ** The author disclaims copyright to this source code.  In place of
65925 ** a legal notice, here is a blessing:
65926 **
65927 **    May you do good and not evil.
65928 **    May you find forgiveness for yourself and forgive others.
65929 **    May you share freely, never taking more than you give.
65930 **
65931 *************************************************************************
65932 ** This file contains code associated with the ANALYZE command.
65933 */
65934 #ifndef SQLITE_OMIT_ANALYZE
65935
65936 /*
65937 ** This routine generates code that opens the sqlite_stat1 table for
65938 ** writing with cursor iStatCur. If the library was built with the
65939 ** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
65940 ** opened for writing using cursor (iStatCur+1)
65941 **
65942 ** If the sqlite_stat1 tables does not previously exist, it is created.
65943 ** Similarly, if the sqlite_stat2 table does not exist and the library
65944 ** is compiled with SQLITE_ENABLE_STAT2 defined, it is created. 
65945 **
65946 ** Argument zWhere may be a pointer to a buffer containing a table name,
65947 ** or it may be a NULL pointer. If it is not NULL, then all entries in
65948 ** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
65949 ** with the named table are deleted. If zWhere==0, then code is generated
65950 ** to delete all stat table entries.
65951 */
65952 static void openStatTable(
65953   Parse *pParse,          /* Parsing context */
65954   int iDb,                /* The database we are looking in */
65955   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
65956   const char *zWhere      /* Delete entries associated with this table */
65957 ){
65958   static struct {
65959     const char *zName;
65960     const char *zCols;
65961   } aTable[] = {
65962     { "sqlite_stat1", "tbl,idx,stat" },
65963 #ifdef SQLITE_ENABLE_STAT2
65964     { "sqlite_stat2", "tbl,idx,sampleno,sample" },
65965 #endif
65966   };
65967
65968   int aRoot[] = {0, 0};
65969   u8 aCreateTbl[] = {0, 0};
65970
65971   int i;
65972   sqlite3 *db = pParse->db;
65973   Db *pDb;
65974   Vdbe *v = sqlite3GetVdbe(pParse);
65975   if( v==0 ) return;
65976   assert( sqlite3BtreeHoldsAllMutexes(db) );
65977   assert( sqlite3VdbeDb(v)==db );
65978   pDb = &db->aDb[iDb];
65979
65980   for(i=0; i<ArraySize(aTable); i++){
65981     const char *zTab = aTable[i].zName;
65982     Table *pStat;
65983     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
65984       /* The sqlite_stat[12] table does not exist. Create it. Note that a 
65985       ** side-effect of the CREATE TABLE statement is to leave the rootpage 
65986       ** of the new table in register pParse->regRoot. This is important 
65987       ** because the OpenWrite opcode below will be needing it. */
65988       sqlite3NestedParse(pParse,
65989           "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
65990       );
65991       aRoot[i] = pParse->regRoot;
65992       aCreateTbl[i] = 1;
65993     }else{
65994       /* The table already exists. If zWhere is not NULL, delete all entries 
65995       ** associated with the table zWhere. If zWhere is NULL, delete the
65996       ** entire contents of the table. */
65997       aRoot[i] = pStat->tnum;
65998       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
65999       if( zWhere ){
66000         sqlite3NestedParse(pParse,
66001            "DELETE FROM %Q.%s WHERE tbl=%Q", pDb->zName, zTab, zWhere
66002         );
66003       }else{
66004         /* The sqlite_stat[12] table already exists.  Delete all rows. */
66005         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
66006       }
66007     }
66008   }
66009
66010   /* Open the sqlite_stat[12] tables for writing. */
66011   for(i=0; i<ArraySize(aTable); i++){
66012     sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
66013     sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
66014     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
66015   }
66016 }
66017
66018 /*
66019 ** Generate code to do an analysis of all indices associated with
66020 ** a single table.
66021 */
66022 static void analyzeOneTable(
66023   Parse *pParse,   /* Parser context */
66024   Table *pTab,     /* Table whose indices are to be analyzed */
66025   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
66026   int iMem         /* Available memory locations begin here */
66027 ){
66028   sqlite3 *db = pParse->db;    /* Database handle */
66029   Index *pIdx;                 /* An index to being analyzed */
66030   int iIdxCur;                 /* Cursor open on index being analyzed */
66031   Vdbe *v;                     /* The virtual machine being built up */
66032   int i;                       /* Loop counter */
66033   int topOfLoop;               /* The top of the loop */
66034   int endOfLoop;               /* The end of the loop */
66035   int addr;                    /* The address of an instruction */
66036   int iDb;                     /* Index of database containing pTab */
66037   int regTabname = iMem++;     /* Register containing table name */
66038   int regIdxname = iMem++;     /* Register containing index name */
66039   int regSampleno = iMem++;    /* Register containing next sample number */
66040   int regCol = iMem++;         /* Content of a column analyzed table */
66041   int regRec = iMem++;         /* Register holding completed record */
66042   int regTemp = iMem++;        /* Temporary use register */
66043   int regRowid = iMem++;       /* Rowid for the inserted record */
66044
66045 #ifdef SQLITE_ENABLE_STAT2
66046   int regTemp2 = iMem++;       /* Temporary use register */
66047   int regSamplerecno = iMem++; /* Index of next sample to record */
66048   int regRecno = iMem++;       /* Current sample index */
66049   int regLast = iMem++;        /* Index of last sample to record */
66050   int regFirst = iMem++;       /* Index of first sample to record */
66051 #endif
66052
66053   v = sqlite3GetVdbe(pParse);
66054   if( v==0 || NEVER(pTab==0) || pTab->pIndex==0 ){
66055     /* Do no analysis for tables that have no indices */
66056     return;
66057   }
66058   assert( sqlite3BtreeHoldsAllMutexes(db) );
66059   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
66060   assert( iDb>=0 );
66061 #ifndef SQLITE_OMIT_AUTHORIZATION
66062   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
66063       db->aDb[iDb].zName ) ){
66064     return;
66065   }
66066 #endif
66067
66068   /* Establish a read-lock on the table at the shared-cache level. */
66069   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
66070
66071   iIdxCur = pParse->nTab++;
66072   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
66073     int nCol = pIdx->nColumn;
66074     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
66075
66076     if( iMem+1+(nCol*2)>pParse->nMem ){
66077       pParse->nMem = iMem+1+(nCol*2);
66078     }
66079
66080     /* Open a cursor to the index to be analyzed. */
66081     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
66082     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
66083         (char *)pKey, P4_KEYINFO_HANDOFF);
66084     VdbeComment((v, "%s", pIdx->zName));
66085
66086     /* Populate the registers containing the table and index names. */
66087     if( pTab->pIndex==pIdx ){
66088       sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
66089     }
66090     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
66091
66092 #ifdef SQLITE_ENABLE_STAT2
66093
66094     /* If this iteration of the loop is generating code to analyze the
66095     ** first index in the pTab->pIndex list, then register regLast has
66096     ** not been populated. In this case populate it now.  */
66097     if( pTab->pIndex==pIdx ){
66098       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regSamplerecno);
66099       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2-1, regTemp);
66100       sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES*2, regTemp2);
66101
66102       sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regLast);
66103       sqlite3VdbeAddOp2(v, OP_Null, 0, regFirst);
66104       addr = sqlite3VdbeAddOp3(v, OP_Lt, regSamplerecno, 0, regLast);
66105       sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regLast, regFirst);
66106       sqlite3VdbeAddOp3(v, OP_Multiply, regLast, regTemp, regLast);
66107       sqlite3VdbeAddOp2(v, OP_AddImm, regLast, SQLITE_INDEX_SAMPLES*2-2);
66108       sqlite3VdbeAddOp3(v, OP_Divide,  regTemp2, regLast, regLast);
66109       sqlite3VdbeJumpHere(v, addr);
66110     }
66111
66112     /* Zero the regSampleno and regRecno registers. */
66113     sqlite3VdbeAddOp2(v, OP_Integer, 0, regSampleno);
66114     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRecno);
66115     sqlite3VdbeAddOp2(v, OP_Copy, regFirst, regSamplerecno);
66116 #endif
66117
66118     /* The block of memory cells initialized here is used as follows.
66119     **
66120     **    iMem:                
66121     **        The total number of rows in the table.
66122     **
66123     **    iMem+1 .. iMem+nCol: 
66124     **        Number of distinct entries in index considering the 
66125     **        left-most N columns only, where N is between 1 and nCol, 
66126     **        inclusive.
66127     **
66128     **    iMem+nCol+1 .. Mem+2*nCol:  
66129     **        Previous value of indexed columns, from left to right.
66130     **
66131     ** Cells iMem through iMem+nCol are initialized to 0. The others are 
66132     ** initialized to contain an SQL NULL.
66133     */
66134     for(i=0; i<=nCol; i++){
66135       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
66136     }
66137     for(i=0; i<nCol; i++){
66138       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
66139     }
66140
66141     /* Start the analysis loop. This loop runs through all the entries in
66142     ** the index b-tree.  */
66143     endOfLoop = sqlite3VdbeMakeLabel(v);
66144     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
66145     topOfLoop = sqlite3VdbeCurrentAddr(v);
66146     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
66147
66148     for(i=0; i<nCol; i++){
66149       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
66150 #ifdef SQLITE_ENABLE_STAT2
66151       if( i==0 ){
66152         /* Check if the record that cursor iIdxCur points to contains a
66153         ** value that should be stored in the sqlite_stat2 table. If so,
66154         ** store it.  */
66155         int ne = sqlite3VdbeAddOp3(v, OP_Ne, regRecno, 0, regSamplerecno);
66156         assert( regTabname+1==regIdxname 
66157              && regTabname+2==regSampleno
66158              && regTabname+3==regCol
66159         );
66160         sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
66161         sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 4, regRec, "aaab", 0);
66162         sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regRowid);
66163         sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regRec, regRowid);
66164
66165         /* Calculate new values for regSamplerecno and regSampleno.
66166         **
66167         **   sampleno = sampleno + 1
66168         **   samplerecno = samplerecno+(remaining records)/(remaining samples)
66169         */
66170         sqlite3VdbeAddOp2(v, OP_AddImm, regSampleno, 1);
66171         sqlite3VdbeAddOp3(v, OP_Subtract, regRecno, regLast, regTemp);
66172         sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
66173         sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_INDEX_SAMPLES, regTemp2);
66174         sqlite3VdbeAddOp3(v, OP_Subtract, regSampleno, regTemp2, regTemp2);
66175         sqlite3VdbeAddOp3(v, OP_Divide, regTemp2, regTemp, regTemp);
66176         sqlite3VdbeAddOp3(v, OP_Add, regSamplerecno, regTemp, regSamplerecno);
66177
66178         sqlite3VdbeJumpHere(v, ne);
66179         sqlite3VdbeAddOp2(v, OP_AddImm, regRecno, 1);
66180       }
66181 #endif
66182
66183       sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
66184       /**** TODO:  add collating sequence *****/
66185       sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
66186     }
66187     if( db->mallocFailed ){
66188       /* If a malloc failure has occurred, then the result of the expression 
66189       ** passed as the second argument to the call to sqlite3VdbeJumpHere() 
66190       ** below may be negative. Which causes an assert() to fail (or an
66191       ** out-of-bounds write if SQLITE_DEBUG is not defined).  */
66192       return;
66193     }
66194     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
66195     for(i=0; i<nCol; i++){
66196       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-(nCol*2));
66197       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
66198       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
66199     }
66200
66201     /* End of the analysis loop. */
66202     sqlite3VdbeResolveLabel(v, endOfLoop);
66203     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
66204     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
66205
66206     /* Store the results in sqlite_stat1.
66207     **
66208     ** The result is a single row of the sqlite_stat1 table.  The first
66209     ** two columns are the names of the table and index.  The third column
66210     ** is a string composed of a list of integer statistics about the
66211     ** index.  The first integer in the list is the total number of entries
66212     ** in the index.  There is one additional integer in the list for each
66213     ** column of the table.  This additional integer is a guess of how many
66214     ** rows of the table the index will select.  If D is the count of distinct
66215     ** values and K is the total number of rows, then the integer is computed
66216     ** as:
66217     **
66218     **        I = (K+D-1)/D
66219     **
66220     ** If K==0 then no entry is made into the sqlite_stat1 table.  
66221     ** If K>0 then it is always the case the D>0 so division by zero
66222     ** is never possible.
66223     */
66224     addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
66225     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
66226     for(i=0; i<nCol; i++){
66227       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
66228       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
66229       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
66230       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
66231       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
66232       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
66233       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
66234     }
66235     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
66236     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
66237     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
66238     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
66239     sqlite3VdbeJumpHere(v, addr);
66240   }
66241 }
66242
66243 /*
66244 ** Generate code that will cause the most recent index analysis to
66245 ** be laoded into internal hash tables where is can be used.
66246 */
66247 static void loadAnalysis(Parse *pParse, int iDb){
66248   Vdbe *v = sqlite3GetVdbe(pParse);
66249   if( v ){
66250     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
66251   }
66252 }
66253
66254 /*
66255 ** Generate code that will do an analysis of an entire database
66256 */
66257 static void analyzeDatabase(Parse *pParse, int iDb){
66258   sqlite3 *db = pParse->db;
66259   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
66260   HashElem *k;
66261   int iStatCur;
66262   int iMem;
66263
66264   sqlite3BeginWriteOperation(pParse, 0, iDb);
66265   iStatCur = pParse->nTab;
66266   pParse->nTab += 2;
66267   openStatTable(pParse, iDb, iStatCur, 0);
66268   iMem = pParse->nMem+1;
66269   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
66270     Table *pTab = (Table*)sqliteHashData(k);
66271     analyzeOneTable(pParse, pTab, iStatCur, iMem);
66272   }
66273   loadAnalysis(pParse, iDb);
66274 }
66275
66276 /*
66277 ** Generate code that will do an analysis of a single table in
66278 ** a database.
66279 */
66280 static void analyzeTable(Parse *pParse, Table *pTab){
66281   int iDb;
66282   int iStatCur;
66283
66284   assert( pTab!=0 );
66285   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
66286   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
66287   sqlite3BeginWriteOperation(pParse, 0, iDb);
66288   iStatCur = pParse->nTab;
66289   pParse->nTab += 2;
66290   openStatTable(pParse, iDb, iStatCur, pTab->zName);
66291   analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
66292   loadAnalysis(pParse, iDb);
66293 }
66294
66295 /*
66296 ** Generate code for the ANALYZE command.  The parser calls this routine
66297 ** when it recognizes an ANALYZE command.
66298 **
66299 **        ANALYZE                            -- 1
66300 **        ANALYZE  <database>                -- 2
66301 **        ANALYZE  ?<database>.?<tablename>  -- 3
66302 **
66303 ** Form 1 causes all indices in all attached databases to be analyzed.
66304 ** Form 2 analyzes all indices the single database named.
66305 ** Form 3 analyzes all indices associated with the named table.
66306 */
66307 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
66308   sqlite3 *db = pParse->db;
66309   int iDb;
66310   int i;
66311   char *z, *zDb;
66312   Table *pTab;
66313   Token *pTableName;
66314
66315   /* Read the database schema. If an error occurs, leave an error message
66316   ** and code in pParse and return NULL. */
66317   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
66318   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
66319     return;
66320   }
66321
66322   assert( pName2!=0 || pName1==0 );
66323   if( pName1==0 ){
66324     /* Form 1:  Analyze everything */
66325     for(i=0; i<db->nDb; i++){
66326       if( i==1 ) continue;  /* Do not analyze the TEMP database */
66327       analyzeDatabase(pParse, i);
66328     }
66329   }else if( pName2->n==0 ){
66330     /* Form 2:  Analyze the database or table named */
66331     iDb = sqlite3FindDb(db, pName1);
66332     if( iDb>=0 ){
66333       analyzeDatabase(pParse, iDb);
66334     }else{
66335       z = sqlite3NameFromToken(db, pName1);
66336       if( z ){
66337         pTab = sqlite3LocateTable(pParse, 0, z, 0);
66338         sqlite3DbFree(db, z);
66339         if( pTab ){
66340           analyzeTable(pParse, pTab);
66341         }
66342       }
66343     }
66344   }else{
66345     /* Form 3: Analyze the fully qualified table name */
66346     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
66347     if( iDb>=0 ){
66348       zDb = db->aDb[iDb].zName;
66349       z = sqlite3NameFromToken(db, pTableName);
66350       if( z ){
66351         pTab = sqlite3LocateTable(pParse, 0, z, zDb);
66352         sqlite3DbFree(db, z);
66353         if( pTab ){
66354           analyzeTable(pParse, pTab);
66355         }
66356       }
66357     }   
66358   }
66359 }
66360
66361 /*
66362 ** Used to pass information from the analyzer reader through to the
66363 ** callback routine.
66364 */
66365 typedef struct analysisInfo analysisInfo;
66366 struct analysisInfo {
66367   sqlite3 *db;
66368   const char *zDatabase;
66369 };
66370
66371 /*
66372 ** This callback is invoked once for each index when reading the
66373 ** sqlite_stat1 table.  
66374 **
66375 **     argv[0] = name of the index
66376 **     argv[1] = results of analysis - on integer for each column
66377 */
66378 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
66379   analysisInfo *pInfo = (analysisInfo*)pData;
66380   Index *pIndex;
66381   int i, c;
66382   unsigned int v;
66383   const char *z;
66384
66385   assert( argc==2 );
66386   UNUSED_PARAMETER2(NotUsed, argc);
66387
66388   if( argv==0 || argv[0]==0 || argv[1]==0 ){
66389     return 0;
66390   }
66391   pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
66392   if( pIndex==0 ){
66393     return 0;
66394   }
66395   z = argv[1];
66396   for(i=0; *z && i<=pIndex->nColumn; i++){
66397     v = 0;
66398     while( (c=z[0])>='0' && c<='9' ){
66399       v = v*10 + c - '0';
66400       z++;
66401     }
66402     pIndex->aiRowEst[i] = v;
66403     if( *z==' ' ) z++;
66404   }
66405   return 0;
66406 }
66407
66408 /*
66409 ** If the Index.aSample variable is not NULL, delete the aSample[] array
66410 ** and its contents.
66411 */
66412 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(Index *pIdx){
66413 #ifdef SQLITE_ENABLE_STAT2
66414   if( pIdx->aSample ){
66415     int j;
66416     sqlite3 *dbMem = pIdx->pTable->dbMem;
66417     for(j=0; j<SQLITE_INDEX_SAMPLES; j++){
66418       IndexSample *p = &pIdx->aSample[j];
66419       if( p->eType==SQLITE_TEXT || p->eType==SQLITE_BLOB ){
66420         sqlite3DbFree(pIdx->pTable->dbMem, p->u.z);
66421       }
66422     }
66423     sqlite3DbFree(dbMem, pIdx->aSample);
66424     pIdx->aSample = 0;
66425   }
66426 #else
66427   UNUSED_PARAMETER(pIdx);
66428 #endif
66429 }
66430
66431 /*
66432 ** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
66433 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
66434 ** arrays. The contents of sqlite_stat2 are used to populate the
66435 ** Index.aSample[] arrays.
66436 **
66437 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
66438 ** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined 
66439 ** during compilation and the sqlite_stat2 table is present, no data is 
66440 ** read from it.
66441 **
66442 ** If SQLITE_ENABLE_STAT2 was defined during compilation and the 
66443 ** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
66444 ** returned. However, in this case, data is read from the sqlite_stat1
66445 ** table (if it is present) before returning.
66446 **
66447 ** If an OOM error occurs, this function always sets db->mallocFailed.
66448 ** This means if the caller does not care about other errors, the return
66449 ** code may be ignored.
66450 */
66451 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
66452   analysisInfo sInfo;
66453   HashElem *i;
66454   char *zSql;
66455   int rc;
66456
66457   assert( iDb>=0 && iDb<db->nDb );
66458   assert( db->aDb[iDb].pBt!=0 );
66459   assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
66460
66461   /* Clear any prior statistics */
66462   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
66463     Index *pIdx = sqliteHashData(i);
66464     sqlite3DefaultRowEst(pIdx);
66465     sqlite3DeleteIndexSamples(pIdx);
66466   }
66467
66468   /* Check to make sure the sqlite_stat1 table exists */
66469   sInfo.db = db;
66470   sInfo.zDatabase = db->aDb[iDb].zName;
66471   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
66472     return SQLITE_ERROR;
66473   }
66474
66475   /* Load new statistics out of the sqlite_stat1 table */
66476   zSql = sqlite3MPrintf(db, 
66477       "SELECT idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
66478   if( zSql==0 ){
66479     rc = SQLITE_NOMEM;
66480   }else{
66481     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
66482     sqlite3DbFree(db, zSql);
66483   }
66484
66485
66486   /* Load the statistics from the sqlite_stat2 table. */
66487 #ifdef SQLITE_ENABLE_STAT2
66488   if( rc==SQLITE_OK && !sqlite3FindTable(db, "sqlite_stat2", sInfo.zDatabase) ){
66489     rc = SQLITE_ERROR;
66490   }
66491   if( rc==SQLITE_OK ){
66492     sqlite3_stmt *pStmt = 0;
66493
66494     zSql = sqlite3MPrintf(db, 
66495         "SELECT idx,sampleno,sample FROM %Q.sqlite_stat2", sInfo.zDatabase);
66496     if( !zSql ){
66497       rc = SQLITE_NOMEM;
66498     }else{
66499       rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
66500       sqlite3DbFree(db, zSql);
66501     }
66502
66503     if( rc==SQLITE_OK ){
66504       while( sqlite3_step(pStmt)==SQLITE_ROW ){
66505         char *zIndex = (char *)sqlite3_column_text(pStmt, 0);
66506         Index *pIdx = sqlite3FindIndex(db, zIndex, sInfo.zDatabase);
66507         if( pIdx ){
66508           int iSample = sqlite3_column_int(pStmt, 1);
66509           sqlite3 *dbMem = pIdx->pTable->dbMem;
66510           assert( dbMem==db || dbMem==0 );
66511           if( iSample<SQLITE_INDEX_SAMPLES && iSample>=0 ){
66512             int eType = sqlite3_column_type(pStmt, 2);
66513
66514             if( pIdx->aSample==0 ){
66515               static const int sz = sizeof(IndexSample)*SQLITE_INDEX_SAMPLES;
66516               pIdx->aSample = (IndexSample *)sqlite3DbMallocZero(dbMem, sz);
66517               if( pIdx->aSample==0 ){
66518                 db->mallocFailed = 1;
66519                 break;
66520               }
66521             }
66522
66523             assert( pIdx->aSample );
66524             {
66525               IndexSample *pSample = &pIdx->aSample[iSample];
66526               pSample->eType = (u8)eType;
66527               if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
66528                 pSample->u.r = sqlite3_column_double(pStmt, 2);
66529               }else if( eType==SQLITE_TEXT || eType==SQLITE_BLOB ){
66530                 const char *z = (const char *)(
66531                     (eType==SQLITE_BLOB) ?
66532                     sqlite3_column_blob(pStmt, 2):
66533                     sqlite3_column_text(pStmt, 2)
66534                 );
66535                 int n = sqlite3_column_bytes(pStmt, 2);
66536                 if( n>24 ){
66537                   n = 24;
66538                 }
66539                 pSample->nByte = (u8)n;
66540                 pSample->u.z = sqlite3DbMallocRaw(dbMem, n);
66541                 if( pSample->u.z ){
66542                   memcpy(pSample->u.z, z, n);
66543                 }else{
66544                   db->mallocFailed = 1;
66545                   break;
66546                 }
66547               }
66548             }
66549           }
66550         }
66551       }
66552       rc = sqlite3_finalize(pStmt);
66553     }
66554   }
66555 #endif
66556
66557   if( rc==SQLITE_NOMEM ){
66558     db->mallocFailed = 1;
66559   }
66560   return rc;
66561 }
66562
66563
66564 #endif /* SQLITE_OMIT_ANALYZE */
66565
66566 /************** End of analyze.c *********************************************/
66567 /************** Begin file attach.c ******************************************/
66568 /*
66569 ** 2003 April 6
66570 **
66571 ** The author disclaims copyright to this source code.  In place of
66572 ** a legal notice, here is a blessing:
66573 **
66574 **    May you do good and not evil.
66575 **    May you find forgiveness for yourself and forgive others.
66576 **    May you share freely, never taking more than you give.
66577 **
66578 *************************************************************************
66579 ** This file contains code used to implement the ATTACH and DETACH commands.
66580 */
66581
66582 #ifndef SQLITE_OMIT_ATTACH
66583 /*
66584 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
66585 ** is slightly different from resolving a normal SQL expression, because simple
66586 ** identifiers are treated as strings, not possible column names or aliases.
66587 **
66588 ** i.e. if the parser sees:
66589 **
66590 **     ATTACH DATABASE abc AS def
66591 **
66592 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
66593 ** looking for columns of the same name.
66594 **
66595 ** This only applies to the root node of pExpr, so the statement:
66596 **
66597 **     ATTACH DATABASE abc||def AS 'db2'
66598 **
66599 ** will fail because neither abc or def can be resolved.
66600 */
66601 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
66602 {
66603   int rc = SQLITE_OK;
66604   if( pExpr ){
66605     if( pExpr->op!=TK_ID ){
66606       rc = sqlite3ResolveExprNames(pName, pExpr);
66607       if( rc==SQLITE_OK && !sqlite3ExprIsConstant(pExpr) ){
66608         sqlite3ErrorMsg(pName->pParse, "invalid name: \"%s\"", pExpr->u.zToken);
66609         return SQLITE_ERROR;
66610       }
66611     }else{
66612       pExpr->op = TK_STRING;
66613     }
66614   }
66615   return rc;
66616 }
66617
66618 /*
66619 ** An SQL user-function registered to do the work of an ATTACH statement. The
66620 ** three arguments to the function come directly from an attach statement:
66621 **
66622 **     ATTACH DATABASE x AS y KEY z
66623 **
66624 **     SELECT sqlite_attach(x, y, z)
66625 **
66626 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
66627 ** third argument.
66628 */
66629 static void attachFunc(
66630   sqlite3_context *context,
66631   int NotUsed,
66632   sqlite3_value **argv
66633 ){
66634   int i;
66635   int rc = 0;
66636   sqlite3 *db = sqlite3_context_db_handle(context);
66637   const char *zName;
66638   const char *zFile;
66639   Db *aNew;
66640   char *zErrDyn = 0;
66641
66642   UNUSED_PARAMETER(NotUsed);
66643
66644   zFile = (const char *)sqlite3_value_text(argv[0]);
66645   zName = (const char *)sqlite3_value_text(argv[1]);
66646   if( zFile==0 ) zFile = "";
66647   if( zName==0 ) zName = "";
66648
66649   /* Check for the following errors:
66650   **
66651   **     * Too many attached databases,
66652   **     * Transaction currently open
66653   **     * Specified database name already being used.
66654   */
66655   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
66656     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", 
66657       db->aLimit[SQLITE_LIMIT_ATTACHED]
66658     );
66659     goto attach_error;
66660   }
66661   if( !db->autoCommit ){
66662     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
66663     goto attach_error;
66664   }
66665   for(i=0; i<db->nDb; i++){
66666     char *z = db->aDb[i].zName;
66667     assert( z && zName );
66668     if( sqlite3StrICmp(z, zName)==0 ){
66669       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
66670       goto attach_error;
66671     }
66672   }
66673
66674   /* Allocate the new entry in the db->aDb[] array and initialise the schema
66675   ** hash tables.
66676   */
66677   if( db->aDb==db->aDbStatic ){
66678     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
66679     if( aNew==0 ) return;
66680     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
66681   }else{
66682     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
66683     if( aNew==0 ) return;
66684   }
66685   db->aDb = aNew;
66686   aNew = &db->aDb[db->nDb];
66687   memset(aNew, 0, sizeof(*aNew));
66688
66689   /* Open the database file. If the btree is successfully opened, use
66690   ** it to obtain the database schema. At this point the schema may
66691   ** or may not be initialised.
66692   */
66693   rc = sqlite3BtreeFactory(db, zFile, 0, SQLITE_DEFAULT_CACHE_SIZE,
66694                            db->openFlags | SQLITE_OPEN_MAIN_DB,
66695                            &aNew->pBt);
66696   db->nDb++;
66697   if( rc==SQLITE_CONSTRAINT ){
66698     rc = SQLITE_ERROR;
66699     zErrDyn = sqlite3MPrintf(db, "database is already attached");
66700   }else if( rc==SQLITE_OK ){
66701     Pager *pPager;
66702     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
66703     if( !aNew->pSchema ){
66704       rc = SQLITE_NOMEM;
66705     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
66706       zErrDyn = sqlite3MPrintf(db, 
66707         "attached databases must use the same text encoding as main database");
66708       rc = SQLITE_ERROR;
66709     }
66710     pPager = sqlite3BtreePager(aNew->pBt);
66711     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
66712     sqlite3PagerJournalMode(pPager, db->dfltJournalMode);
66713     sqlite3BtreeSecureDelete(aNew->pBt,
66714                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
66715   }
66716   aNew->safety_level = 3;
66717   aNew->zName = sqlite3DbStrDup(db, zName);
66718   if( rc==SQLITE_OK && aNew->zName==0 ){
66719     rc = SQLITE_NOMEM;
66720   }
66721
66722
66723 #ifdef SQLITE_HAS_CODEC
66724   if( rc==SQLITE_OK ){
66725     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
66726     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
66727     int nKey;
66728     char *zKey;
66729     int t = sqlite3_value_type(argv[2]);
66730     switch( t ){
66731       case SQLITE_INTEGER:
66732       case SQLITE_FLOAT:
66733         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
66734         rc = SQLITE_ERROR;
66735         break;
66736         
66737       case SQLITE_TEXT:
66738       case SQLITE_BLOB:
66739         nKey = sqlite3_value_bytes(argv[2]);
66740         zKey = (char *)sqlite3_value_blob(argv[2]);
66741         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
66742         break;
66743
66744       case SQLITE_NULL:
66745         /* No key specified.  Use the key from the main database */
66746         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
66747         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
66748         break;
66749     }
66750   }
66751 #endif
66752
66753   /* If the file was opened successfully, read the schema for the new database.
66754   ** If this fails, or if opening the file failed, then close the file and 
66755   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
66756   ** we found it.
66757   */
66758   if( rc==SQLITE_OK ){
66759     sqlite3BtreeEnterAll(db);
66760     rc = sqlite3Init(db, &zErrDyn);
66761     sqlite3BtreeLeaveAll(db);
66762   }
66763   if( rc ){
66764     int iDb = db->nDb - 1;
66765     assert( iDb>=2 );
66766     if( db->aDb[iDb].pBt ){
66767       sqlite3BtreeClose(db->aDb[iDb].pBt);
66768       db->aDb[iDb].pBt = 0;
66769       db->aDb[iDb].pSchema = 0;
66770     }
66771     sqlite3ResetInternalSchema(db, 0);
66772     db->nDb = iDb;
66773     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
66774       db->mallocFailed = 1;
66775       sqlite3DbFree(db, zErrDyn);
66776       zErrDyn = sqlite3MPrintf(db, "out of memory");
66777     }else if( zErrDyn==0 ){
66778       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
66779     }
66780     goto attach_error;
66781   }
66782   
66783   return;
66784
66785 attach_error:
66786   /* Return an error if we get here */
66787   if( zErrDyn ){
66788     sqlite3_result_error(context, zErrDyn, -1);
66789     sqlite3DbFree(db, zErrDyn);
66790   }
66791   if( rc ) sqlite3_result_error_code(context, rc);
66792 }
66793
66794 /*
66795 ** An SQL user-function registered to do the work of an DETACH statement. The
66796 ** three arguments to the function come directly from a detach statement:
66797 **
66798 **     DETACH DATABASE x
66799 **
66800 **     SELECT sqlite_detach(x)
66801 */
66802 static void detachFunc(
66803   sqlite3_context *context,
66804   int NotUsed,
66805   sqlite3_value **argv
66806 ){
66807   const char *zName = (const char *)sqlite3_value_text(argv[0]);
66808   sqlite3 *db = sqlite3_context_db_handle(context);
66809   int i;
66810   Db *pDb = 0;
66811   char zErr[128];
66812
66813   UNUSED_PARAMETER(NotUsed);
66814
66815   if( zName==0 ) zName = "";
66816   for(i=0; i<db->nDb; i++){
66817     pDb = &db->aDb[i];
66818     if( pDb->pBt==0 ) continue;
66819     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
66820   }
66821
66822   if( i>=db->nDb ){
66823     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
66824     goto detach_error;
66825   }
66826   if( i<2 ){
66827     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
66828     goto detach_error;
66829   }
66830   if( !db->autoCommit ){
66831     sqlite3_snprintf(sizeof(zErr), zErr,
66832                      "cannot DETACH database within transaction");
66833     goto detach_error;
66834   }
66835   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
66836     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
66837     goto detach_error;
66838   }
66839
66840   sqlite3BtreeClose(pDb->pBt);
66841   pDb->pBt = 0;
66842   pDb->pSchema = 0;
66843   sqlite3ResetInternalSchema(db, 0);
66844   return;
66845
66846 detach_error:
66847   sqlite3_result_error(context, zErr, -1);
66848 }
66849
66850 /*
66851 ** This procedure generates VDBE code for a single invocation of either the
66852 ** sqlite_detach() or sqlite_attach() SQL user functions.
66853 */
66854 static void codeAttach(
66855   Parse *pParse,       /* The parser context */
66856   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
66857   FuncDef *pFunc,      /* FuncDef wrapper for detachFunc() or attachFunc() */
66858   Expr *pAuthArg,      /* Expression to pass to authorization callback */
66859   Expr *pFilename,     /* Name of database file */
66860   Expr *pDbname,       /* Name of the database to use internally */
66861   Expr *pKey           /* Database key for encryption extension */
66862 ){
66863   int rc;
66864   NameContext sName;
66865   Vdbe *v;
66866   sqlite3* db = pParse->db;
66867   int regArgs;
66868
66869   memset(&sName, 0, sizeof(NameContext));
66870   sName.pParse = pParse;
66871
66872   if( 
66873       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
66874       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
66875       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
66876   ){
66877     pParse->nErr++;
66878     goto attach_end;
66879   }
66880
66881 #ifndef SQLITE_OMIT_AUTHORIZATION
66882   if( pAuthArg ){
66883     char *zAuthArg = pAuthArg->u.zToken;
66884     if( NEVER(zAuthArg==0) ){
66885       goto attach_end;
66886     }
66887     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
66888     if(rc!=SQLITE_OK ){
66889       goto attach_end;
66890     }
66891   }
66892 #endif /* SQLITE_OMIT_AUTHORIZATION */
66893
66894
66895   v = sqlite3GetVdbe(pParse);
66896   regArgs = sqlite3GetTempRange(pParse, 4);
66897   sqlite3ExprCode(pParse, pFilename, regArgs);
66898   sqlite3ExprCode(pParse, pDbname, regArgs+1);
66899   sqlite3ExprCode(pParse, pKey, regArgs+2);
66900
66901   assert( v || db->mallocFailed );
66902   if( v ){
66903     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
66904     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
66905     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
66906     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
66907
66908     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
66909     ** statement only). For DETACH, set it to false (expire all existing
66910     ** statements).
66911     */
66912     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
66913   }
66914   
66915 attach_end:
66916   sqlite3ExprDelete(db, pFilename);
66917   sqlite3ExprDelete(db, pDbname);
66918   sqlite3ExprDelete(db, pKey);
66919 }
66920
66921 /*
66922 ** Called by the parser to compile a DETACH statement.
66923 **
66924 **     DETACH pDbname
66925 */
66926 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
66927   static FuncDef detach_func = {
66928     1,                /* nArg */
66929     SQLITE_UTF8,      /* iPrefEnc */
66930     0,                /* flags */
66931     0,                /* pUserData */
66932     0,                /* pNext */
66933     detachFunc,       /* xFunc */
66934     0,                /* xStep */
66935     0,                /* xFinalize */
66936     "sqlite_detach",  /* zName */
66937     0                 /* pHash */
66938   };
66939   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
66940 }
66941
66942 /*
66943 ** Called by the parser to compile an ATTACH statement.
66944 **
66945 **     ATTACH p AS pDbname KEY pKey
66946 */
66947 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
66948   static FuncDef attach_func = {
66949     3,                /* nArg */
66950     SQLITE_UTF8,      /* iPrefEnc */
66951     0,                /* flags */
66952     0,                /* pUserData */
66953     0,                /* pNext */
66954     attachFunc,       /* xFunc */
66955     0,                /* xStep */
66956     0,                /* xFinalize */
66957     "sqlite_attach",  /* zName */
66958     0                 /* pHash */
66959   };
66960   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
66961 }
66962 #endif /* SQLITE_OMIT_ATTACH */
66963
66964 /*
66965 ** Initialize a DbFixer structure.  This routine must be called prior
66966 ** to passing the structure to one of the sqliteFixAAAA() routines below.
66967 **
66968 ** The return value indicates whether or not fixation is required.  TRUE
66969 ** means we do need to fix the database references, FALSE means we do not.
66970 */
66971 SQLITE_PRIVATE int sqlite3FixInit(
66972   DbFixer *pFix,      /* The fixer to be initialized */
66973   Parse *pParse,      /* Error messages will be written here */
66974   int iDb,            /* This is the database that must be used */
66975   const char *zType,  /* "view", "trigger", or "index" */
66976   const Token *pName  /* Name of the view, trigger, or index */
66977 ){
66978   sqlite3 *db;
66979
66980   if( NEVER(iDb<0) || iDb==1 ) return 0;
66981   db = pParse->db;
66982   assert( db->nDb>iDb );
66983   pFix->pParse = pParse;
66984   pFix->zDb = db->aDb[iDb].zName;
66985   pFix->zType = zType;
66986   pFix->pName = pName;
66987   return 1;
66988 }
66989
66990 /*
66991 ** The following set of routines walk through the parse tree and assign
66992 ** a specific database to all table references where the database name
66993 ** was left unspecified in the original SQL statement.  The pFix structure
66994 ** must have been initialized by a prior call to sqlite3FixInit().
66995 **
66996 ** These routines are used to make sure that an index, trigger, or
66997 ** view in one database does not refer to objects in a different database.
66998 ** (Exception: indices, triggers, and views in the TEMP database are
66999 ** allowed to refer to anything.)  If a reference is explicitly made
67000 ** to an object in a different database, an error message is added to
67001 ** pParse->zErrMsg and these routines return non-zero.  If everything
67002 ** checks out, these routines return 0.
67003 */
67004 SQLITE_PRIVATE int sqlite3FixSrcList(
67005   DbFixer *pFix,       /* Context of the fixation */
67006   SrcList *pList       /* The Source list to check and modify */
67007 ){
67008   int i;
67009   const char *zDb;
67010   struct SrcList_item *pItem;
67011
67012   if( NEVER(pList==0) ) return 0;
67013   zDb = pFix->zDb;
67014   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
67015     if( pItem->zDatabase==0 ){
67016       pItem->zDatabase = sqlite3DbStrDup(pFix->pParse->db, zDb);
67017     }else if( sqlite3StrICmp(pItem->zDatabase,zDb)!=0 ){
67018       sqlite3ErrorMsg(pFix->pParse,
67019          "%s %T cannot reference objects in database %s",
67020          pFix->zType, pFix->pName, pItem->zDatabase);
67021       return 1;
67022     }
67023 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
67024     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
67025     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
67026 #endif
67027   }
67028   return 0;
67029 }
67030 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
67031 SQLITE_PRIVATE int sqlite3FixSelect(
67032   DbFixer *pFix,       /* Context of the fixation */
67033   Select *pSelect      /* The SELECT statement to be fixed to one database */
67034 ){
67035   while( pSelect ){
67036     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
67037       return 1;
67038     }
67039     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
67040       return 1;
67041     }
67042     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
67043       return 1;
67044     }
67045     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
67046       return 1;
67047     }
67048     pSelect = pSelect->pPrior;
67049   }
67050   return 0;
67051 }
67052 SQLITE_PRIVATE int sqlite3FixExpr(
67053   DbFixer *pFix,     /* Context of the fixation */
67054   Expr *pExpr        /* The expression to be fixed to one database */
67055 ){
67056   while( pExpr ){
67057     if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ) break;
67058     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
67059       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
67060     }else{
67061       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
67062     }
67063     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
67064       return 1;
67065     }
67066     pExpr = pExpr->pLeft;
67067   }
67068   return 0;
67069 }
67070 SQLITE_PRIVATE int sqlite3FixExprList(
67071   DbFixer *pFix,     /* Context of the fixation */
67072   ExprList *pList    /* The expression to be fixed to one database */
67073 ){
67074   int i;
67075   struct ExprList_item *pItem;
67076   if( pList==0 ) return 0;
67077   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
67078     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
67079       return 1;
67080     }
67081   }
67082   return 0;
67083 }
67084 #endif
67085
67086 #ifndef SQLITE_OMIT_TRIGGER
67087 SQLITE_PRIVATE int sqlite3FixTriggerStep(
67088   DbFixer *pFix,     /* Context of the fixation */
67089   TriggerStep *pStep /* The trigger step be fixed to one database */
67090 ){
67091   while( pStep ){
67092     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
67093       return 1;
67094     }
67095     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
67096       return 1;
67097     }
67098     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
67099       return 1;
67100     }
67101     pStep = pStep->pNext;
67102   }
67103   return 0;
67104 }
67105 #endif
67106
67107 /************** End of attach.c **********************************************/
67108 /************** Begin file auth.c ********************************************/
67109 /*
67110 ** 2003 January 11
67111 **
67112 ** The author disclaims copyright to this source code.  In place of
67113 ** a legal notice, here is a blessing:
67114 **
67115 **    May you do good and not evil.
67116 **    May you find forgiveness for yourself and forgive others.
67117 **    May you share freely, never taking more than you give.
67118 **
67119 *************************************************************************
67120 ** This file contains code used to implement the sqlite3_set_authorizer()
67121 ** API.  This facility is an optional feature of the library.  Embedded
67122 ** systems that do not need this facility may omit it by recompiling
67123 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
67124 */
67125
67126 /*
67127 ** All of the code in this file may be omitted by defining a single
67128 ** macro.
67129 */
67130 #ifndef SQLITE_OMIT_AUTHORIZATION
67131
67132 /*
67133 ** Set or clear the access authorization function.
67134 **
67135 ** The access authorization function is be called during the compilation
67136 ** phase to verify that the user has read and/or write access permission on
67137 ** various fields of the database.  The first argument to the auth function
67138 ** is a copy of the 3rd argument to this routine.  The second argument
67139 ** to the auth function is one of these constants:
67140 **
67141 **       SQLITE_CREATE_INDEX
67142 **       SQLITE_CREATE_TABLE
67143 **       SQLITE_CREATE_TEMP_INDEX
67144 **       SQLITE_CREATE_TEMP_TABLE
67145 **       SQLITE_CREATE_TEMP_TRIGGER
67146 **       SQLITE_CREATE_TEMP_VIEW
67147 **       SQLITE_CREATE_TRIGGER
67148 **       SQLITE_CREATE_VIEW
67149 **       SQLITE_DELETE
67150 **       SQLITE_DROP_INDEX
67151 **       SQLITE_DROP_TABLE
67152 **       SQLITE_DROP_TEMP_INDEX
67153 **       SQLITE_DROP_TEMP_TABLE
67154 **       SQLITE_DROP_TEMP_TRIGGER
67155 **       SQLITE_DROP_TEMP_VIEW
67156 **       SQLITE_DROP_TRIGGER
67157 **       SQLITE_DROP_VIEW
67158 **       SQLITE_INSERT
67159 **       SQLITE_PRAGMA
67160 **       SQLITE_READ
67161 **       SQLITE_SELECT
67162 **       SQLITE_TRANSACTION
67163 **       SQLITE_UPDATE
67164 **
67165 ** The third and fourth arguments to the auth function are the name of
67166 ** the table and the column that are being accessed.  The auth function
67167 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
67168 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
67169 ** means that the SQL statement will never-run - the sqlite3_exec() call
67170 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
67171 ** should run but attempts to read the specified column will return NULL
67172 ** and attempts to write the column will be ignored.
67173 **
67174 ** Setting the auth function to NULL disables this hook.  The default
67175 ** setting of the auth function is NULL.
67176 */
67177 SQLITE_API int sqlite3_set_authorizer(
67178   sqlite3 *db,
67179   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
67180   void *pArg
67181 ){
67182   sqlite3_mutex_enter(db->mutex);
67183   db->xAuth = xAuth;
67184   db->pAuthArg = pArg;
67185   sqlite3ExpirePreparedStatements(db);
67186   sqlite3_mutex_leave(db->mutex);
67187   return SQLITE_OK;
67188 }
67189
67190 /*
67191 ** Write an error message into pParse->zErrMsg that explains that the
67192 ** user-supplied authorization function returned an illegal value.
67193 */
67194 static void sqliteAuthBadReturnCode(Parse *pParse){
67195   sqlite3ErrorMsg(pParse, "authorizer malfunction");
67196   pParse->rc = SQLITE_ERROR;
67197 }
67198
67199 /*
67200 ** Invoke the authorization callback for permission to read column zCol from
67201 ** table zTab in database zDb. This function assumes that an authorization
67202 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
67203 **
67204 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
67205 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
67206 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
67207 */
67208 SQLITE_PRIVATE int sqlite3AuthReadCol(
67209   Parse *pParse,                  /* The parser context */
67210   const char *zTab,               /* Table name */
67211   const char *zCol,               /* Column name */
67212   int iDb                         /* Index of containing database. */
67213 ){
67214   sqlite3 *db = pParse->db;       /* Database handle */
67215   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
67216   int rc;                         /* Auth callback return code */
67217
67218   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext);
67219   if( rc==SQLITE_DENY ){
67220     if( db->nDb>2 || iDb!=0 ){
67221       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
67222     }else{
67223       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
67224     }
67225     pParse->rc = SQLITE_AUTH;
67226   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
67227     sqliteAuthBadReturnCode(pParse);
67228   }
67229   return rc;
67230 }
67231
67232 /*
67233 ** The pExpr should be a TK_COLUMN expression.  The table referred to
67234 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
67235 ** Check to see if it is OK to read this particular column.
67236 **
67237 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
67238 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
67239 ** then generate an error.
67240 */
67241 SQLITE_PRIVATE void sqlite3AuthRead(
67242   Parse *pParse,        /* The parser context */
67243   Expr *pExpr,          /* The expression to check authorization on */
67244   Schema *pSchema,      /* The schema of the expression */
67245   SrcList *pTabList     /* All table that pExpr might refer to */
67246 ){
67247   sqlite3 *db = pParse->db;
67248   Table *pTab = 0;      /* The table being read */
67249   const char *zCol;     /* Name of the column of the table */
67250   int iSrc;             /* Index in pTabList->a[] of table being read */
67251   int iDb;              /* The index of the database the expression refers to */
67252   int iCol;             /* Index of column in table */
67253
67254   if( db->xAuth==0 ) return;
67255   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
67256   if( iDb<0 ){
67257     /* An attempt to read a column out of a subquery or other
67258     ** temporary table. */
67259     return;
67260   }
67261
67262   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
67263   if( pExpr->op==TK_TRIGGER ){
67264     pTab = pParse->pTriggerTab;
67265   }else{
67266     assert( pTabList );
67267     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
67268       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
67269         pTab = pTabList->a[iSrc].pTab;
67270         break;
67271       }
67272     }
67273   }
67274   iCol = pExpr->iColumn;
67275   if( NEVER(pTab==0) ) return;
67276
67277   if( iCol>=0 ){
67278     assert( iCol<pTab->nCol );
67279     zCol = pTab->aCol[iCol].zName;
67280   }else if( pTab->iPKey>=0 ){
67281     assert( pTab->iPKey<pTab->nCol );
67282     zCol = pTab->aCol[pTab->iPKey].zName;
67283   }else{
67284     zCol = "ROWID";
67285   }
67286   assert( iDb>=0 && iDb<db->nDb );
67287   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
67288     pExpr->op = TK_NULL;
67289   }
67290 }
67291
67292 /*
67293 ** Do an authorization check using the code and arguments given.  Return
67294 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
67295 ** is returned, then the error count and error message in pParse are
67296 ** modified appropriately.
67297 */
67298 SQLITE_PRIVATE int sqlite3AuthCheck(
67299   Parse *pParse,
67300   int code,
67301   const char *zArg1,
67302   const char *zArg2,
67303   const char *zArg3
67304 ){
67305   sqlite3 *db = pParse->db;
67306   int rc;
67307
67308   /* Don't do any authorization checks if the database is initialising
67309   ** or if the parser is being invoked from within sqlite3_declare_vtab.
67310   */
67311   if( db->init.busy || IN_DECLARE_VTAB ){
67312     return SQLITE_OK;
67313   }
67314
67315   if( db->xAuth==0 ){
67316     return SQLITE_OK;
67317   }
67318   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext);
67319   if( rc==SQLITE_DENY ){
67320     sqlite3ErrorMsg(pParse, "not authorized");
67321     pParse->rc = SQLITE_AUTH;
67322   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
67323     rc = SQLITE_DENY;
67324     sqliteAuthBadReturnCode(pParse);
67325   }
67326   return rc;
67327 }
67328
67329 /*
67330 ** Push an authorization context.  After this routine is called, the
67331 ** zArg3 argument to authorization callbacks will be zContext until
67332 ** popped.  Or if pParse==0, this routine is a no-op.
67333 */
67334 SQLITE_PRIVATE void sqlite3AuthContextPush(
67335   Parse *pParse,
67336   AuthContext *pContext, 
67337   const char *zContext
67338 ){
67339   assert( pParse );
67340   pContext->pParse = pParse;
67341   pContext->zAuthContext = pParse->zAuthContext;
67342   pParse->zAuthContext = zContext;
67343 }
67344
67345 /*
67346 ** Pop an authorization context that was previously pushed
67347 ** by sqlite3AuthContextPush
67348 */
67349 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
67350   if( pContext->pParse ){
67351     pContext->pParse->zAuthContext = pContext->zAuthContext;
67352     pContext->pParse = 0;
67353   }
67354 }
67355
67356 #endif /* SQLITE_OMIT_AUTHORIZATION */
67357
67358 /************** End of auth.c ************************************************/
67359 /************** Begin file build.c *******************************************/
67360 /*
67361 ** 2001 September 15
67362 **
67363 ** The author disclaims copyright to this source code.  In place of
67364 ** a legal notice, here is a blessing:
67365 **
67366 **    May you do good and not evil.
67367 **    May you find forgiveness for yourself and forgive others.
67368 **    May you share freely, never taking more than you give.
67369 **
67370 *************************************************************************
67371 ** This file contains C code routines that are called by the SQLite parser
67372 ** when syntax rules are reduced.  The routines in this file handle the
67373 ** following kinds of SQL syntax:
67374 **
67375 **     CREATE TABLE
67376 **     DROP TABLE
67377 **     CREATE INDEX
67378 **     DROP INDEX
67379 **     creating ID lists
67380 **     BEGIN TRANSACTION
67381 **     COMMIT
67382 **     ROLLBACK
67383 */
67384
67385 /*
67386 ** This routine is called when a new SQL statement is beginning to
67387 ** be parsed.  Initialize the pParse structure as needed.
67388 */
67389 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
67390   pParse->explain = (u8)explainFlag;
67391   pParse->nVar = 0;
67392 }
67393
67394 #ifndef SQLITE_OMIT_SHARED_CACHE
67395 /*
67396 ** The TableLock structure is only used by the sqlite3TableLock() and
67397 ** codeTableLocks() functions.
67398 */
67399 struct TableLock {
67400   int iDb;             /* The database containing the table to be locked */
67401   int iTab;            /* The root page of the table to be locked */
67402   u8 isWriteLock;      /* True for write lock.  False for a read lock */
67403   const char *zName;   /* Name of the table */
67404 };
67405
67406 /*
67407 ** Record the fact that we want to lock a table at run-time.  
67408 **
67409 ** The table to be locked has root page iTab and is found in database iDb.
67410 ** A read or a write lock can be taken depending on isWritelock.
67411 **
67412 ** This routine just records the fact that the lock is desired.  The
67413 ** code to make the lock occur is generated by a later call to
67414 ** codeTableLocks() which occurs during sqlite3FinishCoding().
67415 */
67416 SQLITE_PRIVATE void sqlite3TableLock(
67417   Parse *pParse,     /* Parsing context */
67418   int iDb,           /* Index of the database containing the table to lock */
67419   int iTab,          /* Root page number of the table to be locked */
67420   u8 isWriteLock,    /* True for a write lock */
67421   const char *zName  /* Name of the table to be locked */
67422 ){
67423   Parse *pToplevel = sqlite3ParseToplevel(pParse);
67424   int i;
67425   int nBytes;
67426   TableLock *p;
67427   assert( iDb>=0 );
67428
67429   for(i=0; i<pToplevel->nTableLock; i++){
67430     p = &pToplevel->aTableLock[i];
67431     if( p->iDb==iDb && p->iTab==iTab ){
67432       p->isWriteLock = (p->isWriteLock || isWriteLock);
67433       return;
67434     }
67435   }
67436
67437   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
67438   pToplevel->aTableLock =
67439       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
67440   if( pToplevel->aTableLock ){
67441     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
67442     p->iDb = iDb;
67443     p->iTab = iTab;
67444     p->isWriteLock = isWriteLock;
67445     p->zName = zName;
67446   }else{
67447     pToplevel->nTableLock = 0;
67448     pToplevel->db->mallocFailed = 1;
67449   }
67450 }
67451
67452 /*
67453 ** Code an OP_TableLock instruction for each table locked by the
67454 ** statement (configured by calls to sqlite3TableLock()).
67455 */
67456 static void codeTableLocks(Parse *pParse){
67457   int i;
67458   Vdbe *pVdbe; 
67459
67460   pVdbe = sqlite3GetVdbe(pParse);
67461   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
67462
67463   for(i=0; i<pParse->nTableLock; i++){
67464     TableLock *p = &pParse->aTableLock[i];
67465     int p1 = p->iDb;
67466     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
67467                       p->zName, P4_STATIC);
67468   }
67469 }
67470 #else
67471   #define codeTableLocks(x)
67472 #endif
67473
67474 /*
67475 ** This routine is called after a single SQL statement has been
67476 ** parsed and a VDBE program to execute that statement has been
67477 ** prepared.  This routine puts the finishing touches on the
67478 ** VDBE program and resets the pParse structure for the next
67479 ** parse.
67480 **
67481 ** Note that if an error occurred, it might be the case that
67482 ** no VDBE code was generated.
67483 */
67484 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
67485   sqlite3 *db;
67486   Vdbe *v;
67487
67488   db = pParse->db;
67489   if( db->mallocFailed ) return;
67490   if( pParse->nested ) return;
67491   if( pParse->nErr ) return;
67492
67493   /* Begin by generating some termination code at the end of the
67494   ** vdbe program
67495   */
67496   v = sqlite3GetVdbe(pParse);
67497   assert( !pParse->isMultiWrite 
67498        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
67499   if( v ){
67500     sqlite3VdbeAddOp0(v, OP_Halt);
67501
67502     /* The cookie mask contains one bit for each database file open.
67503     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
67504     ** set for each database that is used.  Generate code to start a
67505     ** transaction on each used database and to verify the schema cookie
67506     ** on each used database.
67507     */
67508     if( pParse->cookieGoto>0 ){
67509       u32 mask;
67510       int iDb;
67511       sqlite3VdbeJumpHere(v, pParse->cookieGoto-1);
67512       for(iDb=0, mask=1; iDb<db->nDb; mask<<=1, iDb++){
67513         if( (mask & pParse->cookieMask)==0 ) continue;
67514         sqlite3VdbeUsesBtree(v, iDb);
67515         sqlite3VdbeAddOp2(v,OP_Transaction, iDb, (mask & pParse->writeMask)!=0);
67516         if( db->init.busy==0 ){
67517           sqlite3VdbeAddOp2(v,OP_VerifyCookie, iDb, pParse->cookieValue[iDb]);
67518         }
67519       }
67520 #ifndef SQLITE_OMIT_VIRTUALTABLE
67521       {
67522         int i;
67523         for(i=0; i<pParse->nVtabLock; i++){
67524           char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
67525           sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
67526         }
67527         pParse->nVtabLock = 0;
67528       }
67529 #endif
67530
67531       /* Once all the cookies have been verified and transactions opened, 
67532       ** obtain the required table-locks. This is a no-op unless the 
67533       ** shared-cache feature is enabled.
67534       */
67535       codeTableLocks(pParse);
67536
67537       /* Initialize any AUTOINCREMENT data structures required.
67538       */
67539       sqlite3AutoincrementBegin(pParse);
67540
67541       /* Finally, jump back to the beginning of the executable code. */
67542       sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->cookieGoto);
67543     }
67544   }
67545
67546
67547   /* Get the VDBE program ready for execution
67548   */
67549   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
67550 #ifdef SQLITE_DEBUG
67551     FILE *trace = (db->flags & SQLITE_VdbeTrace)!=0 ? stdout : 0;
67552     sqlite3VdbeTrace(v, trace);
67553 #endif
67554     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
67555     /* A minimum of one cursor is required if autoincrement is used
67556     *  See ticket [a696379c1f08866] */
67557     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
67558     sqlite3VdbeMakeReady(v, pParse->nVar, pParse->nMem,
67559                          pParse->nTab, pParse->nMaxArg, pParse->explain,
67560                          pParse->isMultiWrite && pParse->mayAbort);
67561     pParse->rc = SQLITE_DONE;
67562     pParse->colNamesSet = 0;
67563   }else{
67564     pParse->rc = SQLITE_ERROR;
67565   }
67566   pParse->nTab = 0;
67567   pParse->nMem = 0;
67568   pParse->nSet = 0;
67569   pParse->nVar = 0;
67570   pParse->cookieMask = 0;
67571   pParse->cookieGoto = 0;
67572 }
67573
67574 /*
67575 ** Run the parser and code generator recursively in order to generate
67576 ** code for the SQL statement given onto the end of the pParse context
67577 ** currently under construction.  When the parser is run recursively
67578 ** this way, the final OP_Halt is not appended and other initialization
67579 ** and finalization steps are omitted because those are handling by the
67580 ** outermost parser.
67581 **
67582 ** Not everything is nestable.  This facility is designed to permit
67583 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
67584 ** care if you decide to try to use this routine for some other purposes.
67585 */
67586 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
67587   va_list ap;
67588   char *zSql;
67589   char *zErrMsg = 0;
67590   sqlite3 *db = pParse->db;
67591 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
67592   char saveBuf[SAVE_SZ];
67593
67594   if( pParse->nErr ) return;
67595   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
67596   va_start(ap, zFormat);
67597   zSql = sqlite3VMPrintf(db, zFormat, ap);
67598   va_end(ap);
67599   if( zSql==0 ){
67600     return;   /* A malloc must have failed */
67601   }
67602   pParse->nested++;
67603   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
67604   memset(&pParse->nVar, 0, SAVE_SZ);
67605   sqlite3RunParser(pParse, zSql, &zErrMsg);
67606   sqlite3DbFree(db, zErrMsg);
67607   sqlite3DbFree(db, zSql);
67608   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
67609   pParse->nested--;
67610 }
67611
67612 /*
67613 ** Locate the in-memory structure that describes a particular database
67614 ** table given the name of that table and (optionally) the name of the
67615 ** database containing the table.  Return NULL if not found.
67616 **
67617 ** If zDatabase is 0, all databases are searched for the table and the
67618 ** first matching table is returned.  (No checking for duplicate table
67619 ** names is done.)  The search order is TEMP first, then MAIN, then any
67620 ** auxiliary databases added using the ATTACH command.
67621 **
67622 ** See also sqlite3LocateTable().
67623 */
67624 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
67625   Table *p = 0;
67626   int i;
67627   int nName;
67628   assert( zName!=0 );
67629   nName = sqlite3Strlen30(zName);
67630   for(i=OMIT_TEMPDB; i<db->nDb; i++){
67631     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
67632     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
67633     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName, nName);
67634     if( p ) break;
67635   }
67636   return p;
67637 }
67638
67639 /*
67640 ** Locate the in-memory structure that describes a particular database
67641 ** table given the name of that table and (optionally) the name of the
67642 ** database containing the table.  Return NULL if not found.  Also leave an
67643 ** error message in pParse->zErrMsg.
67644 **
67645 ** The difference between this routine and sqlite3FindTable() is that this
67646 ** routine leaves an error message in pParse->zErrMsg where
67647 ** sqlite3FindTable() does not.
67648 */
67649 SQLITE_PRIVATE Table *sqlite3LocateTable(
67650   Parse *pParse,         /* context in which to report errors */
67651   int isView,            /* True if looking for a VIEW rather than a TABLE */
67652   const char *zName,     /* Name of the table we are looking for */
67653   const char *zDbase     /* Name of the database.  Might be NULL */
67654 ){
67655   Table *p;
67656
67657   /* Read the database schema. If an error occurs, leave an error message
67658   ** and code in pParse and return NULL. */
67659   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
67660     return 0;
67661   }
67662
67663   p = sqlite3FindTable(pParse->db, zName, zDbase);
67664   if( p==0 ){
67665     const char *zMsg = isView ? "no such view" : "no such table";
67666     if( zDbase ){
67667       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
67668     }else{
67669       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
67670     }
67671     pParse->checkSchema = 1;
67672   }
67673   return p;
67674 }
67675
67676 /*
67677 ** Locate the in-memory structure that describes 
67678 ** a particular index given the name of that index
67679 ** and the name of the database that contains the index.
67680 ** Return NULL if not found.
67681 **
67682 ** If zDatabase is 0, all databases are searched for the
67683 ** table and the first matching index is returned.  (No checking
67684 ** for duplicate index names is done.)  The search order is
67685 ** TEMP first, then MAIN, then any auxiliary databases added
67686 ** using the ATTACH command.
67687 */
67688 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
67689   Index *p = 0;
67690   int i;
67691   int nName = sqlite3Strlen30(zName);
67692   for(i=OMIT_TEMPDB; i<db->nDb; i++){
67693     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
67694     Schema *pSchema = db->aDb[j].pSchema;
67695     assert( pSchema );
67696     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
67697     p = sqlite3HashFind(&pSchema->idxHash, zName, nName);
67698     if( p ) break;
67699   }
67700   return p;
67701 }
67702
67703 /*
67704 ** Reclaim the memory used by an index
67705 */
67706 static void freeIndex(Index *p){
67707   sqlite3 *db = p->pTable->dbMem;
67708 #ifndef SQLITE_OMIT_ANALYZE
67709   sqlite3DeleteIndexSamples(p);
67710 #endif
67711   sqlite3DbFree(db, p->zColAff);
67712   sqlite3DbFree(db, p);
67713 }
67714
67715 /*
67716 ** Remove the given index from the index hash table, and free
67717 ** its memory structures.
67718 **
67719 ** The index is removed from the database hash tables but
67720 ** it is not unlinked from the Table that it indexes.
67721 ** Unlinking from the Table must be done by the calling function.
67722 */
67723 static void sqlite3DeleteIndex(Index *p){
67724   Index *pOld;
67725   const char *zName = p->zName;
67726
67727   pOld = sqlite3HashInsert(&p->pSchema->idxHash, zName,
67728                            sqlite3Strlen30(zName), 0);
67729   assert( pOld==0 || pOld==p );
67730   freeIndex(p);
67731 }
67732
67733 /*
67734 ** For the index called zIdxName which is found in the database iDb,
67735 ** unlike that index from its Table then remove the index from
67736 ** the index hash table and free all memory structures associated
67737 ** with the index.
67738 */
67739 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
67740   Index *pIndex;
67741   int len;
67742   Hash *pHash = &db->aDb[iDb].pSchema->idxHash;
67743
67744   len = sqlite3Strlen30(zIdxName);
67745   pIndex = sqlite3HashInsert(pHash, zIdxName, len, 0);
67746   if( pIndex ){
67747     if( pIndex->pTable->pIndex==pIndex ){
67748       pIndex->pTable->pIndex = pIndex->pNext;
67749     }else{
67750       Index *p;
67751       /* Justification of ALWAYS();  The index must be on the list of
67752       ** indices. */
67753       p = pIndex->pTable->pIndex;
67754       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
67755       if( ALWAYS(p && p->pNext==pIndex) ){
67756         p->pNext = pIndex->pNext;
67757       }
67758     }
67759     freeIndex(pIndex);
67760   }
67761   db->flags |= SQLITE_InternChanges;
67762 }
67763
67764 /*
67765 ** Erase all schema information from the in-memory hash tables of
67766 ** a single database.  This routine is called to reclaim memory
67767 ** before the database closes.  It is also called during a rollback
67768 ** if there were schema changes during the transaction or if a
67769 ** schema-cookie mismatch occurs.
67770 **
67771 ** If iDb==0 then reset the internal schema tables for all database
67772 ** files.  If iDb>=1 then reset the internal schema for only the
67773 ** single file indicated.
67774 */
67775 SQLITE_PRIVATE void sqlite3ResetInternalSchema(sqlite3 *db, int iDb){
67776   int i, j;
67777   assert( iDb>=0 && iDb<db->nDb );
67778
67779   if( iDb==0 ){
67780     sqlite3BtreeEnterAll(db);
67781   }
67782   for(i=iDb; i<db->nDb; i++){
67783     Db *pDb = &db->aDb[i];
67784     if( pDb->pSchema ){
67785       assert(i==1 || (pDb->pBt && sqlite3BtreeHoldsMutex(pDb->pBt)));
67786       sqlite3SchemaFree(pDb->pSchema);
67787     }
67788     if( iDb>0 ) return;
67789   }
67790   assert( iDb==0 );
67791   db->flags &= ~SQLITE_InternChanges;
67792   sqlite3VtabUnlockList(db);
67793   sqlite3BtreeLeaveAll(db);
67794
67795   /* If one or more of the auxiliary database files has been closed,
67796   ** then remove them from the auxiliary database list.  We take the
67797   ** opportunity to do this here since we have just deleted all of the
67798   ** schema hash tables and therefore do not have to make any changes
67799   ** to any of those tables.
67800   */
67801   for(i=j=2; i<db->nDb; i++){
67802     struct Db *pDb = &db->aDb[i];
67803     if( pDb->pBt==0 ){
67804       sqlite3DbFree(db, pDb->zName);
67805       pDb->zName = 0;
67806       continue;
67807     }
67808     if( j<i ){
67809       db->aDb[j] = db->aDb[i];
67810     }
67811     j++;
67812   }
67813   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
67814   db->nDb = j;
67815   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
67816     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
67817     sqlite3DbFree(db, db->aDb);
67818     db->aDb = db->aDbStatic;
67819   }
67820 }
67821
67822 /*
67823 ** This routine is called when a commit occurs.
67824 */
67825 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
67826   db->flags &= ~SQLITE_InternChanges;
67827 }
67828
67829 /*
67830 ** Clear the column names from a table or view.
67831 */
67832 static void sqliteResetColumnNames(Table *pTable){
67833   int i;
67834   Column *pCol;
67835   sqlite3 *db = pTable->dbMem;
67836   testcase( db==0 );
67837   assert( pTable!=0 );
67838   if( (pCol = pTable->aCol)!=0 ){
67839     for(i=0; i<pTable->nCol; i++, pCol++){
67840       sqlite3DbFree(db, pCol->zName);
67841       sqlite3ExprDelete(db, pCol->pDflt);
67842       sqlite3DbFree(db, pCol->zDflt);
67843       sqlite3DbFree(db, pCol->zType);
67844       sqlite3DbFree(db, pCol->zColl);
67845     }
67846     sqlite3DbFree(db, pTable->aCol);
67847   }
67848   pTable->aCol = 0;
67849   pTable->nCol = 0;
67850 }
67851
67852 /*
67853 ** Remove the memory data structures associated with the given
67854 ** Table.  No changes are made to disk by this routine.
67855 **
67856 ** This routine just deletes the data structure.  It does not unlink
67857 ** the table data structure from the hash table.  But it does destroy
67858 ** memory structures of the indices and foreign keys associated with 
67859 ** the table.
67860 */
67861 SQLITE_PRIVATE void sqlite3DeleteTable(Table *pTable){
67862   Index *pIndex, *pNext;
67863   sqlite3 *db;
67864
67865   if( pTable==0 ) return;
67866   db = pTable->dbMem;
67867   testcase( db==0 );
67868
67869   /* Do not delete the table until the reference count reaches zero. */
67870   pTable->nRef--;
67871   if( pTable->nRef>0 ){
67872     return;
67873   }
67874   assert( pTable->nRef==0 );
67875
67876   /* Delete all indices associated with this table
67877   */
67878   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
67879     pNext = pIndex->pNext;
67880     assert( pIndex->pSchema==pTable->pSchema );
67881     sqlite3DeleteIndex(pIndex);
67882   }
67883
67884   /* Delete any foreign keys attached to this table. */
67885   sqlite3FkDelete(pTable);
67886
67887   /* Delete the Table structure itself.
67888   */
67889   sqliteResetColumnNames(pTable);
67890   sqlite3DbFree(db, pTable->zName);
67891   sqlite3DbFree(db, pTable->zColAff);
67892   sqlite3SelectDelete(db, pTable->pSelect);
67893 #ifndef SQLITE_OMIT_CHECK
67894   sqlite3ExprDelete(db, pTable->pCheck);
67895 #endif
67896   sqlite3VtabClear(pTable);
67897   sqlite3DbFree(db, pTable);
67898 }
67899
67900 /*
67901 ** Unlink the given table from the hash tables and the delete the
67902 ** table structure with all its indices and foreign keys.
67903 */
67904 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
67905   Table *p;
67906   Db *pDb;
67907
67908   assert( db!=0 );
67909   assert( iDb>=0 && iDb<db->nDb );
67910   assert( zTabName );
67911   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
67912   pDb = &db->aDb[iDb];
67913   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName,
67914                         sqlite3Strlen30(zTabName),0);
67915   sqlite3DeleteTable(p);
67916   db->flags |= SQLITE_InternChanges;
67917 }
67918
67919 /*
67920 ** Given a token, return a string that consists of the text of that
67921 ** token.  Space to hold the returned string
67922 ** is obtained from sqliteMalloc() and must be freed by the calling
67923 ** function.
67924 **
67925 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
67926 ** surround the body of the token are removed.
67927 **
67928 ** Tokens are often just pointers into the original SQL text and so
67929 ** are not \000 terminated and are not persistent.  The returned string
67930 ** is \000 terminated and is persistent.
67931 */
67932 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
67933   char *zName;
67934   if( pName ){
67935     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
67936     sqlite3Dequote(zName);
67937   }else{
67938     zName = 0;
67939   }
67940   return zName;
67941 }
67942
67943 /*
67944 ** Open the sqlite_master table stored in database number iDb for
67945 ** writing. The table is opened using cursor 0.
67946 */
67947 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
67948   Vdbe *v = sqlite3GetVdbe(p);
67949   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
67950   sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
67951   sqlite3VdbeChangeP4(v, -1, (char *)5, P4_INT32);  /* 5 column table */
67952   if( p->nTab==0 ){
67953     p->nTab = 1;
67954   }
67955 }
67956
67957 /*
67958 ** Parameter zName points to a nul-terminated buffer containing the name
67959 ** of a database ("main", "temp" or the name of an attached db). This
67960 ** function returns the index of the named database in db->aDb[], or
67961 ** -1 if the named db cannot be found.
67962 */
67963 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
67964   int i = -1;         /* Database number */
67965   if( zName ){
67966     Db *pDb;
67967     int n = sqlite3Strlen30(zName);
67968     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
67969       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 
67970           0==sqlite3StrICmp(pDb->zName, zName) ){
67971         break;
67972       }
67973     }
67974   }
67975   return i;
67976 }
67977
67978 /*
67979 ** The token *pName contains the name of a database (either "main" or
67980 ** "temp" or the name of an attached db). This routine returns the
67981 ** index of the named database in db->aDb[], or -1 if the named db 
67982 ** does not exist.
67983 */
67984 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
67985   int i;                               /* Database number */
67986   char *zName;                         /* Name we are searching for */
67987   zName = sqlite3NameFromToken(db, pName);
67988   i = sqlite3FindDbName(db, zName);
67989   sqlite3DbFree(db, zName);
67990   return i;
67991 }
67992
67993 /* The table or view or trigger name is passed to this routine via tokens
67994 ** pName1 and pName2. If the table name was fully qualified, for example:
67995 **
67996 ** CREATE TABLE xxx.yyy (...);
67997 ** 
67998 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
67999 ** the table name is not fully qualified, i.e.:
68000 **
68001 ** CREATE TABLE yyy(...);
68002 **
68003 ** Then pName1 is set to "yyy" and pName2 is "".
68004 **
68005 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
68006 ** pName2) that stores the unqualified table name.  The index of the
68007 ** database "xxx" is returned.
68008 */
68009 SQLITE_PRIVATE int sqlite3TwoPartName(
68010   Parse *pParse,      /* Parsing and code generating context */
68011   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
68012   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
68013   Token **pUnqual     /* Write the unqualified object name here */
68014 ){
68015   int iDb;                    /* Database holding the object */
68016   sqlite3 *db = pParse->db;
68017
68018   if( ALWAYS(pName2!=0) && pName2->n>0 ){
68019     if( db->init.busy ) {
68020       sqlite3ErrorMsg(pParse, "corrupt database");
68021       pParse->nErr++;
68022       return -1;
68023     }
68024     *pUnqual = pName2;
68025     iDb = sqlite3FindDb(db, pName1);
68026     if( iDb<0 ){
68027       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
68028       pParse->nErr++;
68029       return -1;
68030     }
68031   }else{
68032     assert( db->init.iDb==0 || db->init.busy );
68033     iDb = db->init.iDb;
68034     *pUnqual = pName1;
68035   }
68036   return iDb;
68037 }
68038
68039 /*
68040 ** This routine is used to check if the UTF-8 string zName is a legal
68041 ** unqualified name for a new schema object (table, index, view or
68042 ** trigger). All names are legal except those that begin with the string
68043 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
68044 ** is reserved for internal use.
68045 */
68046 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
68047   if( !pParse->db->init.busy && pParse->nested==0 
68048           && (pParse->db->flags & SQLITE_WriteSchema)==0
68049           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
68050     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
68051     return SQLITE_ERROR;
68052   }
68053   return SQLITE_OK;
68054 }
68055
68056 /*
68057 ** Begin constructing a new table representation in memory.  This is
68058 ** the first of several action routines that get called in response
68059 ** to a CREATE TABLE statement.  In particular, this routine is called
68060 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
68061 ** flag is true if the table should be stored in the auxiliary database
68062 ** file instead of in the main database file.  This is normally the case
68063 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
68064 ** CREATE and TABLE.
68065 **
68066 ** The new table record is initialized and put in pParse->pNewTable.
68067 ** As more of the CREATE TABLE statement is parsed, additional action
68068 ** routines will be called to add more information to this record.
68069 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
68070 ** is called to complete the construction of the new table record.
68071 */
68072 SQLITE_PRIVATE void sqlite3StartTable(
68073   Parse *pParse,   /* Parser context */
68074   Token *pName1,   /* First part of the name of the table or view */
68075   Token *pName2,   /* Second part of the name of the table or view */
68076   int isTemp,      /* True if this is a TEMP table */
68077   int isView,      /* True if this is a VIEW */
68078   int isVirtual,   /* True if this is a VIRTUAL table */
68079   int noErr        /* Do nothing if table already exists */
68080 ){
68081   Table *pTable;
68082   char *zName = 0; /* The name of the new table */
68083   sqlite3 *db = pParse->db;
68084   Vdbe *v;
68085   int iDb;         /* Database number to create the table in */
68086   Token *pName;    /* Unqualified name of the table to create */
68087
68088   /* The table or view name to create is passed to this routine via tokens
68089   ** pName1 and pName2. If the table name was fully qualified, for example:
68090   **
68091   ** CREATE TABLE xxx.yyy (...);
68092   ** 
68093   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
68094   ** the table name is not fully qualified, i.e.:
68095   **
68096   ** CREATE TABLE yyy(...);
68097   **
68098   ** Then pName1 is set to "yyy" and pName2 is "".
68099   **
68100   ** The call below sets the pName pointer to point at the token (pName1 or
68101   ** pName2) that stores the unqualified table name. The variable iDb is
68102   ** set to the index of the database that the table or view is to be
68103   ** created in.
68104   */
68105   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
68106   if( iDb<0 ) return;
68107   if( !OMIT_TEMPDB && isTemp && iDb>1 ){
68108     /* If creating a temp table, the name may not be qualified */
68109     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
68110     return;
68111   }
68112   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
68113
68114   pParse->sNameToken = *pName;
68115   zName = sqlite3NameFromToken(db, pName);
68116   if( zName==0 ) return;
68117   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
68118     goto begin_table_error;
68119   }
68120   if( db->init.iDb==1 ) isTemp = 1;
68121 #ifndef SQLITE_OMIT_AUTHORIZATION
68122   assert( (isTemp & 1)==isTemp );
68123   {
68124     int code;
68125     char *zDb = db->aDb[iDb].zName;
68126     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
68127       goto begin_table_error;
68128     }
68129     if( isView ){
68130       if( !OMIT_TEMPDB && isTemp ){
68131         code = SQLITE_CREATE_TEMP_VIEW;
68132       }else{
68133         code = SQLITE_CREATE_VIEW;
68134       }
68135     }else{
68136       if( !OMIT_TEMPDB && isTemp ){
68137         code = SQLITE_CREATE_TEMP_TABLE;
68138       }else{
68139         code = SQLITE_CREATE_TABLE;
68140       }
68141     }
68142     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
68143       goto begin_table_error;
68144     }
68145   }
68146 #endif
68147
68148   /* Make sure the new table name does not collide with an existing
68149   ** index or table name in the same database.  Issue an error message if
68150   ** it does. The exception is if the statement being parsed was passed
68151   ** to an sqlite3_declare_vtab() call. In that case only the column names
68152   ** and types will be used, so there is no need to test for namespace
68153   ** collisions.
68154   */
68155   if( !IN_DECLARE_VTAB ){
68156     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
68157       goto begin_table_error;
68158     }
68159     pTable = sqlite3FindTable(db, zName, db->aDb[iDb].zName);
68160     if( pTable ){
68161       if( !noErr ){
68162         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
68163       }
68164       goto begin_table_error;
68165     }
68166     if( sqlite3FindIndex(db, zName, 0)!=0 && (iDb==0 || !db->init.busy) ){
68167       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
68168       goto begin_table_error;
68169     }
68170   }
68171
68172   pTable = sqlite3DbMallocZero(db, sizeof(Table));
68173   if( pTable==0 ){
68174     db->mallocFailed = 1;
68175     pParse->rc = SQLITE_NOMEM;
68176     pParse->nErr++;
68177     goto begin_table_error;
68178   }
68179   pTable->zName = zName;
68180   pTable->iPKey = -1;
68181   pTable->pSchema = db->aDb[iDb].pSchema;
68182   pTable->nRef = 1;
68183   pTable->dbMem = 0;
68184   assert( pParse->pNewTable==0 );
68185   pParse->pNewTable = pTable;
68186
68187   /* If this is the magic sqlite_sequence table used by autoincrement,
68188   ** then record a pointer to this table in the main database structure
68189   ** so that INSERT can find the table easily.
68190   */
68191 #ifndef SQLITE_OMIT_AUTOINCREMENT
68192   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
68193     pTable->pSchema->pSeqTab = pTable;
68194   }
68195 #endif
68196
68197   /* Begin generating the code that will insert the table record into
68198   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
68199   ** and allocate the record number for the table entry now.  Before any
68200   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
68201   ** indices to be created and the table record must come before the 
68202   ** indices.  Hence, the record number for the table must be allocated
68203   ** now.
68204   */
68205   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
68206     int j1;
68207     int fileFormat;
68208     int reg1, reg2, reg3;
68209     sqlite3BeginWriteOperation(pParse, 0, iDb);
68210
68211 #ifndef SQLITE_OMIT_VIRTUALTABLE
68212     if( isVirtual ){
68213       sqlite3VdbeAddOp0(v, OP_VBegin);
68214     }
68215 #endif
68216
68217     /* If the file format and encoding in the database have not been set, 
68218     ** set them now.
68219     */
68220     reg1 = pParse->regRowid = ++pParse->nMem;
68221     reg2 = pParse->regRoot = ++pParse->nMem;
68222     reg3 = ++pParse->nMem;
68223     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
68224     sqlite3VdbeUsesBtree(v, iDb);
68225     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
68226     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
68227                   1 : SQLITE_MAX_FILE_FORMAT;
68228     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
68229     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
68230     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
68231     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
68232     sqlite3VdbeJumpHere(v, j1);
68233
68234     /* This just creates a place-holder record in the sqlite_master table.
68235     ** The record created does not contain anything yet.  It will be replaced
68236     ** by the real entry in code generated at sqlite3EndTable().
68237     **
68238     ** The rowid for the new entry is left in register pParse->regRowid.
68239     ** The root page number of the new table is left in reg pParse->regRoot.
68240     ** The rowid and root page number values are needed by the code that
68241     ** sqlite3EndTable will generate.
68242     */
68243 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
68244     if( isView || isVirtual ){
68245       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
68246     }else
68247 #endif
68248     {
68249       sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
68250     }
68251     sqlite3OpenMasterTable(pParse, iDb);
68252     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
68253     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
68254     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
68255     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
68256     sqlite3VdbeAddOp0(v, OP_Close);
68257   }
68258
68259   /* Normal (non-error) return. */
68260   return;
68261
68262   /* If an error occurs, we jump here */
68263 begin_table_error:
68264   sqlite3DbFree(db, zName);
68265   return;
68266 }
68267
68268 /*
68269 ** This macro is used to compare two strings in a case-insensitive manner.
68270 ** It is slightly faster than calling sqlite3StrICmp() directly, but
68271 ** produces larger code.
68272 **
68273 ** WARNING: This macro is not compatible with the strcmp() family. It
68274 ** returns true if the two strings are equal, otherwise false.
68275 */
68276 #define STRICMP(x, y) (\
68277 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
68278 sqlite3UpperToLower[*(unsigned char *)(y)]     \
68279 && sqlite3StrICmp((x)+1,(y)+1)==0 )
68280
68281 /*
68282 ** Add a new column to the table currently being constructed.
68283 **
68284 ** The parser calls this routine once for each column declaration
68285 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
68286 ** first to get things going.  Then this routine is called for each
68287 ** column.
68288 */
68289 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
68290   Table *p;
68291   int i;
68292   char *z;
68293   Column *pCol;
68294   sqlite3 *db = pParse->db;
68295   if( (p = pParse->pNewTable)==0 ) return;
68296 #if SQLITE_MAX_COLUMN
68297   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
68298     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
68299     return;
68300   }
68301 #endif
68302   z = sqlite3NameFromToken(db, pName);
68303   if( z==0 ) return;
68304   for(i=0; i<p->nCol; i++){
68305     if( STRICMP(z, p->aCol[i].zName) ){
68306       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
68307       sqlite3DbFree(db, z);
68308       return;
68309     }
68310   }
68311   if( (p->nCol & 0x7)==0 ){
68312     Column *aNew;
68313     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
68314     if( aNew==0 ){
68315       sqlite3DbFree(db, z);
68316       return;
68317     }
68318     p->aCol = aNew;
68319   }
68320   pCol = &p->aCol[p->nCol];
68321   memset(pCol, 0, sizeof(p->aCol[0]));
68322   pCol->zName = z;
68323  
68324   /* If there is no type specified, columns have the default affinity
68325   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
68326   ** be called next to set pCol->affinity correctly.
68327   */
68328   pCol->affinity = SQLITE_AFF_NONE;
68329   p->nCol++;
68330 }
68331
68332 /*
68333 ** This routine is called by the parser while in the middle of
68334 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
68335 ** been seen on a column.  This routine sets the notNull flag on
68336 ** the column currently under construction.
68337 */
68338 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
68339   Table *p;
68340   p = pParse->pNewTable;
68341   if( p==0 || NEVER(p->nCol<1) ) return;
68342   p->aCol[p->nCol-1].notNull = (u8)onError;
68343 }
68344
68345 /*
68346 ** Scan the column type name zType (length nType) and return the
68347 ** associated affinity type.
68348 **
68349 ** This routine does a case-independent search of zType for the 
68350 ** substrings in the following table. If one of the substrings is
68351 ** found, the corresponding affinity is returned. If zType contains
68352 ** more than one of the substrings, entries toward the top of 
68353 ** the table take priority. For example, if zType is 'BLOBINT', 
68354 ** SQLITE_AFF_INTEGER is returned.
68355 **
68356 ** Substring     | Affinity
68357 ** --------------------------------
68358 ** 'INT'         | SQLITE_AFF_INTEGER
68359 ** 'CHAR'        | SQLITE_AFF_TEXT
68360 ** 'CLOB'        | SQLITE_AFF_TEXT
68361 ** 'TEXT'        | SQLITE_AFF_TEXT
68362 ** 'BLOB'        | SQLITE_AFF_NONE
68363 ** 'REAL'        | SQLITE_AFF_REAL
68364 ** 'FLOA'        | SQLITE_AFF_REAL
68365 ** 'DOUB'        | SQLITE_AFF_REAL
68366 **
68367 ** If none of the substrings in the above table are found,
68368 ** SQLITE_AFF_NUMERIC is returned.
68369 */
68370 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn){
68371   u32 h = 0;
68372   char aff = SQLITE_AFF_NUMERIC;
68373
68374   if( zIn ) while( zIn[0] ){
68375     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
68376     zIn++;
68377     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
68378       aff = SQLITE_AFF_TEXT; 
68379     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
68380       aff = SQLITE_AFF_TEXT;
68381     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
68382       aff = SQLITE_AFF_TEXT;
68383     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
68384         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
68385       aff = SQLITE_AFF_NONE;
68386 #ifndef SQLITE_OMIT_FLOATING_POINT
68387     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
68388         && aff==SQLITE_AFF_NUMERIC ){
68389       aff = SQLITE_AFF_REAL;
68390     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
68391         && aff==SQLITE_AFF_NUMERIC ){
68392       aff = SQLITE_AFF_REAL;
68393     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
68394         && aff==SQLITE_AFF_NUMERIC ){
68395       aff = SQLITE_AFF_REAL;
68396 #endif
68397     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
68398       aff = SQLITE_AFF_INTEGER;
68399       break;
68400     }
68401   }
68402
68403   return aff;
68404 }
68405
68406 /*
68407 ** This routine is called by the parser while in the middle of
68408 ** parsing a CREATE TABLE statement.  The pFirst token is the first
68409 ** token in the sequence of tokens that describe the type of the
68410 ** column currently under construction.   pLast is the last token
68411 ** in the sequence.  Use this information to construct a string
68412 ** that contains the typename of the column and store that string
68413 ** in zType.
68414 */ 
68415 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
68416   Table *p;
68417   Column *pCol;
68418
68419   p = pParse->pNewTable;
68420   if( p==0 || NEVER(p->nCol<1) ) return;
68421   pCol = &p->aCol[p->nCol-1];
68422   assert( pCol->zType==0 );
68423   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
68424   pCol->affinity = sqlite3AffinityType(pCol->zType);
68425 }
68426
68427 /*
68428 ** The expression is the default value for the most recently added column
68429 ** of the table currently under construction.
68430 **
68431 ** Default value expressions must be constant.  Raise an exception if this
68432 ** is not the case.
68433 **
68434 ** This routine is called by the parser while in the middle of
68435 ** parsing a CREATE TABLE statement.
68436 */
68437 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
68438   Table *p;
68439   Column *pCol;
68440   sqlite3 *db = pParse->db;
68441   p = pParse->pNewTable;
68442   if( p!=0 ){
68443     pCol = &(p->aCol[p->nCol-1]);
68444     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr) ){
68445       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
68446           pCol->zName);
68447     }else{
68448       /* A copy of pExpr is used instead of the original, as pExpr contains
68449       ** tokens that point to volatile memory. The 'span' of the expression
68450       ** is required by pragma table_info.
68451       */
68452       sqlite3ExprDelete(db, pCol->pDflt);
68453       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
68454       sqlite3DbFree(db, pCol->zDflt);
68455       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
68456                                      (int)(pSpan->zEnd - pSpan->zStart));
68457     }
68458   }
68459   sqlite3ExprDelete(db, pSpan->pExpr);
68460 }
68461
68462 /*
68463 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
68464 ** of columns that form the primary key.  If pList is NULL, then the
68465 ** most recently added column of the table is the primary key.
68466 **
68467 ** A table can have at most one primary key.  If the table already has
68468 ** a primary key (and this is the second primary key) then create an
68469 ** error.
68470 **
68471 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
68472 ** then we will try to use that column as the rowid.  Set the Table.iPKey
68473 ** field of the table under construction to be the index of the
68474 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
68475 ** no INTEGER PRIMARY KEY.
68476 **
68477 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
68478 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
68479 */
68480 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
68481   Parse *pParse,    /* Parsing context */
68482   ExprList *pList,  /* List of field names to be indexed */
68483   int onError,      /* What to do with a uniqueness conflict */
68484   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
68485   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
68486 ){
68487   Table *pTab = pParse->pNewTable;
68488   char *zType = 0;
68489   int iCol = -1, i;
68490   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
68491   if( pTab->tabFlags & TF_HasPrimaryKey ){
68492     sqlite3ErrorMsg(pParse, 
68493       "table \"%s\" has more than one primary key", pTab->zName);
68494     goto primary_key_exit;
68495   }
68496   pTab->tabFlags |= TF_HasPrimaryKey;
68497   if( pList==0 ){
68498     iCol = pTab->nCol - 1;
68499     pTab->aCol[iCol].isPrimKey = 1;
68500   }else{
68501     for(i=0; i<pList->nExpr; i++){
68502       for(iCol=0; iCol<pTab->nCol; iCol++){
68503         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
68504           break;
68505         }
68506       }
68507       if( iCol<pTab->nCol ){
68508         pTab->aCol[iCol].isPrimKey = 1;
68509       }
68510     }
68511     if( pList->nExpr>1 ) iCol = -1;
68512   }
68513   if( iCol>=0 && iCol<pTab->nCol ){
68514     zType = pTab->aCol[iCol].zType;
68515   }
68516   if( zType && sqlite3StrICmp(zType, "INTEGER")==0
68517         && sortOrder==SQLITE_SO_ASC ){
68518     pTab->iPKey = iCol;
68519     pTab->keyConf = (u8)onError;
68520     assert( autoInc==0 || autoInc==1 );
68521     pTab->tabFlags |= autoInc*TF_Autoincrement;
68522   }else if( autoInc ){
68523 #ifndef SQLITE_OMIT_AUTOINCREMENT
68524     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
68525        "INTEGER PRIMARY KEY");
68526 #endif
68527   }else{
68528     Index *p;
68529     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
68530     if( p ){
68531       p->autoIndex = 2;
68532     }
68533     pList = 0;
68534   }
68535
68536 primary_key_exit:
68537   sqlite3ExprListDelete(pParse->db, pList);
68538   return;
68539 }
68540
68541 /*
68542 ** Add a new CHECK constraint to the table currently under construction.
68543 */
68544 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
68545   Parse *pParse,    /* Parsing context */
68546   Expr *pCheckExpr  /* The check expression */
68547 ){
68548   sqlite3 *db = pParse->db;
68549 #ifndef SQLITE_OMIT_CHECK
68550   Table *pTab = pParse->pNewTable;
68551   if( pTab && !IN_DECLARE_VTAB ){
68552     pTab->pCheck = sqlite3ExprAnd(db, pTab->pCheck, pCheckExpr);
68553   }else
68554 #endif
68555   {
68556     sqlite3ExprDelete(db, pCheckExpr);
68557   }
68558 }
68559
68560 /*
68561 ** Set the collation function of the most recently parsed table column
68562 ** to the CollSeq given.
68563 */
68564 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
68565   Table *p;
68566   int i;
68567   char *zColl;              /* Dequoted name of collation sequence */
68568   sqlite3 *db;
68569
68570   if( (p = pParse->pNewTable)==0 ) return;
68571   i = p->nCol-1;
68572   db = pParse->db;
68573   zColl = sqlite3NameFromToken(db, pToken);
68574   if( !zColl ) return;
68575
68576   if( sqlite3LocateCollSeq(pParse, zColl) ){
68577     Index *pIdx;
68578     p->aCol[i].zColl = zColl;
68579   
68580     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
68581     ** then an index may have been created on this column before the
68582     ** collation type was added. Correct this if it is the case.
68583     */
68584     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
68585       assert( pIdx->nColumn==1 );
68586       if( pIdx->aiColumn[0]==i ){
68587         pIdx->azColl[0] = p->aCol[i].zColl;
68588       }
68589     }
68590   }else{
68591     sqlite3DbFree(db, zColl);
68592   }
68593 }
68594
68595 /*
68596 ** This function returns the collation sequence for database native text
68597 ** encoding identified by the string zName, length nName.
68598 **
68599 ** If the requested collation sequence is not available, or not available
68600 ** in the database native encoding, the collation factory is invoked to
68601 ** request it. If the collation factory does not supply such a sequence,
68602 ** and the sequence is available in another text encoding, then that is
68603 ** returned instead.
68604 **
68605 ** If no versions of the requested collations sequence are available, or
68606 ** another error occurs, NULL is returned and an error message written into
68607 ** pParse.
68608 **
68609 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
68610 ** invokes the collation factory if the named collation cannot be found
68611 ** and generates an error message.
68612 **
68613 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
68614 */
68615 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
68616   sqlite3 *db = pParse->db;
68617   u8 enc = ENC(db);
68618   u8 initbusy = db->init.busy;
68619   CollSeq *pColl;
68620
68621   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
68622   if( !initbusy && (!pColl || !pColl->xCmp) ){
68623     pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
68624     if( !pColl ){
68625       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
68626     }
68627   }
68628
68629   return pColl;
68630 }
68631
68632
68633 /*
68634 ** Generate code that will increment the schema cookie.
68635 **
68636 ** The schema cookie is used to determine when the schema for the
68637 ** database changes.  After each schema change, the cookie value
68638 ** changes.  When a process first reads the schema it records the
68639 ** cookie.  Thereafter, whenever it goes to access the database,
68640 ** it checks the cookie to make sure the schema has not changed
68641 ** since it was last read.
68642 **
68643 ** This plan is not completely bullet-proof.  It is possible for
68644 ** the schema to change multiple times and for the cookie to be
68645 ** set back to prior value.  But schema changes are infrequent
68646 ** and the probability of hitting the same cookie value is only
68647 ** 1 chance in 2^32.  So we're safe enough.
68648 */
68649 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
68650   int r1 = sqlite3GetTempReg(pParse);
68651   sqlite3 *db = pParse->db;
68652   Vdbe *v = pParse->pVdbe;
68653   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
68654   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
68655   sqlite3ReleaseTempReg(pParse, r1);
68656 }
68657
68658 /*
68659 ** Measure the number of characters needed to output the given
68660 ** identifier.  The number returned includes any quotes used
68661 ** but does not include the null terminator.
68662 **
68663 ** The estimate is conservative.  It might be larger that what is
68664 ** really needed.
68665 */
68666 static int identLength(const char *z){
68667   int n;
68668   for(n=0; *z; n++, z++){
68669     if( *z=='"' ){ n++; }
68670   }
68671   return n + 2;
68672 }
68673
68674 /*
68675 ** The first parameter is a pointer to an output buffer. The second 
68676 ** parameter is a pointer to an integer that contains the offset at
68677 ** which to write into the output buffer. This function copies the
68678 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
68679 ** to the specified offset in the buffer and updates *pIdx to refer
68680 ** to the first byte after the last byte written before returning.
68681 ** 
68682 ** If the string zSignedIdent consists entirely of alpha-numeric
68683 ** characters, does not begin with a digit and is not an SQL keyword,
68684 ** then it is copied to the output buffer exactly as it is. Otherwise,
68685 ** it is quoted using double-quotes.
68686 */
68687 static void identPut(char *z, int *pIdx, char *zSignedIdent){
68688   unsigned char *zIdent = (unsigned char*)zSignedIdent;
68689   int i, j, needQuote;
68690   i = *pIdx;
68691
68692   for(j=0; zIdent[j]; j++){
68693     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
68694   }
68695   needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j)!=TK_ID;
68696   if( !needQuote ){
68697     needQuote = zIdent[j];
68698   }
68699
68700   if( needQuote ) z[i++] = '"';
68701   for(j=0; zIdent[j]; j++){
68702     z[i++] = zIdent[j];
68703     if( zIdent[j]=='"' ) z[i++] = '"';
68704   }
68705   if( needQuote ) z[i++] = '"';
68706   z[i] = 0;
68707   *pIdx = i;
68708 }
68709
68710 /*
68711 ** Generate a CREATE TABLE statement appropriate for the given
68712 ** table.  Memory to hold the text of the statement is obtained
68713 ** from sqliteMalloc() and must be freed by the calling function.
68714 */
68715 static char *createTableStmt(sqlite3 *db, Table *p){
68716   int i, k, n;
68717   char *zStmt;
68718   char *zSep, *zSep2, *zEnd;
68719   Column *pCol;
68720   n = 0;
68721   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
68722     n += identLength(pCol->zName) + 5;
68723   }
68724   n += identLength(p->zName);
68725   if( n<50 ){ 
68726     zSep = "";
68727     zSep2 = ",";
68728     zEnd = ")";
68729   }else{
68730     zSep = "\n  ";
68731     zSep2 = ",\n  ";
68732     zEnd = "\n)";
68733   }
68734   n += 35 + 6*p->nCol;
68735   zStmt = sqlite3Malloc( n );
68736   if( zStmt==0 ){
68737     db->mallocFailed = 1;
68738     return 0;
68739   }
68740   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
68741   k = sqlite3Strlen30(zStmt);
68742   identPut(zStmt, &k, p->zName);
68743   zStmt[k++] = '(';
68744   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
68745     static const char * const azType[] = {
68746         /* SQLITE_AFF_TEXT    */ " TEXT",
68747         /* SQLITE_AFF_NONE    */ "",
68748         /* SQLITE_AFF_NUMERIC */ " NUM",
68749         /* SQLITE_AFF_INTEGER */ " INT",
68750         /* SQLITE_AFF_REAL    */ " REAL"
68751     };
68752     int len;
68753     const char *zType;
68754
68755     sqlite3_snprintf(n-k, &zStmt[k], zSep);
68756     k += sqlite3Strlen30(&zStmt[k]);
68757     zSep = zSep2;
68758     identPut(zStmt, &k, pCol->zName);
68759     assert( pCol->affinity-SQLITE_AFF_TEXT >= 0 );
68760     assert( pCol->affinity-SQLITE_AFF_TEXT < sizeof(azType)/sizeof(azType[0]) );
68761     testcase( pCol->affinity==SQLITE_AFF_TEXT );
68762     testcase( pCol->affinity==SQLITE_AFF_NONE );
68763     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
68764     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
68765     testcase( pCol->affinity==SQLITE_AFF_REAL );
68766     
68767     zType = azType[pCol->affinity - SQLITE_AFF_TEXT];
68768     len = sqlite3Strlen30(zType);
68769     assert( pCol->affinity==SQLITE_AFF_NONE 
68770             || pCol->affinity==sqlite3AffinityType(zType) );
68771     memcpy(&zStmt[k], zType, len);
68772     k += len;
68773     assert( k<=n );
68774   }
68775   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
68776   return zStmt;
68777 }
68778
68779 /*
68780 ** This routine is called to report the final ")" that terminates
68781 ** a CREATE TABLE statement.
68782 **
68783 ** The table structure that other action routines have been building
68784 ** is added to the internal hash tables, assuming no errors have
68785 ** occurred.
68786 **
68787 ** An entry for the table is made in the master table on disk, unless
68788 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
68789 ** it means we are reading the sqlite_master table because we just
68790 ** connected to the database or because the sqlite_master table has
68791 ** recently changed, so the entry for this table already exists in
68792 ** the sqlite_master table.  We do not want to create it again.
68793 **
68794 ** If the pSelect argument is not NULL, it means that this routine
68795 ** was called to create a table generated from a 
68796 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
68797 ** the new table will match the result set of the SELECT.
68798 */
68799 SQLITE_PRIVATE void sqlite3EndTable(
68800   Parse *pParse,          /* Parse context */
68801   Token *pCons,           /* The ',' token after the last column defn. */
68802   Token *pEnd,            /* The final ')' token in the CREATE TABLE */
68803   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
68804 ){
68805   Table *p;
68806   sqlite3 *db = pParse->db;
68807   int iDb;
68808
68809   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
68810     return;
68811   }
68812   p = pParse->pNewTable;
68813   if( p==0 ) return;
68814
68815   assert( !db->init.busy || !pSelect );
68816
68817   iDb = sqlite3SchemaToIndex(db, p->pSchema);
68818
68819 #ifndef SQLITE_OMIT_CHECK
68820   /* Resolve names in all CHECK constraint expressions.
68821   */
68822   if( p->pCheck ){
68823     SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
68824     NameContext sNC;                /* Name context for pParse->pNewTable */
68825
68826     memset(&sNC, 0, sizeof(sNC));
68827     memset(&sSrc, 0, sizeof(sSrc));
68828     sSrc.nSrc = 1;
68829     sSrc.a[0].zName = p->zName;
68830     sSrc.a[0].pTab = p;
68831     sSrc.a[0].iCursor = -1;
68832     sNC.pParse = pParse;
68833     sNC.pSrcList = &sSrc;
68834     sNC.isCheck = 1;
68835     if( sqlite3ResolveExprNames(&sNC, p->pCheck) ){
68836       return;
68837     }
68838   }
68839 #endif /* !defined(SQLITE_OMIT_CHECK) */
68840
68841   /* If the db->init.busy is 1 it means we are reading the SQL off the
68842   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
68843   ** So do not write to the disk again.  Extract the root page number
68844   ** for the table from the db->init.newTnum field.  (The page number
68845   ** should have been put there by the sqliteOpenCb routine.)
68846   */
68847   if( db->init.busy ){
68848     p->tnum = db->init.newTnum;
68849   }
68850
68851   /* If not initializing, then create a record for the new table
68852   ** in the SQLITE_MASTER table of the database.
68853   **
68854   ** If this is a TEMPORARY table, write the entry into the auxiliary
68855   ** file instead of into the main database file.
68856   */
68857   if( !db->init.busy ){
68858     int n;
68859     Vdbe *v;
68860     char *zType;    /* "view" or "table" */
68861     char *zType2;   /* "VIEW" or "TABLE" */
68862     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
68863
68864     v = sqlite3GetVdbe(pParse);
68865     if( NEVER(v==0) ) return;
68866
68867     sqlite3VdbeAddOp1(v, OP_Close, 0);
68868
68869     /* 
68870     ** Initialize zType for the new view or table.
68871     */
68872     if( p->pSelect==0 ){
68873       /* A regular table */
68874       zType = "table";
68875       zType2 = "TABLE";
68876 #ifndef SQLITE_OMIT_VIEW
68877     }else{
68878       /* A view */
68879       zType = "view";
68880       zType2 = "VIEW";
68881 #endif
68882     }
68883
68884     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
68885     ** statement to populate the new table. The root-page number for the
68886     ** new table is in register pParse->regRoot.
68887     **
68888     ** Once the SELECT has been coded by sqlite3Select(), it is in a
68889     ** suitable state to query for the column names and types to be used
68890     ** by the new table.
68891     **
68892     ** A shared-cache write-lock is not required to write to the new table,
68893     ** as a schema-lock must have already been obtained to create it. Since
68894     ** a schema-lock excludes all other database users, the write-lock would
68895     ** be redundant.
68896     */
68897     if( pSelect ){
68898       SelectDest dest;
68899       Table *pSelTab;
68900
68901       assert(pParse->nTab==1);
68902       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
68903       sqlite3VdbeChangeP5(v, 1);
68904       pParse->nTab = 2;
68905       sqlite3SelectDestInit(&dest, SRT_Table, 1);
68906       sqlite3Select(pParse, pSelect, &dest);
68907       sqlite3VdbeAddOp1(v, OP_Close, 1);
68908       if( pParse->nErr==0 ){
68909         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
68910         if( pSelTab==0 ) return;
68911         assert( p->aCol==0 );
68912         p->nCol = pSelTab->nCol;
68913         p->aCol = pSelTab->aCol;
68914         pSelTab->nCol = 0;
68915         pSelTab->aCol = 0;
68916         sqlite3DeleteTable(pSelTab);
68917       }
68918     }
68919
68920     /* Compute the complete text of the CREATE statement */
68921     if( pSelect ){
68922       zStmt = createTableStmt(db, p);
68923     }else{
68924       n = (int)(pEnd->z - pParse->sNameToken.z) + 1;
68925       zStmt = sqlite3MPrintf(db, 
68926           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
68927       );
68928     }
68929
68930     /* A slot for the record has already been allocated in the 
68931     ** SQLITE_MASTER table.  We just need to update that slot with all
68932     ** the information we've collected.
68933     */
68934     sqlite3NestedParse(pParse,
68935       "UPDATE %Q.%s "
68936          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
68937        "WHERE rowid=#%d",
68938       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
68939       zType,
68940       p->zName,
68941       p->zName,
68942       pParse->regRoot,
68943       zStmt,
68944       pParse->regRowid
68945     );
68946     sqlite3DbFree(db, zStmt);
68947     sqlite3ChangeCookie(pParse, iDb);
68948
68949 #ifndef SQLITE_OMIT_AUTOINCREMENT
68950     /* Check to see if we need to create an sqlite_sequence table for
68951     ** keeping track of autoincrement keys.
68952     */
68953     if( p->tabFlags & TF_Autoincrement ){
68954       Db *pDb = &db->aDb[iDb];
68955       if( pDb->pSchema->pSeqTab==0 ){
68956         sqlite3NestedParse(pParse,
68957           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
68958           pDb->zName
68959         );
68960       }
68961     }
68962 #endif
68963
68964     /* Reparse everything to update our internal data structures */
68965     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
68966         sqlite3MPrintf(db, "tbl_name='%q'",p->zName), P4_DYNAMIC);
68967   }
68968
68969
68970   /* Add the table to the in-memory representation of the database.
68971   */
68972   if( db->init.busy ){
68973     Table *pOld;
68974     Schema *pSchema = p->pSchema;
68975     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName,
68976                              sqlite3Strlen30(p->zName),p);
68977     if( pOld ){
68978       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
68979       db->mallocFailed = 1;
68980       return;
68981     }
68982     pParse->pNewTable = 0;
68983     db->nTable++;
68984     db->flags |= SQLITE_InternChanges;
68985
68986 #ifndef SQLITE_OMIT_ALTERTABLE
68987     if( !p->pSelect ){
68988       const char *zName = (const char *)pParse->sNameToken.z;
68989       int nName;
68990       assert( !pSelect && pCons && pEnd );
68991       if( pCons->z==0 ){
68992         pCons = pEnd;
68993       }
68994       nName = (int)((const char *)pCons->z - zName);
68995       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
68996     }
68997 #endif
68998   }
68999 }
69000
69001 #ifndef SQLITE_OMIT_VIEW
69002 /*
69003 ** The parser calls this routine in order to create a new VIEW
69004 */
69005 SQLITE_PRIVATE void sqlite3CreateView(
69006   Parse *pParse,     /* The parsing context */
69007   Token *pBegin,     /* The CREATE token that begins the statement */
69008   Token *pName1,     /* The token that holds the name of the view */
69009   Token *pName2,     /* The token that holds the name of the view */
69010   Select *pSelect,   /* A SELECT statement that will become the new view */
69011   int isTemp,        /* TRUE for a TEMPORARY view */
69012   int noErr          /* Suppress error messages if VIEW already exists */
69013 ){
69014   Table *p;
69015   int n;
69016   const char *z;
69017   Token sEnd;
69018   DbFixer sFix;
69019   Token *pName;
69020   int iDb;
69021   sqlite3 *db = pParse->db;
69022
69023   if( pParse->nVar>0 ){
69024     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
69025     sqlite3SelectDelete(db, pSelect);
69026     return;
69027   }
69028   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
69029   p = pParse->pNewTable;
69030   if( p==0 ){
69031     sqlite3SelectDelete(db, pSelect);
69032     return;
69033   }
69034   assert( pParse->nErr==0 ); /* If sqlite3StartTable return non-NULL then
69035                              ** there could not have been an error */
69036   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
69037   iDb = sqlite3SchemaToIndex(db, p->pSchema);
69038   if( sqlite3FixInit(&sFix, pParse, iDb, "view", pName)
69039     && sqlite3FixSelect(&sFix, pSelect)
69040   ){
69041     sqlite3SelectDelete(db, pSelect);
69042     return;
69043   }
69044
69045   /* Make a copy of the entire SELECT statement that defines the view.
69046   ** This will force all the Expr.token.z values to be dynamically
69047   ** allocated rather than point to the input string - which means that
69048   ** they will persist after the current sqlite3_exec() call returns.
69049   */
69050   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
69051   sqlite3SelectDelete(db, pSelect);
69052   if( db->mallocFailed ){
69053     return;
69054   }
69055   if( !db->init.busy ){
69056     sqlite3ViewGetColumnNames(pParse, p);
69057   }
69058
69059   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
69060   ** the end.
69061   */
69062   sEnd = pParse->sLastToken;
69063   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
69064     sEnd.z += sEnd.n;
69065   }
69066   sEnd.n = 0;
69067   n = (int)(sEnd.z - pBegin->z);
69068   z = pBegin->z;
69069   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
69070   sEnd.z = &z[n-1];
69071   sEnd.n = 1;
69072
69073   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
69074   sqlite3EndTable(pParse, 0, &sEnd, 0);
69075   return;
69076 }
69077 #endif /* SQLITE_OMIT_VIEW */
69078
69079 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
69080 /*
69081 ** The Table structure pTable is really a VIEW.  Fill in the names of
69082 ** the columns of the view in the pTable structure.  Return the number
69083 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
69084 */
69085 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
69086   Table *pSelTab;   /* A fake table from which we get the result set */
69087   Select *pSel;     /* Copy of the SELECT that implements the view */
69088   int nErr = 0;     /* Number of errors encountered */
69089   int n;            /* Temporarily holds the number of cursors assigned */
69090   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
69091   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
69092
69093   assert( pTable );
69094
69095 #ifndef SQLITE_OMIT_VIRTUALTABLE
69096   if( sqlite3VtabCallConnect(pParse, pTable) ){
69097     return SQLITE_ERROR;
69098   }
69099   if( IsVirtual(pTable) ) return 0;
69100 #endif
69101
69102 #ifndef SQLITE_OMIT_VIEW
69103   /* A positive nCol means the columns names for this view are
69104   ** already known.
69105   */
69106   if( pTable->nCol>0 ) return 0;
69107
69108   /* A negative nCol is a special marker meaning that we are currently
69109   ** trying to compute the column names.  If we enter this routine with
69110   ** a negative nCol, it means two or more views form a loop, like this:
69111   **
69112   **     CREATE VIEW one AS SELECT * FROM two;
69113   **     CREATE VIEW two AS SELECT * FROM one;
69114   **
69115   ** Actually, the error above is now caught prior to reaching this point.
69116   ** But the following test is still important as it does come up
69117   ** in the following:
69118   ** 
69119   **     CREATE TABLE main.ex1(a);
69120   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
69121   **     SELECT * FROM temp.ex1;
69122   */
69123   if( pTable->nCol<0 ){
69124     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
69125     return 1;
69126   }
69127   assert( pTable->nCol>=0 );
69128
69129   /* If we get this far, it means we need to compute the table names.
69130   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
69131   ** "*" elements in the results set of the view and will assign cursors
69132   ** to the elements of the FROM clause.  But we do not want these changes
69133   ** to be permanent.  So the computation is done on a copy of the SELECT
69134   ** statement that defines the view.
69135   */
69136   assert( pTable->pSelect );
69137   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
69138   if( pSel ){
69139     u8 enableLookaside = db->lookaside.bEnabled;
69140     n = pParse->nTab;
69141     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
69142     pTable->nCol = -1;
69143     db->lookaside.bEnabled = 0;
69144 #ifndef SQLITE_OMIT_AUTHORIZATION
69145     xAuth = db->xAuth;
69146     db->xAuth = 0;
69147     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
69148     db->xAuth = xAuth;
69149 #else
69150     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
69151 #endif
69152     db->lookaside.bEnabled = enableLookaside;
69153     pParse->nTab = n;
69154     if( pSelTab ){
69155       assert( pTable->aCol==0 );
69156       pTable->nCol = pSelTab->nCol;
69157       pTable->aCol = pSelTab->aCol;
69158       pSelTab->nCol = 0;
69159       pSelTab->aCol = 0;
69160       sqlite3DeleteTable(pSelTab);
69161       pTable->pSchema->flags |= DB_UnresetViews;
69162     }else{
69163       pTable->nCol = 0;
69164       nErr++;
69165     }
69166     sqlite3SelectDelete(db, pSel);
69167   } else {
69168     nErr++;
69169   }
69170 #endif /* SQLITE_OMIT_VIEW */
69171   return nErr;  
69172 }
69173 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
69174
69175 #ifndef SQLITE_OMIT_VIEW
69176 /*
69177 ** Clear the column names from every VIEW in database idx.
69178 */
69179 static void sqliteViewResetAll(sqlite3 *db, int idx){
69180   HashElem *i;
69181   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
69182   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
69183     Table *pTab = sqliteHashData(i);
69184     if( pTab->pSelect ){
69185       sqliteResetColumnNames(pTab);
69186     }
69187   }
69188   DbClearProperty(db, idx, DB_UnresetViews);
69189 }
69190 #else
69191 # define sqliteViewResetAll(A,B)
69192 #endif /* SQLITE_OMIT_VIEW */
69193
69194 /*
69195 ** This function is called by the VDBE to adjust the internal schema
69196 ** used by SQLite when the btree layer moves a table root page. The
69197 ** root-page of a table or index in database iDb has changed from iFrom
69198 ** to iTo.
69199 **
69200 ** Ticket #1728:  The symbol table might still contain information
69201 ** on tables and/or indices that are the process of being deleted.
69202 ** If you are unlucky, one of those deleted indices or tables might
69203 ** have the same rootpage number as the real table or index that is
69204 ** being moved.  So we cannot stop searching after the first match 
69205 ** because the first match might be for one of the deleted indices
69206 ** or tables and not the table/index that is actually being moved.
69207 ** We must continue looping until all tables and indices with
69208 ** rootpage==iFrom have been converted to have a rootpage of iTo
69209 ** in order to be certain that we got the right one.
69210 */
69211 #ifndef SQLITE_OMIT_AUTOVACUUM
69212 SQLITE_PRIVATE void sqlite3RootPageMoved(Db *pDb, int iFrom, int iTo){
69213   HashElem *pElem;
69214   Hash *pHash;
69215
69216   pHash = &pDb->pSchema->tblHash;
69217   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
69218     Table *pTab = sqliteHashData(pElem);
69219     if( pTab->tnum==iFrom ){
69220       pTab->tnum = iTo;
69221     }
69222   }
69223   pHash = &pDb->pSchema->idxHash;
69224   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
69225     Index *pIdx = sqliteHashData(pElem);
69226     if( pIdx->tnum==iFrom ){
69227       pIdx->tnum = iTo;
69228     }
69229   }
69230 }
69231 #endif
69232
69233 /*
69234 ** Write code to erase the table with root-page iTable from database iDb.
69235 ** Also write code to modify the sqlite_master table and internal schema
69236 ** if a root-page of another table is moved by the btree-layer whilst
69237 ** erasing iTable (this can happen with an auto-vacuum database).
69238 */ 
69239 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
69240   Vdbe *v = sqlite3GetVdbe(pParse);
69241   int r1 = sqlite3GetTempReg(pParse);
69242   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
69243   sqlite3MayAbort(pParse);
69244 #ifndef SQLITE_OMIT_AUTOVACUUM
69245   /* OP_Destroy stores an in integer r1. If this integer
69246   ** is non-zero, then it is the root page number of a table moved to
69247   ** location iTable. The following code modifies the sqlite_master table to
69248   ** reflect this.
69249   **
69250   ** The "#NNN" in the SQL is a special constant that means whatever value
69251   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
69252   ** token for additional information.
69253   */
69254   sqlite3NestedParse(pParse, 
69255      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
69256      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
69257 #endif
69258   sqlite3ReleaseTempReg(pParse, r1);
69259 }
69260
69261 /*
69262 ** Write VDBE code to erase table pTab and all associated indices on disk.
69263 ** Code to update the sqlite_master tables and internal schema definitions
69264 ** in case a root-page belonging to another table is moved by the btree layer
69265 ** is also added (this can happen with an auto-vacuum database).
69266 */
69267 static void destroyTable(Parse *pParse, Table *pTab){
69268 #ifdef SQLITE_OMIT_AUTOVACUUM
69269   Index *pIdx;
69270   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
69271   destroyRootPage(pParse, pTab->tnum, iDb);
69272   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
69273     destroyRootPage(pParse, pIdx->tnum, iDb);
69274   }
69275 #else
69276   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
69277   ** is not defined), then it is important to call OP_Destroy on the
69278   ** table and index root-pages in order, starting with the numerically 
69279   ** largest root-page number. This guarantees that none of the root-pages
69280   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
69281   ** following were coded:
69282   **
69283   ** OP_Destroy 4 0
69284   ** ...
69285   ** OP_Destroy 5 0
69286   **
69287   ** and root page 5 happened to be the largest root-page number in the
69288   ** database, then root page 5 would be moved to page 4 by the 
69289   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
69290   ** a free-list page.
69291   */
69292   int iTab = pTab->tnum;
69293   int iDestroyed = 0;
69294
69295   while( 1 ){
69296     Index *pIdx;
69297     int iLargest = 0;
69298
69299     if( iDestroyed==0 || iTab<iDestroyed ){
69300       iLargest = iTab;
69301     }
69302     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
69303       int iIdx = pIdx->tnum;
69304       assert( pIdx->pSchema==pTab->pSchema );
69305       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
69306         iLargest = iIdx;
69307       }
69308     }
69309     if( iLargest==0 ){
69310       return;
69311     }else{
69312       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
69313       destroyRootPage(pParse, iLargest, iDb);
69314       iDestroyed = iLargest;
69315     }
69316   }
69317 #endif
69318 }
69319
69320 /*
69321 ** This routine is called to do the work of a DROP TABLE statement.
69322 ** pName is the name of the table to be dropped.
69323 */
69324 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
69325   Table *pTab;
69326   Vdbe *v;
69327   sqlite3 *db = pParse->db;
69328   int iDb;
69329
69330   if( db->mallocFailed ){
69331     goto exit_drop_table;
69332   }
69333   assert( pParse->nErr==0 );
69334   assert( pName->nSrc==1 );
69335   if( noErr ) db->suppressErr++;
69336   pTab = sqlite3LocateTable(pParse, isView, 
69337                             pName->a[0].zName, pName->a[0].zDatabase);
69338   if( noErr ) db->suppressErr--;
69339
69340   if( pTab==0 ){
69341     goto exit_drop_table;
69342   }
69343   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
69344   assert( iDb>=0 && iDb<db->nDb );
69345
69346   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
69347   ** it is initialized.
69348   */
69349   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
69350     goto exit_drop_table;
69351   }
69352 #ifndef SQLITE_OMIT_AUTHORIZATION
69353   {
69354     int code;
69355     const char *zTab = SCHEMA_TABLE(iDb);
69356     const char *zDb = db->aDb[iDb].zName;
69357     const char *zArg2 = 0;
69358     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
69359       goto exit_drop_table;
69360     }
69361     if( isView ){
69362       if( !OMIT_TEMPDB && iDb==1 ){
69363         code = SQLITE_DROP_TEMP_VIEW;
69364       }else{
69365         code = SQLITE_DROP_VIEW;
69366       }
69367 #ifndef SQLITE_OMIT_VIRTUALTABLE
69368     }else if( IsVirtual(pTab) ){
69369       code = SQLITE_DROP_VTABLE;
69370       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
69371 #endif
69372     }else{
69373       if( !OMIT_TEMPDB && iDb==1 ){
69374         code = SQLITE_DROP_TEMP_TABLE;
69375       }else{
69376         code = SQLITE_DROP_TABLE;
69377       }
69378     }
69379     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
69380       goto exit_drop_table;
69381     }
69382     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
69383       goto exit_drop_table;
69384     }
69385   }
69386 #endif
69387   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
69388     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
69389     goto exit_drop_table;
69390   }
69391
69392 #ifndef SQLITE_OMIT_VIEW
69393   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
69394   ** on a table.
69395   */
69396   if( isView && pTab->pSelect==0 ){
69397     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
69398     goto exit_drop_table;
69399   }
69400   if( !isView && pTab->pSelect ){
69401     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
69402     goto exit_drop_table;
69403   }
69404 #endif
69405
69406   /* Generate code to remove the table from the master table
69407   ** on disk.
69408   */
69409   v = sqlite3GetVdbe(pParse);
69410   if( v ){
69411     Trigger *pTrigger;
69412     Db *pDb = &db->aDb[iDb];
69413     sqlite3BeginWriteOperation(pParse, 1, iDb);
69414
69415 #ifndef SQLITE_OMIT_VIRTUALTABLE
69416     if( IsVirtual(pTab) ){
69417       sqlite3VdbeAddOp0(v, OP_VBegin);
69418     }
69419 #endif
69420     sqlite3FkDropTable(pParse, pName, pTab);
69421
69422     /* Drop all triggers associated with the table being dropped. Code
69423     ** is generated to remove entries from sqlite_master and/or
69424     ** sqlite_temp_master if required.
69425     */
69426     pTrigger = sqlite3TriggerList(pParse, pTab);
69427     while( pTrigger ){
69428       assert( pTrigger->pSchema==pTab->pSchema || 
69429           pTrigger->pSchema==db->aDb[1].pSchema );
69430       sqlite3DropTriggerPtr(pParse, pTrigger);
69431       pTrigger = pTrigger->pNext;
69432     }
69433
69434 #ifndef SQLITE_OMIT_AUTOINCREMENT
69435     /* Remove any entries of the sqlite_sequence table associated with
69436     ** the table being dropped. This is done before the table is dropped
69437     ** at the btree level, in case the sqlite_sequence table needs to
69438     ** move as a result of the drop (can happen in auto-vacuum mode).
69439     */
69440     if( pTab->tabFlags & TF_Autoincrement ){
69441       sqlite3NestedParse(pParse,
69442         "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
69443         pDb->zName, pTab->zName
69444       );
69445     }
69446 #endif
69447
69448     /* Drop all SQLITE_MASTER table and index entries that refer to the
69449     ** table. The program name loops through the master table and deletes
69450     ** every row that refers to a table of the same name as the one being
69451     ** dropped. Triggers are handled seperately because a trigger can be
69452     ** created in the temp database that refers to a table in another
69453     ** database.
69454     */
69455     sqlite3NestedParse(pParse, 
69456         "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
69457         pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
69458
69459     /* Drop any statistics from the sqlite_stat1 table, if it exists */
69460     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
69461       sqlite3NestedParse(pParse,
69462         "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb->zName, pTab->zName
69463       );
69464     }
69465
69466     if( !isView && !IsVirtual(pTab) ){
69467       destroyTable(pParse, pTab);
69468     }
69469
69470     /* Remove the table entry from SQLite's internal schema and modify
69471     ** the schema cookie.
69472     */
69473     if( IsVirtual(pTab) ){
69474       sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
69475     }
69476     sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
69477     sqlite3ChangeCookie(pParse, iDb);
69478   }
69479   sqliteViewResetAll(db, iDb);
69480
69481 exit_drop_table:
69482   sqlite3SrcListDelete(db, pName);
69483 }
69484
69485 /*
69486 ** This routine is called to create a new foreign key on the table
69487 ** currently under construction.  pFromCol determines which columns
69488 ** in the current table point to the foreign key.  If pFromCol==0 then
69489 ** connect the key to the last column inserted.  pTo is the name of
69490 ** the table referred to.  pToCol is a list of tables in the other
69491 ** pTo table that the foreign key points to.  flags contains all
69492 ** information about the conflict resolution algorithms specified
69493 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
69494 **
69495 ** An FKey structure is created and added to the table currently
69496 ** under construction in the pParse->pNewTable field.
69497 **
69498 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
69499 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
69500 */
69501 SQLITE_PRIVATE void sqlite3CreateForeignKey(
69502   Parse *pParse,       /* Parsing context */
69503   ExprList *pFromCol,  /* Columns in this table that point to other table */
69504   Token *pTo,          /* Name of the other table */
69505   ExprList *pToCol,    /* Columns in the other table */
69506   int flags            /* Conflict resolution algorithms. */
69507 ){
69508   sqlite3 *db = pParse->db;
69509 #ifndef SQLITE_OMIT_FOREIGN_KEY
69510   FKey *pFKey = 0;
69511   FKey *pNextTo;
69512   Table *p = pParse->pNewTable;
69513   int nByte;
69514   int i;
69515   int nCol;
69516   char *z;
69517
69518   assert( pTo!=0 );
69519   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
69520   if( pFromCol==0 ){
69521     int iCol = p->nCol-1;
69522     if( NEVER(iCol<0) ) goto fk_end;
69523     if( pToCol && pToCol->nExpr!=1 ){
69524       sqlite3ErrorMsg(pParse, "foreign key on %s"
69525          " should reference only one column of table %T",
69526          p->aCol[iCol].zName, pTo);
69527       goto fk_end;
69528     }
69529     nCol = 1;
69530   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
69531     sqlite3ErrorMsg(pParse,
69532         "number of columns in foreign key does not match the number of "
69533         "columns in the referenced table");
69534     goto fk_end;
69535   }else{
69536     nCol = pFromCol->nExpr;
69537   }
69538   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
69539   if( pToCol ){
69540     for(i=0; i<pToCol->nExpr; i++){
69541       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
69542     }
69543   }
69544   pFKey = sqlite3DbMallocZero(db, nByte );
69545   if( pFKey==0 ){
69546     goto fk_end;
69547   }
69548   pFKey->pFrom = p;
69549   pFKey->pNextFrom = p->pFKey;
69550   z = (char*)&pFKey->aCol[nCol];
69551   pFKey->zTo = z;
69552   memcpy(z, pTo->z, pTo->n);
69553   z[pTo->n] = 0;
69554   sqlite3Dequote(z);
69555   z += pTo->n+1;
69556   pFKey->nCol = nCol;
69557   if( pFromCol==0 ){
69558     pFKey->aCol[0].iFrom = p->nCol-1;
69559   }else{
69560     for(i=0; i<nCol; i++){
69561       int j;
69562       for(j=0; j<p->nCol; j++){
69563         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
69564           pFKey->aCol[i].iFrom = j;
69565           break;
69566         }
69567       }
69568       if( j>=p->nCol ){
69569         sqlite3ErrorMsg(pParse, 
69570           "unknown column \"%s\" in foreign key definition", 
69571           pFromCol->a[i].zName);
69572         goto fk_end;
69573       }
69574     }
69575   }
69576   if( pToCol ){
69577     for(i=0; i<nCol; i++){
69578       int n = sqlite3Strlen30(pToCol->a[i].zName);
69579       pFKey->aCol[i].zCol = z;
69580       memcpy(z, pToCol->a[i].zName, n);
69581       z[n] = 0;
69582       z += n+1;
69583     }
69584   }
69585   pFKey->isDeferred = 0;
69586   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
69587   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
69588
69589   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
69590       pFKey->zTo, sqlite3Strlen30(pFKey->zTo), (void *)pFKey
69591   );
69592   if( pNextTo==pFKey ){
69593     db->mallocFailed = 1;
69594     goto fk_end;
69595   }
69596   if( pNextTo ){
69597     assert( pNextTo->pPrevTo==0 );
69598     pFKey->pNextTo = pNextTo;
69599     pNextTo->pPrevTo = pFKey;
69600   }
69601
69602   /* Link the foreign key to the table as the last step.
69603   */
69604   p->pFKey = pFKey;
69605   pFKey = 0;
69606
69607 fk_end:
69608   sqlite3DbFree(db, pFKey);
69609 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
69610   sqlite3ExprListDelete(db, pFromCol);
69611   sqlite3ExprListDelete(db, pToCol);
69612 }
69613
69614 /*
69615 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
69616 ** clause is seen as part of a foreign key definition.  The isDeferred
69617 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
69618 ** The behavior of the most recently created foreign key is adjusted
69619 ** accordingly.
69620 */
69621 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
69622 #ifndef SQLITE_OMIT_FOREIGN_KEY
69623   Table *pTab;
69624   FKey *pFKey;
69625   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
69626   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
69627   pFKey->isDeferred = (u8)isDeferred;
69628 #endif
69629 }
69630
69631 /*
69632 ** Generate code that will erase and refill index *pIdx.  This is
69633 ** used to initialize a newly created index or to recompute the
69634 ** content of an index in response to a REINDEX command.
69635 **
69636 ** if memRootPage is not negative, it means that the index is newly
69637 ** created.  The register specified by memRootPage contains the
69638 ** root page number of the index.  If memRootPage is negative, then
69639 ** the index already exists and must be cleared before being refilled and
69640 ** the root page number of the index is taken from pIndex->tnum.
69641 */
69642 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
69643   Table *pTab = pIndex->pTable;  /* The table that is indexed */
69644   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
69645   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
69646   int addr1;                     /* Address of top of loop */
69647   int tnum;                      /* Root page of index */
69648   Vdbe *v;                       /* Generate code into this virtual machine */
69649   KeyInfo *pKey;                 /* KeyInfo for index */
69650   int regIdxKey;                 /* Registers containing the index key */
69651   int regRecord;                 /* Register holding assemblied index record */
69652   sqlite3 *db = pParse->db;      /* The database connection */
69653   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
69654
69655 #ifndef SQLITE_OMIT_AUTHORIZATION
69656   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
69657       db->aDb[iDb].zName ) ){
69658     return;
69659   }
69660 #endif
69661
69662   /* Require a write-lock on the table to perform this operation */
69663   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
69664
69665   v = sqlite3GetVdbe(pParse);
69666   if( v==0 ) return;
69667   if( memRootPage>=0 ){
69668     tnum = memRootPage;
69669   }else{
69670     tnum = pIndex->tnum;
69671     sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
69672   }
69673   pKey = sqlite3IndexKeyinfo(pParse, pIndex);
69674   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
69675                     (char *)pKey, P4_KEYINFO_HANDOFF);
69676   if( memRootPage>=0 ){
69677     sqlite3VdbeChangeP5(v, 1);
69678   }
69679   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
69680   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
69681   regRecord = sqlite3GetTempReg(pParse);
69682   regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, 1);
69683   if( pIndex->onError!=OE_None ){
69684     const int regRowid = regIdxKey + pIndex->nColumn;
69685     const int j2 = sqlite3VdbeCurrentAddr(v) + 2;
69686     void * const pRegKey = SQLITE_INT_TO_PTR(regIdxKey);
69687
69688     /* The registers accessed by the OP_IsUnique opcode were allocated
69689     ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
69690     ** call above. Just before that function was freed they were released
69691     ** (made available to the compiler for reuse) using 
69692     ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
69693     ** opcode use the values stored within seems dangerous. However, since
69694     ** we can be sure that no other temp registers have been allocated
69695     ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
69696     */
69697     sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
69698     sqlite3HaltConstraint(
69699         pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
69700   }
69701   sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
69702   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
69703   sqlite3ReleaseTempReg(pParse, regRecord);
69704   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1);
69705   sqlite3VdbeJumpHere(v, addr1);
69706   sqlite3VdbeAddOp1(v, OP_Close, iTab);
69707   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
69708 }
69709
69710 /*
69711 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
69712 ** and pTblList is the name of the table that is to be indexed.  Both will 
69713 ** be NULL for a primary key or an index that is created to satisfy a
69714 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
69715 ** as the table to be indexed.  pParse->pNewTable is a table that is
69716 ** currently being constructed by a CREATE TABLE statement.
69717 **
69718 ** pList is a list of columns to be indexed.  pList will be NULL if this
69719 ** is a primary key or unique-constraint on the most recent column added
69720 ** to the table currently under construction.  
69721 **
69722 ** If the index is created successfully, return a pointer to the new Index
69723 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
69724 ** as the tables primary key (Index.autoIndex==2).
69725 */
69726 SQLITE_PRIVATE Index *sqlite3CreateIndex(
69727   Parse *pParse,     /* All information about this parse */
69728   Token *pName1,     /* First part of index name. May be NULL */
69729   Token *pName2,     /* Second part of index name. May be NULL */
69730   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
69731   ExprList *pList,   /* A list of columns to be indexed */
69732   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
69733   Token *pStart,     /* The CREATE token that begins this statement */
69734   Token *pEnd,       /* The ")" that closes the CREATE INDEX statement */
69735   int sortOrder,     /* Sort order of primary key when pList==NULL */
69736   int ifNotExist     /* Omit error if index already exists */
69737 ){
69738   Index *pRet = 0;     /* Pointer to return */
69739   Table *pTab = 0;     /* Table to be indexed */
69740   Index *pIndex = 0;   /* The index to be created */
69741   char *zName = 0;     /* Name of the index */
69742   int nName;           /* Number of characters in zName */
69743   int i, j;
69744   Token nullId;        /* Fake token for an empty ID list */
69745   DbFixer sFix;        /* For assigning database names to pTable */
69746   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
69747   sqlite3 *db = pParse->db;
69748   Db *pDb;             /* The specific table containing the indexed database */
69749   int iDb;             /* Index of the database that is being written */
69750   Token *pName = 0;    /* Unqualified name of the index to create */
69751   struct ExprList_item *pListItem; /* For looping over pList */
69752   int nCol;
69753   int nExtra = 0;
69754   char *zExtra;
69755
69756   assert( pStart==0 || pEnd!=0 ); /* pEnd must be non-NULL if pStart is */
69757   assert( pParse->nErr==0 );      /* Never called with prior errors */
69758   if( db->mallocFailed || IN_DECLARE_VTAB ){
69759     goto exit_create_index;
69760   }
69761   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
69762     goto exit_create_index;
69763   }
69764
69765   /*
69766   ** Find the table that is to be indexed.  Return early if not found.
69767   */
69768   if( pTblName!=0 ){
69769
69770     /* Use the two-part index name to determine the database 
69771     ** to search for the table. 'Fix' the table name to this db
69772     ** before looking up the table.
69773     */
69774     assert( pName1 && pName2 );
69775     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
69776     if( iDb<0 ) goto exit_create_index;
69777
69778 #ifndef SQLITE_OMIT_TEMPDB
69779     /* If the index name was unqualified, check if the the table
69780     ** is a temp table. If so, set the database to 1. Do not do this
69781     ** if initialising a database schema.
69782     */
69783     if( !db->init.busy ){
69784       pTab = sqlite3SrcListLookup(pParse, pTblName);
69785       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
69786         iDb = 1;
69787       }
69788     }
69789 #endif
69790
69791     if( sqlite3FixInit(&sFix, pParse, iDb, "index", pName) &&
69792         sqlite3FixSrcList(&sFix, pTblName)
69793     ){
69794       /* Because the parser constructs pTblName from a single identifier,
69795       ** sqlite3FixSrcList can never fail. */
69796       assert(0);
69797     }
69798     pTab = sqlite3LocateTable(pParse, 0, pTblName->a[0].zName, 
69799         pTblName->a[0].zDatabase);
69800     if( !pTab || db->mallocFailed ) goto exit_create_index;
69801     assert( db->aDb[iDb].pSchema==pTab->pSchema );
69802   }else{
69803     assert( pName==0 );
69804     pTab = pParse->pNewTable;
69805     if( !pTab ) goto exit_create_index;
69806     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
69807   }
69808   pDb = &db->aDb[iDb];
69809
69810   assert( pTab!=0 );
69811   assert( pParse->nErr==0 );
69812   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
69813        && memcmp(&pTab->zName[7],"altertab_",9)!=0 ){
69814     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
69815     goto exit_create_index;
69816   }
69817 #ifndef SQLITE_OMIT_VIEW
69818   if( pTab->pSelect ){
69819     sqlite3ErrorMsg(pParse, "views may not be indexed");
69820     goto exit_create_index;
69821   }
69822 #endif
69823 #ifndef SQLITE_OMIT_VIRTUALTABLE
69824   if( IsVirtual(pTab) ){
69825     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
69826     goto exit_create_index;
69827   }
69828 #endif
69829
69830   /*
69831   ** Find the name of the index.  Make sure there is not already another
69832   ** index or table with the same name.  
69833   **
69834   ** Exception:  If we are reading the names of permanent indices from the
69835   ** sqlite_master table (because some other process changed the schema) and
69836   ** one of the index names collides with the name of a temporary table or
69837   ** index, then we will continue to process this index.
69838   **
69839   ** If pName==0 it means that we are
69840   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
69841   ** own name.
69842   */
69843   if( pName ){
69844     zName = sqlite3NameFromToken(db, pName);
69845     if( zName==0 ) goto exit_create_index;
69846     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
69847       goto exit_create_index;
69848     }
69849     if( !db->init.busy ){
69850       if( sqlite3FindTable(db, zName, 0)!=0 ){
69851         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
69852         goto exit_create_index;
69853       }
69854     }
69855     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
69856       if( !ifNotExist ){
69857         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
69858       }
69859       goto exit_create_index;
69860     }
69861   }else{
69862     int n;
69863     Index *pLoop;
69864     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
69865     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
69866     if( zName==0 ){
69867       goto exit_create_index;
69868     }
69869   }
69870
69871   /* Check for authorization to create an index.
69872   */
69873 #ifndef SQLITE_OMIT_AUTHORIZATION
69874   {
69875     const char *zDb = pDb->zName;
69876     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
69877       goto exit_create_index;
69878     }
69879     i = SQLITE_CREATE_INDEX;
69880     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
69881     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
69882       goto exit_create_index;
69883     }
69884   }
69885 #endif
69886
69887   /* If pList==0, it means this routine was called to make a primary
69888   ** key out of the last column added to the table under construction.
69889   ** So create a fake list to simulate this.
69890   */
69891   if( pList==0 ){
69892     nullId.z = pTab->aCol[pTab->nCol-1].zName;
69893     nullId.n = sqlite3Strlen30((char*)nullId.z);
69894     pList = sqlite3ExprListAppend(pParse, 0, 0);
69895     if( pList==0 ) goto exit_create_index;
69896     sqlite3ExprListSetName(pParse, pList, &nullId, 0);
69897     pList->a[0].sortOrder = (u8)sortOrder;
69898   }
69899
69900   /* Figure out how many bytes of space are required to store explicitly
69901   ** specified collation sequence names.
69902   */
69903   for(i=0; i<pList->nExpr; i++){
69904     Expr *pExpr = pList->a[i].pExpr;
69905     if( pExpr ){
69906       CollSeq *pColl = pExpr->pColl;
69907       /* Either pColl!=0 or there was an OOM failure.  But if an OOM
69908       ** failure we have quit before reaching this point. */
69909       if( ALWAYS(pColl) ){
69910         nExtra += (1 + sqlite3Strlen30(pColl->zName));
69911       }
69912     }
69913   }
69914
69915   /* 
69916   ** Allocate the index structure. 
69917   */
69918   nName = sqlite3Strlen30(zName);
69919   nCol = pList->nExpr;
69920   pIndex = sqlite3DbMallocZero(db, 
69921       sizeof(Index) +              /* Index structure  */
69922       sizeof(int)*nCol +           /* Index.aiColumn   */
69923       sizeof(int)*(nCol+1) +       /* Index.aiRowEst   */
69924       sizeof(char *)*nCol +        /* Index.azColl     */
69925       sizeof(u8)*nCol +            /* Index.aSortOrder */
69926       nName + 1 +                  /* Index.zName      */
69927       nExtra                       /* Collation sequence names */
69928   );
69929   if( db->mallocFailed ){
69930     goto exit_create_index;
69931   }
69932   pIndex->azColl = (char**)(&pIndex[1]);
69933   pIndex->aiColumn = (int *)(&pIndex->azColl[nCol]);
69934   pIndex->aiRowEst = (unsigned *)(&pIndex->aiColumn[nCol]);
69935   pIndex->aSortOrder = (u8 *)(&pIndex->aiRowEst[nCol+1]);
69936   pIndex->zName = (char *)(&pIndex->aSortOrder[nCol]);
69937   zExtra = (char *)(&pIndex->zName[nName+1]);
69938   memcpy(pIndex->zName, zName, nName+1);
69939   pIndex->pTable = pTab;
69940   pIndex->nColumn = pList->nExpr;
69941   pIndex->onError = (u8)onError;
69942   pIndex->autoIndex = (u8)(pName==0);
69943   pIndex->pSchema = db->aDb[iDb].pSchema;
69944
69945   /* Check to see if we should honor DESC requests on index columns
69946   */
69947   if( pDb->pSchema->file_format>=4 ){
69948     sortOrderMask = -1;   /* Honor DESC */
69949   }else{
69950     sortOrderMask = 0;    /* Ignore DESC */
69951   }
69952
69953   /* Scan the names of the columns of the table to be indexed and
69954   ** load the column indices into the Index structure.  Report an error
69955   ** if any column is not found.
69956   **
69957   ** TODO:  Add a test to make sure that the same column is not named
69958   ** more than once within the same index.  Only the first instance of
69959   ** the column will ever be used by the optimizer.  Note that using the
69960   ** same column more than once cannot be an error because that would 
69961   ** break backwards compatibility - it needs to be a warning.
69962   */
69963   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
69964     const char *zColName = pListItem->zName;
69965     Column *pTabCol;
69966     int requestedSortOrder;
69967     char *zColl;                   /* Collation sequence name */
69968
69969     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
69970       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
69971     }
69972     if( j>=pTab->nCol ){
69973       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
69974         pTab->zName, zColName);
69975       goto exit_create_index;
69976     }
69977     pIndex->aiColumn[i] = j;
69978     /* Justification of the ALWAYS(pListItem->pExpr->pColl):  Because of
69979     ** the way the "idxlist" non-terminal is constructed by the parser,
69980     ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
69981     ** must exist or else there must have been an OOM error.  But if there
69982     ** was an OOM error, we would never reach this point. */
69983     if( pListItem->pExpr && ALWAYS(pListItem->pExpr->pColl) ){
69984       int nColl;
69985       zColl = pListItem->pExpr->pColl->zName;
69986       nColl = sqlite3Strlen30(zColl) + 1;
69987       assert( nExtra>=nColl );
69988       memcpy(zExtra, zColl, nColl);
69989       zColl = zExtra;
69990       zExtra += nColl;
69991       nExtra -= nColl;
69992     }else{
69993       zColl = pTab->aCol[j].zColl;
69994       if( !zColl ){
69995         zColl = db->pDfltColl->zName;
69996       }
69997     }
69998     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
69999       goto exit_create_index;
70000     }
70001     pIndex->azColl[i] = zColl;
70002     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
70003     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
70004   }
70005   sqlite3DefaultRowEst(pIndex);
70006
70007   if( pTab==pParse->pNewTable ){
70008     /* This routine has been called to create an automatic index as a
70009     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
70010     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
70011     ** i.e. one of:
70012     **
70013     ** CREATE TABLE t(x PRIMARY KEY, y);
70014     ** CREATE TABLE t(x, y, UNIQUE(x, y));
70015     **
70016     ** Either way, check to see if the table already has such an index. If
70017     ** so, don't bother creating this one. This only applies to
70018     ** automatically created indices. Users can do as they wish with
70019     ** explicit indices.
70020     **
70021     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
70022     ** (and thus suppressing the second one) even if they have different
70023     ** sort orders.
70024     **
70025     ** If there are different collating sequences or if the columns of
70026     ** the constraint occur in different orders, then the constraints are
70027     ** considered distinct and both result in separate indices.
70028     */
70029     Index *pIdx;
70030     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
70031       int k;
70032       assert( pIdx->onError!=OE_None );
70033       assert( pIdx->autoIndex );
70034       assert( pIndex->onError!=OE_None );
70035
70036       if( pIdx->nColumn!=pIndex->nColumn ) continue;
70037       for(k=0; k<pIdx->nColumn; k++){
70038         const char *z1;
70039         const char *z2;
70040         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
70041         z1 = pIdx->azColl[k];
70042         z2 = pIndex->azColl[k];
70043         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
70044       }
70045       if( k==pIdx->nColumn ){
70046         if( pIdx->onError!=pIndex->onError ){
70047           /* This constraint creates the same index as a previous
70048           ** constraint specified somewhere in the CREATE TABLE statement.
70049           ** However the ON CONFLICT clauses are different. If both this 
70050           ** constraint and the previous equivalent constraint have explicit
70051           ** ON CONFLICT clauses this is an error. Otherwise, use the
70052           ** explicitly specified behaviour for the index.
70053           */
70054           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
70055             sqlite3ErrorMsg(pParse, 
70056                 "conflicting ON CONFLICT clauses specified", 0);
70057           }
70058           if( pIdx->onError==OE_Default ){
70059             pIdx->onError = pIndex->onError;
70060           }
70061         }
70062         goto exit_create_index;
70063       }
70064     }
70065   }
70066
70067   /* Link the new Index structure to its table and to the other
70068   ** in-memory database structures. 
70069   */
70070   if( db->init.busy ){
70071     Index *p;
70072     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
70073                           pIndex->zName, sqlite3Strlen30(pIndex->zName),
70074                           pIndex);
70075     if( p ){
70076       assert( p==pIndex );  /* Malloc must have failed */
70077       db->mallocFailed = 1;
70078       goto exit_create_index;
70079     }
70080     db->flags |= SQLITE_InternChanges;
70081     if( pTblName!=0 ){
70082       pIndex->tnum = db->init.newTnum;
70083     }
70084   }
70085
70086   /* If the db->init.busy is 0 then create the index on disk.  This
70087   ** involves writing the index into the master table and filling in the
70088   ** index with the current table contents.
70089   **
70090   ** The db->init.busy is 0 when the user first enters a CREATE INDEX 
70091   ** command.  db->init.busy is 1 when a database is opened and 
70092   ** CREATE INDEX statements are read out of the master table.  In
70093   ** the latter case the index already exists on disk, which is why
70094   ** we don't want to recreate it.
70095   **
70096   ** If pTblName==0 it means this index is generated as a primary key
70097   ** or UNIQUE constraint of a CREATE TABLE statement.  Since the table
70098   ** has just been created, it contains no data and the index initialization
70099   ** step can be skipped.
70100   */
70101   else{ /* if( db->init.busy==0 ) */
70102     Vdbe *v;
70103     char *zStmt;
70104     int iMem = ++pParse->nMem;
70105
70106     v = sqlite3GetVdbe(pParse);
70107     if( v==0 ) goto exit_create_index;
70108
70109
70110     /* Create the rootpage for the index
70111     */
70112     sqlite3BeginWriteOperation(pParse, 1, iDb);
70113     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
70114
70115     /* Gather the complete text of the CREATE INDEX statement into
70116     ** the zStmt variable
70117     */
70118     if( pStart ){
70119       assert( pEnd!=0 );
70120       /* A named index with an explicit CREATE INDEX statement */
70121       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
70122         onError==OE_None ? "" : " UNIQUE",
70123         pEnd->z - pName->z + 1,
70124         pName->z);
70125     }else{
70126       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
70127       /* zStmt = sqlite3MPrintf(""); */
70128       zStmt = 0;
70129     }
70130
70131     /* Add an entry in sqlite_master for this index
70132     */
70133     sqlite3NestedParse(pParse, 
70134         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
70135         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
70136         pIndex->zName,
70137         pTab->zName,
70138         iMem,
70139         zStmt
70140     );
70141     sqlite3DbFree(db, zStmt);
70142
70143     /* Fill the index with data and reparse the schema. Code an OP_Expire
70144     ** to invalidate all pre-compiled statements.
70145     */
70146     if( pTblName ){
70147       sqlite3RefillIndex(pParse, pIndex, iMem);
70148       sqlite3ChangeCookie(pParse, iDb);
70149       sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0,
70150          sqlite3MPrintf(db, "name='%q'", pIndex->zName), P4_DYNAMIC);
70151       sqlite3VdbeAddOp1(v, OP_Expire, 0);
70152     }
70153   }
70154
70155   /* When adding an index to the list of indices for a table, make
70156   ** sure all indices labeled OE_Replace come after all those labeled
70157   ** OE_Ignore.  This is necessary for the correct constraint check
70158   ** processing (in sqlite3GenerateConstraintChecks()) as part of
70159   ** UPDATE and INSERT statements.  
70160   */
70161   if( db->init.busy || pTblName==0 ){
70162     if( onError!=OE_Replace || pTab->pIndex==0
70163          || pTab->pIndex->onError==OE_Replace){
70164       pIndex->pNext = pTab->pIndex;
70165       pTab->pIndex = pIndex;
70166     }else{
70167       Index *pOther = pTab->pIndex;
70168       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
70169         pOther = pOther->pNext;
70170       }
70171       pIndex->pNext = pOther->pNext;
70172       pOther->pNext = pIndex;
70173     }
70174     pRet = pIndex;
70175     pIndex = 0;
70176   }
70177
70178   /* Clean up before exiting */
70179 exit_create_index:
70180   if( pIndex ){
70181     sqlite3_free(pIndex->zColAff);
70182     sqlite3DbFree(db, pIndex);
70183   }
70184   sqlite3ExprListDelete(db, pList);
70185   sqlite3SrcListDelete(db, pTblName);
70186   sqlite3DbFree(db, zName);
70187   return pRet;
70188 }
70189
70190 /*
70191 ** Fill the Index.aiRowEst[] array with default information - information
70192 ** to be used when we have not run the ANALYZE command.
70193 **
70194 ** aiRowEst[0] is suppose to contain the number of elements in the index.
70195 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
70196 ** number of rows in the table that match any particular value of the
70197 ** first column of the index.  aiRowEst[2] is an estimate of the number
70198 ** of rows that match any particular combiniation of the first 2 columns
70199 ** of the index.  And so forth.  It must always be the case that
70200 *
70201 **           aiRowEst[N]<=aiRowEst[N-1]
70202 **           aiRowEst[N]>=1
70203 **
70204 ** Apart from that, we have little to go on besides intuition as to
70205 ** how aiRowEst[] should be initialized.  The numbers generated here
70206 ** are based on typical values found in actual indices.
70207 */
70208 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
70209   unsigned *a = pIdx->aiRowEst;
70210   int i;
70211   assert( a!=0 );
70212   a[0] = 1000000;
70213   for(i=pIdx->nColumn; i>=5; i--){
70214     a[i] = 5;
70215   }
70216   while( i>=1 ){
70217     a[i] = 11 - i;
70218     i--;
70219   }
70220   if( pIdx->onError!=OE_None ){
70221     a[pIdx->nColumn] = 1;
70222   }
70223 }
70224
70225 /*
70226 ** This routine will drop an existing named index.  This routine
70227 ** implements the DROP INDEX statement.
70228 */
70229 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
70230   Index *pIndex;
70231   Vdbe *v;
70232   sqlite3 *db = pParse->db;
70233   int iDb;
70234
70235   assert( pParse->nErr==0 );   /* Never called with prior errors */
70236   if( db->mallocFailed ){
70237     goto exit_drop_index;
70238   }
70239   assert( pName->nSrc==1 );
70240   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
70241     goto exit_drop_index;
70242   }
70243   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
70244   if( pIndex==0 ){
70245     if( !ifExists ){
70246       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
70247     }
70248     pParse->checkSchema = 1;
70249     goto exit_drop_index;
70250   }
70251   if( pIndex->autoIndex ){
70252     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
70253       "or PRIMARY KEY constraint cannot be dropped", 0);
70254     goto exit_drop_index;
70255   }
70256   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
70257 #ifndef SQLITE_OMIT_AUTHORIZATION
70258   {
70259     int code = SQLITE_DROP_INDEX;
70260     Table *pTab = pIndex->pTable;
70261     const char *zDb = db->aDb[iDb].zName;
70262     const char *zTab = SCHEMA_TABLE(iDb);
70263     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
70264       goto exit_drop_index;
70265     }
70266     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
70267     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
70268       goto exit_drop_index;
70269     }
70270   }
70271 #endif
70272
70273   /* Generate code to remove the index and from the master table */
70274   v = sqlite3GetVdbe(pParse);
70275   if( v ){
70276     sqlite3BeginWriteOperation(pParse, 1, iDb);
70277     sqlite3NestedParse(pParse,
70278        "DELETE FROM %Q.%s WHERE name=%Q",
70279        db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
70280        pIndex->zName
70281     );
70282     if( sqlite3FindTable(db, "sqlite_stat1", db->aDb[iDb].zName) ){
70283       sqlite3NestedParse(pParse,
70284         "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
70285         db->aDb[iDb].zName, pIndex->zName
70286       );
70287     }
70288     sqlite3ChangeCookie(pParse, iDb);
70289     destroyRootPage(pParse, pIndex->tnum, iDb);
70290     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
70291   }
70292
70293 exit_drop_index:
70294   sqlite3SrcListDelete(db, pName);
70295 }
70296
70297 /*
70298 ** pArray is a pointer to an array of objects.  Each object in the
70299 ** array is szEntry bytes in size.  This routine allocates a new
70300 ** object on the end of the array.
70301 **
70302 ** *pnEntry is the number of entries already in use.  *pnAlloc is
70303 ** the previously allocated size of the array.  initSize is the
70304 ** suggested initial array size allocation.
70305 **
70306 ** The index of the new entry is returned in *pIdx.
70307 **
70308 ** This routine returns a pointer to the array of objects.  This
70309 ** might be the same as the pArray parameter or it might be a different
70310 ** pointer if the array was resized.
70311 */
70312 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
70313   sqlite3 *db,      /* Connection to notify of malloc failures */
70314   void *pArray,     /* Array of objects.  Might be reallocated */
70315   int szEntry,      /* Size of each object in the array */
70316   int initSize,     /* Suggested initial allocation, in elements */
70317   int *pnEntry,     /* Number of objects currently in use */
70318   int *pnAlloc,     /* Current size of the allocation, in elements */
70319   int *pIdx         /* Write the index of a new slot here */
70320 ){
70321   char *z;
70322   if( *pnEntry >= *pnAlloc ){
70323     void *pNew;
70324     int newSize;
70325     newSize = (*pnAlloc)*2 + initSize;
70326     pNew = sqlite3DbRealloc(db, pArray, newSize*szEntry);
70327     if( pNew==0 ){
70328       *pIdx = -1;
70329       return pArray;
70330     }
70331     *pnAlloc = sqlite3DbMallocSize(db, pNew)/szEntry;
70332     pArray = pNew;
70333   }
70334   z = (char*)pArray;
70335   memset(&z[*pnEntry * szEntry], 0, szEntry);
70336   *pIdx = *pnEntry;
70337   ++*pnEntry;
70338   return pArray;
70339 }
70340
70341 /*
70342 ** Append a new element to the given IdList.  Create a new IdList if
70343 ** need be.
70344 **
70345 ** A new IdList is returned, or NULL if malloc() fails.
70346 */
70347 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
70348   int i;
70349   if( pList==0 ){
70350     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
70351     if( pList==0 ) return 0;
70352     pList->nAlloc = 0;
70353   }
70354   pList->a = sqlite3ArrayAllocate(
70355       db,
70356       pList->a,
70357       sizeof(pList->a[0]),
70358       5,
70359       &pList->nId,
70360       &pList->nAlloc,
70361       &i
70362   );
70363   if( i<0 ){
70364     sqlite3IdListDelete(db, pList);
70365     return 0;
70366   }
70367   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
70368   return pList;
70369 }
70370
70371 /*
70372 ** Delete an IdList.
70373 */
70374 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
70375   int i;
70376   if( pList==0 ) return;
70377   for(i=0; i<pList->nId; i++){
70378     sqlite3DbFree(db, pList->a[i].zName);
70379   }
70380   sqlite3DbFree(db, pList->a);
70381   sqlite3DbFree(db, pList);
70382 }
70383
70384 /*
70385 ** Return the index in pList of the identifier named zId.  Return -1
70386 ** if not found.
70387 */
70388 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
70389   int i;
70390   if( pList==0 ) return -1;
70391   for(i=0; i<pList->nId; i++){
70392     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
70393   }
70394   return -1;
70395 }
70396
70397 /*
70398 ** Expand the space allocated for the given SrcList object by
70399 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
70400 ** New slots are zeroed.
70401 **
70402 ** For example, suppose a SrcList initially contains two entries: A,B.
70403 ** To append 3 new entries onto the end, do this:
70404 **
70405 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
70406 **
70407 ** After the call above it would contain:  A, B, nil, nil, nil.
70408 ** If the iStart argument had been 1 instead of 2, then the result
70409 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
70410 ** the iStart value would be 0.  The result then would
70411 ** be: nil, nil, nil, A, B.
70412 **
70413 ** If a memory allocation fails the SrcList is unchanged.  The
70414 ** db->mallocFailed flag will be set to true.
70415 */
70416 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
70417   sqlite3 *db,       /* Database connection to notify of OOM errors */
70418   SrcList *pSrc,     /* The SrcList to be enlarged */
70419   int nExtra,        /* Number of new slots to add to pSrc->a[] */
70420   int iStart         /* Index in pSrc->a[] of first new slot */
70421 ){
70422   int i;
70423
70424   /* Sanity checking on calling parameters */
70425   assert( iStart>=0 );
70426   assert( nExtra>=1 );
70427   assert( pSrc!=0 );
70428   assert( iStart<=pSrc->nSrc );
70429
70430   /* Allocate additional space if needed */
70431   if( pSrc->nSrc+nExtra>pSrc->nAlloc ){
70432     SrcList *pNew;
70433     int nAlloc = pSrc->nSrc+nExtra;
70434     int nGot;
70435     pNew = sqlite3DbRealloc(db, pSrc,
70436                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
70437     if( pNew==0 ){
70438       assert( db->mallocFailed );
70439       return pSrc;
70440     }
70441     pSrc = pNew;
70442     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
70443     pSrc->nAlloc = (u16)nGot;
70444   }
70445
70446   /* Move existing slots that come after the newly inserted slots
70447   ** out of the way */
70448   for(i=pSrc->nSrc-1; i>=iStart; i--){
70449     pSrc->a[i+nExtra] = pSrc->a[i];
70450   }
70451   pSrc->nSrc += (i16)nExtra;
70452
70453   /* Zero the newly allocated slots */
70454   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
70455   for(i=iStart; i<iStart+nExtra; i++){
70456     pSrc->a[i].iCursor = -1;
70457   }
70458
70459   /* Return a pointer to the enlarged SrcList */
70460   return pSrc;
70461 }
70462
70463
70464 /*
70465 ** Append a new table name to the given SrcList.  Create a new SrcList if
70466 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
70467 **
70468 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
70469 ** SrcList might be the same as the SrcList that was input or it might be
70470 ** a new one.  If an OOM error does occurs, then the prior value of pList
70471 ** that is input to this routine is automatically freed.
70472 **
70473 ** If pDatabase is not null, it means that the table has an optional
70474 ** database name prefix.  Like this:  "database.table".  The pDatabase
70475 ** points to the table name and the pTable points to the database name.
70476 ** The SrcList.a[].zName field is filled with the table name which might
70477 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
70478 ** SrcList.a[].zDatabase is filled with the database name from pTable,
70479 ** or with NULL if no database is specified.
70480 **
70481 ** In other words, if call like this:
70482 **
70483 **         sqlite3SrcListAppend(D,A,B,0);
70484 **
70485 ** Then B is a table name and the database name is unspecified.  If called
70486 ** like this:
70487 **
70488 **         sqlite3SrcListAppend(D,A,B,C);
70489 **
70490 ** Then C is the table name and B is the database name.  If C is defined
70491 ** then so is B.  In other words, we never have a case where:
70492 **
70493 **         sqlite3SrcListAppend(D,A,0,C);
70494 **
70495 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
70496 ** before being added to the SrcList.
70497 */
70498 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
70499   sqlite3 *db,        /* Connection to notify of malloc failures */
70500   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
70501   Token *pTable,      /* Table to append */
70502   Token *pDatabase    /* Database of the table */
70503 ){
70504   struct SrcList_item *pItem;
70505   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
70506   if( pList==0 ){
70507     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
70508     if( pList==0 ) return 0;
70509     pList->nAlloc = 1;
70510   }
70511   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
70512   if( db->mallocFailed ){
70513     sqlite3SrcListDelete(db, pList);
70514     return 0;
70515   }
70516   pItem = &pList->a[pList->nSrc-1];
70517   if( pDatabase && pDatabase->z==0 ){
70518     pDatabase = 0;
70519   }
70520   if( pDatabase ){
70521     Token *pTemp = pDatabase;
70522     pDatabase = pTable;
70523     pTable = pTemp;
70524   }
70525   pItem->zName = sqlite3NameFromToken(db, pTable);
70526   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
70527   return pList;
70528 }
70529
70530 /*
70531 ** Assign VdbeCursor index numbers to all tables in a SrcList
70532 */
70533 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
70534   int i;
70535   struct SrcList_item *pItem;
70536   assert(pList || pParse->db->mallocFailed );
70537   if( pList ){
70538     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
70539       if( pItem->iCursor>=0 ) break;
70540       pItem->iCursor = pParse->nTab++;
70541       if( pItem->pSelect ){
70542         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
70543       }
70544     }
70545   }
70546 }
70547
70548 /*
70549 ** Delete an entire SrcList including all its substructure.
70550 */
70551 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
70552   int i;
70553   struct SrcList_item *pItem;
70554   if( pList==0 ) return;
70555   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
70556     sqlite3DbFree(db, pItem->zDatabase);
70557     sqlite3DbFree(db, pItem->zName);
70558     sqlite3DbFree(db, pItem->zAlias);
70559     sqlite3DbFree(db, pItem->zIndex);
70560     sqlite3DeleteTable(pItem->pTab);
70561     sqlite3SelectDelete(db, pItem->pSelect);
70562     sqlite3ExprDelete(db, pItem->pOn);
70563     sqlite3IdListDelete(db, pItem->pUsing);
70564   }
70565   sqlite3DbFree(db, pList);
70566 }
70567
70568 /*
70569 ** This routine is called by the parser to add a new term to the
70570 ** end of a growing FROM clause.  The "p" parameter is the part of
70571 ** the FROM clause that has already been constructed.  "p" is NULL
70572 ** if this is the first term of the FROM clause.  pTable and pDatabase
70573 ** are the name of the table and database named in the FROM clause term.
70574 ** pDatabase is NULL if the database name qualifier is missing - the
70575 ** usual case.  If the term has a alias, then pAlias points to the
70576 ** alias token.  If the term is a subquery, then pSubquery is the
70577 ** SELECT statement that the subquery encodes.  The pTable and
70578 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
70579 ** parameters are the content of the ON and USING clauses.
70580 **
70581 ** Return a new SrcList which encodes is the FROM with the new
70582 ** term added.
70583 */
70584 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
70585   Parse *pParse,          /* Parsing context */
70586   SrcList *p,             /* The left part of the FROM clause already seen */
70587   Token *pTable,          /* Name of the table to add to the FROM clause */
70588   Token *pDatabase,       /* Name of the database containing pTable */
70589   Token *pAlias,          /* The right-hand side of the AS subexpression */
70590   Select *pSubquery,      /* A subquery used in place of a table name */
70591   Expr *pOn,              /* The ON clause of a join */
70592   IdList *pUsing          /* The USING clause of a join */
70593 ){
70594   struct SrcList_item *pItem;
70595   sqlite3 *db = pParse->db;
70596   if( !p && (pOn || pUsing) ){
70597     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
70598       (pOn ? "ON" : "USING")
70599     );
70600     goto append_from_error;
70601   }
70602   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
70603   if( p==0 || NEVER(p->nSrc==0) ){
70604     goto append_from_error;
70605   }
70606   pItem = &p->a[p->nSrc-1];
70607   assert( pAlias!=0 );
70608   if( pAlias->n ){
70609     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
70610   }
70611   pItem->pSelect = pSubquery;
70612   pItem->pOn = pOn;
70613   pItem->pUsing = pUsing;
70614   return p;
70615
70616  append_from_error:
70617   assert( p==0 );
70618   sqlite3ExprDelete(db, pOn);
70619   sqlite3IdListDelete(db, pUsing);
70620   sqlite3SelectDelete(db, pSubquery);
70621   return 0;
70622 }
70623
70624 /*
70625 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
70626 ** element of the source-list passed as the second argument.
70627 */
70628 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
70629   assert( pIndexedBy!=0 );
70630   if( p && ALWAYS(p->nSrc>0) ){
70631     struct SrcList_item *pItem = &p->a[p->nSrc-1];
70632     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
70633     if( pIndexedBy->n==1 && !pIndexedBy->z ){
70634       /* A "NOT INDEXED" clause was supplied. See parse.y 
70635       ** construct "indexed_opt" for details. */
70636       pItem->notIndexed = 1;
70637     }else{
70638       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
70639     }
70640   }
70641 }
70642
70643 /*
70644 ** When building up a FROM clause in the parser, the join operator
70645 ** is initially attached to the left operand.  But the code generator
70646 ** expects the join operator to be on the right operand.  This routine
70647 ** Shifts all join operators from left to right for an entire FROM
70648 ** clause.
70649 **
70650 ** Example: Suppose the join is like this:
70651 **
70652 **           A natural cross join B
70653 **
70654 ** The operator is "natural cross join".  The A and B operands are stored
70655 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
70656 ** operator with A.  This routine shifts that operator over to B.
70657 */
70658 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
70659   if( p && p->a ){
70660     int i;
70661     for(i=p->nSrc-1; i>0; i--){
70662       p->a[i].jointype = p->a[i-1].jointype;
70663     }
70664     p->a[0].jointype = 0;
70665   }
70666 }
70667
70668 /*
70669 ** Begin a transaction
70670 */
70671 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
70672   sqlite3 *db;
70673   Vdbe *v;
70674   int i;
70675
70676   assert( pParse!=0 );
70677   db = pParse->db;
70678   assert( db!=0 );
70679 /*  if( db->aDb[0].pBt==0 ) return; */
70680   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
70681     return;
70682   }
70683   v = sqlite3GetVdbe(pParse);
70684   if( !v ) return;
70685   if( type!=TK_DEFERRED ){
70686     for(i=0; i<db->nDb; i++){
70687       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
70688       sqlite3VdbeUsesBtree(v, i);
70689     }
70690   }
70691   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
70692 }
70693
70694 /*
70695 ** Commit a transaction
70696 */
70697 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
70698   sqlite3 *db;
70699   Vdbe *v;
70700
70701   assert( pParse!=0 );
70702   db = pParse->db;
70703   assert( db!=0 );
70704 /*  if( db->aDb[0].pBt==0 ) return; */
70705   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
70706     return;
70707   }
70708   v = sqlite3GetVdbe(pParse);
70709   if( v ){
70710     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
70711   }
70712 }
70713
70714 /*
70715 ** Rollback a transaction
70716 */
70717 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
70718   sqlite3 *db;
70719   Vdbe *v;
70720
70721   assert( pParse!=0 );
70722   db = pParse->db;
70723   assert( db!=0 );
70724 /*  if( db->aDb[0].pBt==0 ) return; */
70725   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
70726     return;
70727   }
70728   v = sqlite3GetVdbe(pParse);
70729   if( v ){
70730     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
70731   }
70732 }
70733
70734 /*
70735 ** This function is called by the parser when it parses a command to create,
70736 ** release or rollback an SQL savepoint. 
70737 */
70738 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
70739   char *zName = sqlite3NameFromToken(pParse->db, pName);
70740   if( zName ){
70741     Vdbe *v = sqlite3GetVdbe(pParse);
70742 #ifndef SQLITE_OMIT_AUTHORIZATION
70743     static const char *az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
70744     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
70745 #endif
70746     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
70747       sqlite3DbFree(pParse->db, zName);
70748       return;
70749     }
70750     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
70751   }
70752 }
70753
70754 /*
70755 ** Make sure the TEMP database is open and available for use.  Return
70756 ** the number of errors.  Leave any error messages in the pParse structure.
70757 */
70758 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
70759   sqlite3 *db = pParse->db;
70760   if( db->aDb[1].pBt==0 && !pParse->explain ){
70761     int rc;
70762     Btree *pBt;
70763     static const int flags = 
70764           SQLITE_OPEN_READWRITE |
70765           SQLITE_OPEN_CREATE |
70766           SQLITE_OPEN_EXCLUSIVE |
70767           SQLITE_OPEN_DELETEONCLOSE |
70768           SQLITE_OPEN_TEMP_DB;
70769
70770     rc = sqlite3BtreeFactory(db, 0, 0, SQLITE_DEFAULT_CACHE_SIZE, flags, &pBt);
70771     if( rc!=SQLITE_OK ){
70772       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
70773         "file for storing temporary tables");
70774       pParse->rc = rc;
70775       return 1;
70776     }
70777     db->aDb[1].pBt = pBt;
70778     assert( db->aDb[1].pSchema );
70779     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
70780       db->mallocFailed = 1;
70781       return 1;
70782     }
70783     sqlite3PagerJournalMode(sqlite3BtreePager(pBt), db->dfltJournalMode);
70784   }
70785   return 0;
70786 }
70787
70788 /*
70789 ** Generate VDBE code that will verify the schema cookie and start
70790 ** a read-transaction for all named database files.
70791 **
70792 ** It is important that all schema cookies be verified and all
70793 ** read transactions be started before anything else happens in
70794 ** the VDBE program.  But this routine can be called after much other
70795 ** code has been generated.  So here is what we do:
70796 **
70797 ** The first time this routine is called, we code an OP_Goto that
70798 ** will jump to a subroutine at the end of the program.  Then we
70799 ** record every database that needs its schema verified in the
70800 ** pParse->cookieMask field.  Later, after all other code has been
70801 ** generated, the subroutine that does the cookie verifications and
70802 ** starts the transactions will be coded and the OP_Goto P2 value
70803 ** will be made to point to that subroutine.  The generation of the
70804 ** cookie verification subroutine code happens in sqlite3FinishCoding().
70805 **
70806 ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
70807 ** schema on any databases.  This can be used to position the OP_Goto
70808 ** early in the code, before we know if any database tables will be used.
70809 */
70810 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
70811   Parse *pToplevel = sqlite3ParseToplevel(pParse);
70812
70813   if( pToplevel->cookieGoto==0 ){
70814     Vdbe *v = sqlite3GetVdbe(pToplevel);
70815     if( v==0 ) return;  /* This only happens if there was a prior error */
70816     pToplevel->cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0)+1;
70817   }
70818   if( iDb>=0 ){
70819     sqlite3 *db = pToplevel->db;
70820     int mask;
70821
70822     assert( iDb<db->nDb );
70823     assert( db->aDb[iDb].pBt!=0 || iDb==1 );
70824     assert( iDb<SQLITE_MAX_ATTACHED+2 );
70825     mask = 1<<iDb;
70826     if( (pToplevel->cookieMask & mask)==0 ){
70827       pToplevel->cookieMask |= mask;
70828       pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
70829       if( !OMIT_TEMPDB && iDb==1 ){
70830         sqlite3OpenTempDatabase(pToplevel);
70831       }
70832     }
70833   }
70834 }
70835
70836 /*
70837 ** Generate VDBE code that prepares for doing an operation that
70838 ** might change the database.
70839 **
70840 ** This routine starts a new transaction if we are not already within
70841 ** a transaction.  If we are already within a transaction, then a checkpoint
70842 ** is set if the setStatement parameter is true.  A checkpoint should
70843 ** be set for operations that might fail (due to a constraint) part of
70844 ** the way through and which will need to undo some writes without having to
70845 ** rollback the whole transaction.  For operations where all constraints
70846 ** can be checked before any changes are made to the database, it is never
70847 ** necessary to undo a write and the checkpoint should not be set.
70848 */
70849 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
70850   Parse *pToplevel = sqlite3ParseToplevel(pParse);
70851   sqlite3CodeVerifySchema(pParse, iDb);
70852   pToplevel->writeMask |= 1<<iDb;
70853   pToplevel->isMultiWrite |= setStatement;
70854 }
70855
70856 /*
70857 ** Indicate that the statement currently under construction might write
70858 ** more than one entry (example: deleting one row then inserting another,
70859 ** inserting multiple rows in a table, or inserting a row and index entries.)
70860 ** If an abort occurs after some of these writes have completed, then it will
70861 ** be necessary to undo the completed writes.
70862 */
70863 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
70864   Parse *pToplevel = sqlite3ParseToplevel(pParse);
70865   pToplevel->isMultiWrite = 1;
70866 }
70867
70868 /* 
70869 ** The code generator calls this routine if is discovers that it is
70870 ** possible to abort a statement prior to completion.  In order to 
70871 ** perform this abort without corrupting the database, we need to make
70872 ** sure that the statement is protected by a statement transaction.
70873 **
70874 ** Technically, we only need to set the mayAbort flag if the
70875 ** isMultiWrite flag was previously set.  There is a time dependency
70876 ** such that the abort must occur after the multiwrite.  This makes
70877 ** some statements involving the REPLACE conflict resolution algorithm
70878 ** go a little faster.  But taking advantage of this time dependency
70879 ** makes it more difficult to prove that the code is correct (in 
70880 ** particular, it prevents us from writing an effective
70881 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
70882 ** to take the safe route and skip the optimization.
70883 */
70884 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
70885   Parse *pToplevel = sqlite3ParseToplevel(pParse);
70886   pToplevel->mayAbort = 1;
70887 }
70888
70889 /*
70890 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
70891 ** error. The onError parameter determines which (if any) of the statement
70892 ** and/or current transaction is rolled back.
70893 */
70894 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse *pParse, int onError, char *p4, int p4type){
70895   Vdbe *v = sqlite3GetVdbe(pParse);
70896   if( onError==OE_Abort ){
70897     sqlite3MayAbort(pParse);
70898   }
70899   sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
70900 }
70901
70902 /*
70903 ** Check to see if pIndex uses the collating sequence pColl.  Return
70904 ** true if it does and false if it does not.
70905 */
70906 #ifndef SQLITE_OMIT_REINDEX
70907 static int collationMatch(const char *zColl, Index *pIndex){
70908   int i;
70909   assert( zColl!=0 );
70910   for(i=0; i<pIndex->nColumn; i++){
70911     const char *z = pIndex->azColl[i];
70912     assert( z!=0 );
70913     if( 0==sqlite3StrICmp(z, zColl) ){
70914       return 1;
70915     }
70916   }
70917   return 0;
70918 }
70919 #endif
70920
70921 /*
70922 ** Recompute all indices of pTab that use the collating sequence pColl.
70923 ** If pColl==0 then recompute all indices of pTab.
70924 */
70925 #ifndef SQLITE_OMIT_REINDEX
70926 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
70927   Index *pIndex;              /* An index associated with pTab */
70928
70929   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
70930     if( zColl==0 || collationMatch(zColl, pIndex) ){
70931       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
70932       sqlite3BeginWriteOperation(pParse, 0, iDb);
70933       sqlite3RefillIndex(pParse, pIndex, -1);
70934     }
70935   }
70936 }
70937 #endif
70938
70939 /*
70940 ** Recompute all indices of all tables in all databases where the
70941 ** indices use the collating sequence pColl.  If pColl==0 then recompute
70942 ** all indices everywhere.
70943 */
70944 #ifndef SQLITE_OMIT_REINDEX
70945 static void reindexDatabases(Parse *pParse, char const *zColl){
70946   Db *pDb;                    /* A single database */
70947   int iDb;                    /* The database index number */
70948   sqlite3 *db = pParse->db;   /* The database connection */
70949   HashElem *k;                /* For looping over tables in pDb */
70950   Table *pTab;                /* A table in the database */
70951
70952   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
70953     assert( pDb!=0 );
70954     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
70955       pTab = (Table*)sqliteHashData(k);
70956       reindexTable(pParse, pTab, zColl);
70957     }
70958   }
70959 }
70960 #endif
70961
70962 /*
70963 ** Generate code for the REINDEX command.
70964 **
70965 **        REINDEX                            -- 1
70966 **        REINDEX  <collation>               -- 2
70967 **        REINDEX  ?<database>.?<tablename>  -- 3
70968 **        REINDEX  ?<database>.?<indexname>  -- 4
70969 **
70970 ** Form 1 causes all indices in all attached databases to be rebuilt.
70971 ** Form 2 rebuilds all indices in all databases that use the named
70972 ** collating function.  Forms 3 and 4 rebuild the named index or all
70973 ** indices associated with the named table.
70974 */
70975 #ifndef SQLITE_OMIT_REINDEX
70976 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
70977   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
70978   char *z;                    /* Name of a table or index */
70979   const char *zDb;            /* Name of the database */
70980   Table *pTab;                /* A table in the database */
70981   Index *pIndex;              /* An index associated with pTab */
70982   int iDb;                    /* The database index number */
70983   sqlite3 *db = pParse->db;   /* The database connection */
70984   Token *pObjName;            /* Name of the table or index to be reindexed */
70985
70986   /* Read the database schema. If an error occurs, leave an error message
70987   ** and code in pParse and return NULL. */
70988   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
70989     return;
70990   }
70991
70992   if( pName1==0 ){
70993     reindexDatabases(pParse, 0);
70994     return;
70995   }else if( NEVER(pName2==0) || pName2->z==0 ){
70996     char *zColl;
70997     assert( pName1->z );
70998     zColl = sqlite3NameFromToken(pParse->db, pName1);
70999     if( !zColl ) return;
71000     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
71001     if( pColl ){
71002       reindexDatabases(pParse, zColl);
71003       sqlite3DbFree(db, zColl);
71004       return;
71005     }
71006     sqlite3DbFree(db, zColl);
71007   }
71008   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
71009   if( iDb<0 ) return;
71010   z = sqlite3NameFromToken(db, pObjName);
71011   if( z==0 ) return;
71012   zDb = db->aDb[iDb].zName;
71013   pTab = sqlite3FindTable(db, z, zDb);
71014   if( pTab ){
71015     reindexTable(pParse, pTab, 0);
71016     sqlite3DbFree(db, z);
71017     return;
71018   }
71019   pIndex = sqlite3FindIndex(db, z, zDb);
71020   sqlite3DbFree(db, z);
71021   if( pIndex ){
71022     sqlite3BeginWriteOperation(pParse, 0, iDb);
71023     sqlite3RefillIndex(pParse, pIndex, -1);
71024     return;
71025   }
71026   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
71027 }
71028 #endif
71029
71030 /*
71031 ** Return a dynamicly allocated KeyInfo structure that can be used
71032 ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
71033 **
71034 ** If successful, a pointer to the new structure is returned. In this case
71035 ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned 
71036 ** pointer. If an error occurs (out of memory or missing collation 
71037 ** sequence), NULL is returned and the state of pParse updated to reflect
71038 ** the error.
71039 */
71040 SQLITE_PRIVATE KeyInfo *sqlite3IndexKeyinfo(Parse *pParse, Index *pIdx){
71041   int i;
71042   int nCol = pIdx->nColumn;
71043   int nBytes = sizeof(KeyInfo) + (nCol-1)*sizeof(CollSeq*) + nCol;
71044   sqlite3 *db = pParse->db;
71045   KeyInfo *pKey = (KeyInfo *)sqlite3DbMallocZero(db, nBytes);
71046
71047   if( pKey ){
71048     pKey->db = pParse->db;
71049     pKey->aSortOrder = (u8 *)&(pKey->aColl[nCol]);
71050     assert( &pKey->aSortOrder[nCol]==&(((u8 *)pKey)[nBytes]) );
71051     for(i=0; i<nCol; i++){
71052       char *zColl = pIdx->azColl[i];
71053       assert( zColl );
71054       pKey->aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
71055       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
71056     }
71057     pKey->nField = (u16)nCol;
71058   }
71059
71060   if( pParse->nErr ){
71061     sqlite3DbFree(db, pKey);
71062     pKey = 0;
71063   }
71064   return pKey;
71065 }
71066
71067 /************** End of build.c ***********************************************/
71068 /************** Begin file callback.c ****************************************/
71069 /*
71070 ** 2005 May 23 
71071 **
71072 ** The author disclaims copyright to this source code.  In place of
71073 ** a legal notice, here is a blessing:
71074 **
71075 **    May you do good and not evil.
71076 **    May you find forgiveness for yourself and forgive others.
71077 **    May you share freely, never taking more than you give.
71078 **
71079 *************************************************************************
71080 **
71081 ** This file contains functions used to access the internal hash tables
71082 ** of user defined functions and collation sequences.
71083 */
71084
71085
71086 /*
71087 ** Invoke the 'collation needed' callback to request a collation sequence
71088 ** in the encoding enc of name zName, length nName.
71089 */
71090 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
71091   assert( !db->xCollNeeded || !db->xCollNeeded16 );
71092   if( db->xCollNeeded ){
71093     char *zExternal = sqlite3DbStrDup(db, zName);
71094     if( !zExternal ) return;
71095     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
71096     sqlite3DbFree(db, zExternal);
71097   }
71098 #ifndef SQLITE_OMIT_UTF16
71099   if( db->xCollNeeded16 ){
71100     char const *zExternal;
71101     sqlite3_value *pTmp = sqlite3ValueNew(db);
71102     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
71103     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
71104     if( zExternal ){
71105       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
71106     }
71107     sqlite3ValueFree(pTmp);
71108   }
71109 #endif
71110 }
71111
71112 /*
71113 ** This routine is called if the collation factory fails to deliver a
71114 ** collation function in the best encoding but there may be other versions
71115 ** of this collation function (for other text encodings) available. Use one
71116 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
71117 ** possible.
71118 */
71119 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
71120   CollSeq *pColl2;
71121   char *z = pColl->zName;
71122   int i;
71123   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
71124   for(i=0; i<3; i++){
71125     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
71126     if( pColl2->xCmp!=0 ){
71127       memcpy(pColl, pColl2, sizeof(CollSeq));
71128       pColl->xDel = 0;         /* Do not copy the destructor */
71129       return SQLITE_OK;
71130     }
71131   }
71132   return SQLITE_ERROR;
71133 }
71134
71135 /*
71136 ** This function is responsible for invoking the collation factory callback
71137 ** or substituting a collation sequence of a different encoding when the
71138 ** requested collation sequence is not available in the desired encoding.
71139 ** 
71140 ** If it is not NULL, then pColl must point to the database native encoding 
71141 ** collation sequence with name zName, length nName.
71142 **
71143 ** The return value is either the collation sequence to be used in database
71144 ** db for collation type name zName, length nName, or NULL, if no collation
71145 ** sequence can be found.
71146 **
71147 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
71148 */
71149 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
71150   sqlite3* db,          /* The database connection */
71151   u8 enc,               /* The desired encoding for the collating sequence */
71152   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
71153   const char *zName     /* Collating sequence name */
71154 ){
71155   CollSeq *p;
71156
71157   p = pColl;
71158   if( !p ){
71159     p = sqlite3FindCollSeq(db, enc, zName, 0);
71160   }
71161   if( !p || !p->xCmp ){
71162     /* No collation sequence of this type for this encoding is registered.
71163     ** Call the collation factory to see if it can supply us with one.
71164     */
71165     callCollNeeded(db, enc, zName);
71166     p = sqlite3FindCollSeq(db, enc, zName, 0);
71167   }
71168   if( p && !p->xCmp && synthCollSeq(db, p) ){
71169     p = 0;
71170   }
71171   assert( !p || p->xCmp );
71172   return p;
71173 }
71174
71175 /*
71176 ** This routine is called on a collation sequence before it is used to
71177 ** check that it is defined. An undefined collation sequence exists when
71178 ** a database is loaded that contains references to collation sequences
71179 ** that have not been defined by sqlite3_create_collation() etc.
71180 **
71181 ** If required, this routine calls the 'collation needed' callback to
71182 ** request a definition of the collating sequence. If this doesn't work, 
71183 ** an equivalent collating sequence that uses a text encoding different
71184 ** from the main database is substituted, if one is available.
71185 */
71186 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
71187   if( pColl ){
71188     const char *zName = pColl->zName;
71189     sqlite3 *db = pParse->db;
71190     CollSeq *p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
71191     if( !p ){
71192       sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
71193       pParse->nErr++;
71194       return SQLITE_ERROR;
71195     }
71196     assert( p==pColl );
71197   }
71198   return SQLITE_OK;
71199 }
71200
71201
71202
71203 /*
71204 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
71205 ** specified by zName and nName is not found and parameter 'create' is
71206 ** true, then create a new entry. Otherwise return NULL.
71207 **
71208 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
71209 ** array of three CollSeq structures. The first is the collation sequence
71210 ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
71211 **
71212 ** Stored immediately after the three collation sequences is a copy of
71213 ** the collation sequence name. A pointer to this string is stored in
71214 ** each collation sequence structure.
71215 */
71216 static CollSeq *findCollSeqEntry(
71217   sqlite3 *db,          /* Database connection */
71218   const char *zName,    /* Name of the collating sequence */
71219   int create            /* Create a new entry if true */
71220 ){
71221   CollSeq *pColl;
71222   int nName = sqlite3Strlen30(zName);
71223   pColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
71224
71225   if( 0==pColl && create ){
71226     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
71227     if( pColl ){
71228       CollSeq *pDel = 0;
71229       pColl[0].zName = (char*)&pColl[3];
71230       pColl[0].enc = SQLITE_UTF8;
71231       pColl[1].zName = (char*)&pColl[3];
71232       pColl[1].enc = SQLITE_UTF16LE;
71233       pColl[2].zName = (char*)&pColl[3];
71234       pColl[2].enc = SQLITE_UTF16BE;
71235       memcpy(pColl[0].zName, zName, nName);
71236       pColl[0].zName[nName] = 0;
71237       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, nName, pColl);
71238
71239       /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
71240       ** return the pColl pointer to be deleted (because it wasn't added
71241       ** to the hash table).
71242       */
71243       assert( pDel==0 || pDel==pColl );
71244       if( pDel!=0 ){
71245         db->mallocFailed = 1;
71246         sqlite3DbFree(db, pDel);
71247         pColl = 0;
71248       }
71249     }
71250   }
71251   return pColl;
71252 }
71253
71254 /*
71255 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
71256 ** Return the CollSeq* pointer for the collation sequence named zName
71257 ** for the encoding 'enc' from the database 'db'.
71258 **
71259 ** If the entry specified is not found and 'create' is true, then create a
71260 ** new entry.  Otherwise return NULL.
71261 **
71262 ** A separate function sqlite3LocateCollSeq() is a wrapper around
71263 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
71264 ** if necessary and generates an error message if the collating sequence
71265 ** cannot be found.
71266 **
71267 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
71268 */
71269 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
71270   sqlite3 *db,
71271   u8 enc,
71272   const char *zName,
71273   int create
71274 ){
71275   CollSeq *pColl;
71276   if( zName ){
71277     pColl = findCollSeqEntry(db, zName, create);
71278   }else{
71279     pColl = db->pDfltColl;
71280   }
71281   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
71282   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
71283   if( pColl ) pColl += enc-1;
71284   return pColl;
71285 }
71286
71287 /* During the search for the best function definition, this procedure
71288 ** is called to test how well the function passed as the first argument
71289 ** matches the request for a function with nArg arguments in a system
71290 ** that uses encoding enc. The value returned indicates how well the
71291 ** request is matched. A higher value indicates a better match.
71292 **
71293 ** The returned value is always between 0 and 6, as follows:
71294 **
71295 ** 0: Not a match, or if nArg<0 and the function is has no implementation.
71296 ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
71297 **    encoding is requested, or vice versa.
71298 ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
71299 **    requested, or vice versa.
71300 ** 3: A variable arguments function using the same text encoding.
71301 ** 4: A function with the exact number of arguments requested that
71302 **    prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
71303 ** 5: A function with the exact number of arguments requested that
71304 **    prefers UTF-16LE when UTF-16BE is requested, or vice versa.
71305 ** 6: An exact match.
71306 **
71307 */
71308 static int matchQuality(FuncDef *p, int nArg, u8 enc){
71309   int match = 0;
71310   if( p->nArg==-1 || p->nArg==nArg 
71311    || (nArg==-1 && (p->xFunc!=0 || p->xStep!=0))
71312   ){
71313     match = 1;
71314     if( p->nArg==nArg || nArg==-1 ){
71315       match = 4;
71316     }
71317     if( enc==p->iPrefEnc ){
71318       match += 2;
71319     }
71320     else if( (enc==SQLITE_UTF16LE && p->iPrefEnc==SQLITE_UTF16BE) ||
71321              (enc==SQLITE_UTF16BE && p->iPrefEnc==SQLITE_UTF16LE) ){
71322       match += 1;
71323     }
71324   }
71325   return match;
71326 }
71327
71328 /*
71329 ** Search a FuncDefHash for a function with the given name.  Return
71330 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
71331 */
71332 static FuncDef *functionSearch(
71333   FuncDefHash *pHash,  /* Hash table to search */
71334   int h,               /* Hash of the name */
71335   const char *zFunc,   /* Name of function */
71336   int nFunc            /* Number of bytes in zFunc */
71337 ){
71338   FuncDef *p;
71339   for(p=pHash->a[h]; p; p=p->pHash){
71340     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
71341       return p;
71342     }
71343   }
71344   return 0;
71345 }
71346
71347 /*
71348 ** Insert a new FuncDef into a FuncDefHash hash table.
71349 */
71350 SQLITE_PRIVATE void sqlite3FuncDefInsert(
71351   FuncDefHash *pHash,  /* The hash table into which to insert */
71352   FuncDef *pDef        /* The function definition to insert */
71353 ){
71354   FuncDef *pOther;
71355   int nName = sqlite3Strlen30(pDef->zName);
71356   u8 c1 = (u8)pDef->zName[0];
71357   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
71358   pOther = functionSearch(pHash, h, pDef->zName, nName);
71359   if( pOther ){
71360     assert( pOther!=pDef && pOther->pNext!=pDef );
71361     pDef->pNext = pOther->pNext;
71362     pOther->pNext = pDef;
71363   }else{
71364     pDef->pNext = 0;
71365     pDef->pHash = pHash->a[h];
71366     pHash->a[h] = pDef;
71367   }
71368 }
71369   
71370   
71371
71372 /*
71373 ** Locate a user function given a name, a number of arguments and a flag
71374 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
71375 ** pointer to the FuncDef structure that defines that function, or return
71376 ** NULL if the function does not exist.
71377 **
71378 ** If the createFlag argument is true, then a new (blank) FuncDef
71379 ** structure is created and liked into the "db" structure if a
71380 ** no matching function previously existed.  When createFlag is true
71381 ** and the nArg parameter is -1, then only a function that accepts
71382 ** any number of arguments will be returned.
71383 **
71384 ** If createFlag is false and nArg is -1, then the first valid
71385 ** function found is returned.  A function is valid if either xFunc
71386 ** or xStep is non-zero.
71387 **
71388 ** If createFlag is false, then a function with the required name and
71389 ** number of arguments may be returned even if the eTextRep flag does not
71390 ** match that requested.
71391 */
71392 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
71393   sqlite3 *db,       /* An open database */
71394   const char *zName, /* Name of the function.  Not null-terminated */
71395   int nName,         /* Number of characters in the name */
71396   int nArg,          /* Number of arguments.  -1 means any number */
71397   u8 enc,            /* Preferred text encoding */
71398   int createFlag     /* Create new entry if true and does not otherwise exist */
71399 ){
71400   FuncDef *p;         /* Iterator variable */
71401   FuncDef *pBest = 0; /* Best match found so far */
71402   int bestScore = 0;  /* Score of best match */
71403   int h;              /* Hash value */
71404
71405
71406   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
71407   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
71408
71409   /* First search for a match amongst the application-defined functions.
71410   */
71411   p = functionSearch(&db->aFunc, h, zName, nName);
71412   while( p ){
71413     int score = matchQuality(p, nArg, enc);
71414     if( score>bestScore ){
71415       pBest = p;
71416       bestScore = score;
71417     }
71418     p = p->pNext;
71419   }
71420
71421   /* If no match is found, search the built-in functions.
71422   **
71423   ** Except, if createFlag is true, that means that we are trying to
71424   ** install a new function.  Whatever FuncDef structure is returned will
71425   ** have fields overwritten with new information appropriate for the
71426   ** new function.  But the FuncDefs for built-in functions are read-only.
71427   ** So we must not search for built-ins when creating a new function.
71428   */ 
71429   if( !createFlag && !pBest ){
71430     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
71431     p = functionSearch(pHash, h, zName, nName);
71432     while( p ){
71433       int score = matchQuality(p, nArg, enc);
71434       if( score>bestScore ){
71435         pBest = p;
71436         bestScore = score;
71437       }
71438       p = p->pNext;
71439     }
71440   }
71441
71442   /* If the createFlag parameter is true and the search did not reveal an
71443   ** exact match for the name, number of arguments and encoding, then add a
71444   ** new entry to the hash table and return it.
71445   */
71446   if( createFlag && (bestScore<6 || pBest->nArg!=nArg) && 
71447       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
71448     pBest->zName = (char *)&pBest[1];
71449     pBest->nArg = (u16)nArg;
71450     pBest->iPrefEnc = enc;
71451     memcpy(pBest->zName, zName, nName);
71452     pBest->zName[nName] = 0;
71453     sqlite3FuncDefInsert(&db->aFunc, pBest);
71454   }
71455
71456   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
71457     return pBest;
71458   }
71459   return 0;
71460 }
71461
71462 /*
71463 ** Free all resources held by the schema structure. The void* argument points
71464 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
71465 ** pointer itself, it just cleans up subsiduary resources (i.e. the contents
71466 ** of the schema hash tables).
71467 **
71468 ** The Schema.cache_size variable is not cleared.
71469 */
71470 SQLITE_PRIVATE void sqlite3SchemaFree(void *p){
71471   Hash temp1;
71472   Hash temp2;
71473   HashElem *pElem;
71474   Schema *pSchema = (Schema *)p;
71475
71476   temp1 = pSchema->tblHash;
71477   temp2 = pSchema->trigHash;
71478   sqlite3HashInit(&pSchema->trigHash);
71479   sqlite3HashClear(&pSchema->idxHash);
71480   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
71481     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
71482   }
71483   sqlite3HashClear(&temp2);
71484   sqlite3HashInit(&pSchema->tblHash);
71485   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
71486     Table *pTab = sqliteHashData(pElem);
71487     assert( pTab->dbMem==0 );
71488     sqlite3DeleteTable(pTab);
71489   }
71490   sqlite3HashClear(&temp1);
71491   sqlite3HashClear(&pSchema->fkeyHash);
71492   pSchema->pSeqTab = 0;
71493   pSchema->flags &= ~DB_SchemaLoaded;
71494 }
71495
71496 /*
71497 ** Find and return the schema associated with a BTree.  Create
71498 ** a new one if necessary.
71499 */
71500 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
71501   Schema * p;
71502   if( pBt ){
71503     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaFree);
71504   }else{
71505     p = (Schema *)sqlite3MallocZero(sizeof(Schema));
71506   }
71507   if( !p ){
71508     db->mallocFailed = 1;
71509   }else if ( 0==p->file_format ){
71510     sqlite3HashInit(&p->tblHash);
71511     sqlite3HashInit(&p->idxHash);
71512     sqlite3HashInit(&p->trigHash);
71513     sqlite3HashInit(&p->fkeyHash);
71514     p->enc = SQLITE_UTF8;
71515   }
71516   return p;
71517 }
71518
71519 /************** End of callback.c ********************************************/
71520 /************** Begin file delete.c ******************************************/
71521 /*
71522 ** 2001 September 15
71523 **
71524 ** The author disclaims copyright to this source code.  In place of
71525 ** a legal notice, here is a blessing:
71526 **
71527 **    May you do good and not evil.
71528 **    May you find forgiveness for yourself and forgive others.
71529 **    May you share freely, never taking more than you give.
71530 **
71531 *************************************************************************
71532 ** This file contains C code routines that are called by the parser
71533 ** in order to generate code for DELETE FROM statements.
71534 */
71535
71536 /*
71537 ** Look up every table that is named in pSrc.  If any table is not found,
71538 ** add an error message to pParse->zErrMsg and return NULL.  If all tables
71539 ** are found, return a pointer to the last table.
71540 */
71541 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
71542   struct SrcList_item *pItem = pSrc->a;
71543   Table *pTab;
71544   assert( pItem && pSrc->nSrc==1 );
71545   pTab = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
71546   sqlite3DeleteTable(pItem->pTab);
71547   pItem->pTab = pTab;
71548   if( pTab ){
71549     pTab->nRef++;
71550   }
71551   if( sqlite3IndexedByLookup(pParse, pItem) ){
71552     pTab = 0;
71553   }
71554   return pTab;
71555 }
71556
71557 /*
71558 ** Check to make sure the given table is writable.  If it is not
71559 ** writable, generate an error message and return 1.  If it is
71560 ** writable return 0;
71561 */
71562 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
71563   /* A table is not writable under the following circumstances:
71564   **
71565   **   1) It is a virtual table and no implementation of the xUpdate method
71566   **      has been provided, or
71567   **   2) It is a system table (i.e. sqlite_master), this call is not
71568   **      part of a nested parse and writable_schema pragma has not 
71569   **      been specified.
71570   **
71571   ** In either case leave an error message in pParse and return non-zero.
71572   */
71573   if( ( IsVirtual(pTab) 
71574      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
71575    || ( (pTab->tabFlags & TF_Readonly)!=0
71576      && (pParse->db->flags & SQLITE_WriteSchema)==0
71577      && pParse->nested==0 )
71578   ){
71579     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
71580     return 1;
71581   }
71582
71583 #ifndef SQLITE_OMIT_VIEW
71584   if( !viewOk && pTab->pSelect ){
71585     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
71586     return 1;
71587   }
71588 #endif
71589   return 0;
71590 }
71591
71592
71593 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
71594 /*
71595 ** Evaluate a view and store its result in an ephemeral table.  The
71596 ** pWhere argument is an optional WHERE clause that restricts the
71597 ** set of rows in the view that are to be added to the ephemeral table.
71598 */
71599 SQLITE_PRIVATE void sqlite3MaterializeView(
71600   Parse *pParse,       /* Parsing context */
71601   Table *pView,        /* View definition */
71602   Expr *pWhere,        /* Optional WHERE clause to be added */
71603   int iCur             /* Cursor number for ephemerial table */
71604 ){
71605   SelectDest dest;
71606   Select *pDup;
71607   sqlite3 *db = pParse->db;
71608
71609   pDup = sqlite3SelectDup(db, pView->pSelect, 0);
71610   if( pWhere ){
71611     SrcList *pFrom;
71612     
71613     pWhere = sqlite3ExprDup(db, pWhere, 0);
71614     pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
71615     if( pFrom ){
71616       assert( pFrom->nSrc==1 );
71617       pFrom->a[0].zAlias = sqlite3DbStrDup(db, pView->zName);
71618       pFrom->a[0].pSelect = pDup;
71619       assert( pFrom->a[0].pOn==0 );
71620       assert( pFrom->a[0].pUsing==0 );
71621     }else{
71622       sqlite3SelectDelete(db, pDup);
71623     }
71624     pDup = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
71625   }
71626   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
71627   sqlite3Select(pParse, pDup, &dest);
71628   sqlite3SelectDelete(db, pDup);
71629 }
71630 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
71631
71632 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
71633 /*
71634 ** Generate an expression tree to implement the WHERE, ORDER BY,
71635 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
71636 **
71637 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
71638 **                            \__________________________/
71639 **                               pLimitWhere (pInClause)
71640 */
71641 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
71642   Parse *pParse,               /* The parser context */
71643   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
71644   Expr *pWhere,                /* The WHERE clause.  May be null */
71645   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
71646   Expr *pLimit,                /* The LIMIT clause.  May be null */
71647   Expr *pOffset,               /* The OFFSET clause.  May be null */
71648   char *zStmtType              /* Either DELETE or UPDATE.  For error messages. */
71649 ){
71650   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
71651   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
71652   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
71653   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
71654   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
71655   Select *pSelect = NULL;      /* Complete SELECT tree */
71656
71657   /* Check that there isn't an ORDER BY without a LIMIT clause.
71658   */
71659   if( pOrderBy && (pLimit == 0) ) {
71660     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
71661     pParse->parseError = 1;
71662     goto limit_where_cleanup_2;
71663   }
71664
71665   /* We only need to generate a select expression if there
71666   ** is a limit/offset term to enforce.
71667   */
71668   if( pLimit == 0 ) {
71669     /* if pLimit is null, pOffset will always be null as well. */
71670     assert( pOffset == 0 );
71671     return pWhere;
71672   }
71673
71674   /* Generate a select expression tree to enforce the limit/offset 
71675   ** term for the DELETE or UPDATE statement.  For example:
71676   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
71677   ** becomes:
71678   **   DELETE FROM table_a WHERE rowid IN ( 
71679   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
71680   **   );
71681   */
71682
71683   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
71684   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
71685   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
71686   if( pEList == 0 ) goto limit_where_cleanup_2;
71687
71688   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
71689   ** and the SELECT subtree. */
71690   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
71691   if( pSelectSrc == 0 ) {
71692     sqlite3ExprListDelete(pParse->db, pEList);
71693     goto limit_where_cleanup_2;
71694   }
71695
71696   /* generate the SELECT expression tree. */
71697   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
71698                              pOrderBy,0,pLimit,pOffset);
71699   if( pSelect == 0 ) return 0;
71700
71701   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
71702   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
71703   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
71704   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
71705   if( pInClause == 0 ) goto limit_where_cleanup_1;
71706
71707   pInClause->x.pSelect = pSelect;
71708   pInClause->flags |= EP_xIsSelect;
71709   sqlite3ExprSetHeight(pParse, pInClause);
71710   return pInClause;
71711
71712   /* something went wrong. clean up anything allocated. */
71713 limit_where_cleanup_1:
71714   sqlite3SelectDelete(pParse->db, pSelect);
71715   return 0;
71716
71717 limit_where_cleanup_2:
71718   sqlite3ExprDelete(pParse->db, pWhere);
71719   sqlite3ExprListDelete(pParse->db, pOrderBy);
71720   sqlite3ExprDelete(pParse->db, pLimit);
71721   sqlite3ExprDelete(pParse->db, pOffset);
71722   return 0;
71723 }
71724 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
71725
71726 /*
71727 ** Generate code for a DELETE FROM statement.
71728 **
71729 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
71730 **                 \________/       \________________/
71731 **                  pTabList              pWhere
71732 */
71733 SQLITE_PRIVATE void sqlite3DeleteFrom(
71734   Parse *pParse,         /* The parser context */
71735   SrcList *pTabList,     /* The table from which we should delete things */
71736   Expr *pWhere           /* The WHERE clause.  May be null */
71737 ){
71738   Vdbe *v;               /* The virtual database engine */
71739   Table *pTab;           /* The table from which records will be deleted */
71740   const char *zDb;       /* Name of database holding pTab */
71741   int end, addr = 0;     /* A couple addresses of generated code */
71742   int i;                 /* Loop counter */
71743   WhereInfo *pWInfo;     /* Information about the WHERE clause */
71744   Index *pIdx;           /* For looping over indices of the table */
71745   int iCur;              /* VDBE Cursor number for pTab */
71746   sqlite3 *db;           /* Main database structure */
71747   AuthContext sContext;  /* Authorization context */
71748   NameContext sNC;       /* Name context to resolve expressions in */
71749   int iDb;               /* Database number */
71750   int memCnt = -1;       /* Memory cell used for change counting */
71751   int rcauth;            /* Value returned by authorization callback */
71752
71753 #ifndef SQLITE_OMIT_TRIGGER
71754   int isView;                  /* True if attempting to delete from a view */
71755   Trigger *pTrigger;           /* List of table triggers, if required */
71756 #endif
71757
71758   memset(&sContext, 0, sizeof(sContext));
71759   db = pParse->db;
71760   if( pParse->nErr || db->mallocFailed ){
71761     goto delete_from_cleanup;
71762   }
71763   assert( pTabList->nSrc==1 );
71764
71765   /* Locate the table which we want to delete.  This table has to be
71766   ** put in an SrcList structure because some of the subroutines we
71767   ** will be calling are designed to work with multiple tables and expect
71768   ** an SrcList* parameter instead of just a Table* parameter.
71769   */
71770   pTab = sqlite3SrcListLookup(pParse, pTabList);
71771   if( pTab==0 )  goto delete_from_cleanup;
71772
71773   /* Figure out if we have any triggers and if the table being
71774   ** deleted from is a view
71775   */
71776 #ifndef SQLITE_OMIT_TRIGGER
71777   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
71778   isView = pTab->pSelect!=0;
71779 #else
71780 # define pTrigger 0
71781 # define isView 0
71782 #endif
71783 #ifdef SQLITE_OMIT_VIEW
71784 # undef isView
71785 # define isView 0
71786 #endif
71787
71788   /* If pTab is really a view, make sure it has been initialized.
71789   */
71790   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
71791     goto delete_from_cleanup;
71792   }
71793
71794   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
71795     goto delete_from_cleanup;
71796   }
71797   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
71798   assert( iDb<db->nDb );
71799   zDb = db->aDb[iDb].zName;
71800   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
71801   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
71802   if( rcauth==SQLITE_DENY ){
71803     goto delete_from_cleanup;
71804   }
71805   assert(!isView || pTrigger);
71806
71807   /* Assign  cursor number to the table and all its indices.
71808   */
71809   assert( pTabList->nSrc==1 );
71810   iCur = pTabList->a[0].iCursor = pParse->nTab++;
71811   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
71812     pParse->nTab++;
71813   }
71814
71815   /* Start the view context
71816   */
71817   if( isView ){
71818     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
71819   }
71820
71821   /* Begin generating code.
71822   */
71823   v = sqlite3GetVdbe(pParse);
71824   if( v==0 ){
71825     goto delete_from_cleanup;
71826   }
71827   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
71828   sqlite3BeginWriteOperation(pParse, 1, iDb);
71829
71830   /* If we are trying to delete from a view, realize that view into
71831   ** a ephemeral table.
71832   */
71833 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
71834   if( isView ){
71835     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
71836   }
71837 #endif
71838
71839   /* Resolve the column names in the WHERE clause.
71840   */
71841   memset(&sNC, 0, sizeof(sNC));
71842   sNC.pParse = pParse;
71843   sNC.pSrcList = pTabList;
71844   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
71845     goto delete_from_cleanup;
71846   }
71847
71848   /* Initialize the counter of the number of rows deleted, if
71849   ** we are counting rows.
71850   */
71851   if( db->flags & SQLITE_CountRows ){
71852     memCnt = ++pParse->nMem;
71853     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
71854   }
71855
71856 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
71857   /* Special case: A DELETE without a WHERE clause deletes everything.
71858   ** It is easier just to erase the whole table. Prior to version 3.6.5,
71859   ** this optimization caused the row change count (the value returned by 
71860   ** API function sqlite3_count_changes) to be set incorrectly.  */
71861   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) 
71862    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
71863   ){
71864     assert( !isView );
71865     sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
71866                       pTab->zName, P4_STATIC);
71867     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
71868       assert( pIdx->pSchema==pTab->pSchema );
71869       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
71870     }
71871   }else
71872 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
71873   /* The usual case: There is a WHERE clause so we have to scan through
71874   ** the table and pick which records to delete.
71875   */
71876   {
71877     int iRowSet = ++pParse->nMem;   /* Register for rowset of rows to delete */
71878     int iRowid = ++pParse->nMem;    /* Used for storing rowid values. */
71879     int regRowid;                   /* Actual register containing rowids */
71880
71881     /* Collect rowids of every row to be deleted.
71882     */
71883     sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
71884     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0,WHERE_DUPLICATES_OK);
71885     if( pWInfo==0 ) goto delete_from_cleanup;
71886     regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
71887     sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
71888     if( db->flags & SQLITE_CountRows ){
71889       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
71890     }
71891     sqlite3WhereEnd(pWInfo);
71892
71893     /* Delete every item whose key was written to the list during the
71894     ** database scan.  We have to delete items after the scan is complete
71895     ** because deleting an item can change the scan order.  */
71896     end = sqlite3VdbeMakeLabel(v);
71897
71898     /* Unless this is a view, open cursors for the table we are 
71899     ** deleting from and all its indices. If this is a view, then the
71900     ** only effect this statement has is to fire the INSTEAD OF 
71901     ** triggers.  */
71902     if( !isView ){
71903       sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
71904     }
71905
71906     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
71907
71908     /* Delete the row */
71909 #ifndef SQLITE_OMIT_VIRTUALTABLE
71910     if( IsVirtual(pTab) ){
71911       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
71912       sqlite3VtabMakeWritable(pParse, pTab);
71913       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
71914       sqlite3MayAbort(pParse);
71915     }else
71916 #endif
71917     {
71918       int count = (pParse->nested==0);    /* True to count changes */
71919       sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
71920     }
71921
71922     /* End of the delete loop */
71923     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
71924     sqlite3VdbeResolveLabel(v, end);
71925
71926     /* Close the cursors open on the table and its indexes. */
71927     if( !isView && !IsVirtual(pTab) ){
71928       for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
71929         sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx->tnum);
71930       }
71931       sqlite3VdbeAddOp1(v, OP_Close, iCur);
71932     }
71933   }
71934
71935   /* Update the sqlite_sequence table by storing the content of the
71936   ** maximum rowid counter values recorded while inserting into
71937   ** autoincrement tables.
71938   */
71939   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
71940     sqlite3AutoincrementEnd(pParse);
71941   }
71942
71943   /* Return the number of rows that were deleted. If this routine is 
71944   ** generating code because of a call to sqlite3NestedParse(), do not
71945   ** invoke the callback function.
71946   */
71947   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
71948     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
71949     sqlite3VdbeSetNumCols(v, 1);
71950     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
71951   }
71952
71953 delete_from_cleanup:
71954   sqlite3AuthContextPop(&sContext);
71955   sqlite3SrcListDelete(db, pTabList);
71956   sqlite3ExprDelete(db, pWhere);
71957   return;
71958 }
71959 /* Make sure "isView" and other macros defined above are undefined. Otherwise
71960 ** thely may interfere with compilation of other functions in this file
71961 ** (or in another file, if this file becomes part of the amalgamation).  */
71962 #ifdef isView
71963  #undef isView
71964 #endif
71965 #ifdef pTrigger
71966  #undef pTrigger
71967 #endif
71968
71969 /*
71970 ** This routine generates VDBE code that causes a single row of a
71971 ** single table to be deleted.
71972 **
71973 ** The VDBE must be in a particular state when this routine is called.
71974 ** These are the requirements:
71975 **
71976 **   1.  A read/write cursor pointing to pTab, the table containing the row
71977 **       to be deleted, must be opened as cursor number $iCur.
71978 **
71979 **   2.  Read/write cursors for all indices of pTab must be open as
71980 **       cursor number base+i for the i-th index.
71981 **
71982 **   3.  The record number of the row to be deleted must be stored in
71983 **       memory cell iRowid.
71984 **
71985 ** This routine generates code to remove both the table record and all 
71986 ** index entries that point to that record.
71987 */
71988 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
71989   Parse *pParse,     /* Parsing context */
71990   Table *pTab,       /* Table containing the row to be deleted */
71991   int iCur,          /* Cursor number for the table */
71992   int iRowid,        /* Memory cell that contains the rowid to delete */
71993   int count,         /* If non-zero, increment the row change counter */
71994   Trigger *pTrigger, /* List of triggers to (potentially) fire */
71995   int onconf         /* Default ON CONFLICT policy for triggers */
71996 ){
71997   Vdbe *v = pParse->pVdbe;        /* Vdbe */
71998   int iOld = 0;                   /* First register in OLD.* array */
71999   int iLabel;                     /* Label resolved to end of generated code */
72000
72001   /* Vdbe is guaranteed to have been allocated by this stage. */
72002   assert( v );
72003
72004   /* Seek cursor iCur to the row to delete. If this row no longer exists 
72005   ** (this can happen if a trigger program has already deleted it), do
72006   ** not attempt to delete it or fire any DELETE triggers.  */
72007   iLabel = sqlite3VdbeMakeLabel(v);
72008   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
72009  
72010   /* If there are any triggers to fire, allocate a range of registers to
72011   ** use for the old.* references in the triggers.  */
72012   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
72013     u32 mask;                     /* Mask of OLD.* columns in use */
72014     int iCol;                     /* Iterator used while populating OLD.* */
72015
72016     /* TODO: Could use temporary registers here. Also could attempt to
72017     ** avoid copying the contents of the rowid register.  */
72018     mask = sqlite3TriggerColmask(
72019         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
72020     );
72021     mask |= sqlite3FkOldmask(pParse, pTab);
72022     iOld = pParse->nMem+1;
72023     pParse->nMem += (1 + pTab->nCol);
72024
72025     /* Populate the OLD.* pseudo-table register array. These values will be 
72026     ** used by any BEFORE and AFTER triggers that exist.  */
72027     sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
72028     for(iCol=0; iCol<pTab->nCol; iCol++){
72029       if( mask==0xffffffff || mask&(1<<iCol) ){
72030         int iTarget = iOld + iCol + 1;
72031         sqlite3VdbeAddOp3(v, OP_Column, iCur, iCol, iTarget);
72032         sqlite3ColumnDefault(v, pTab, iCol, iTarget);
72033       }
72034     }
72035
72036     /* Invoke BEFORE DELETE trigger programs. */
72037     sqlite3CodeRowTrigger(pParse, pTrigger, 
72038         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
72039     );
72040
72041     /* Seek the cursor to the row to be deleted again. It may be that
72042     ** the BEFORE triggers coded above have already removed the row
72043     ** being deleted. Do not attempt to delete the row a second time, and 
72044     ** do not fire AFTER triggers.  */
72045     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
72046
72047     /* Do FK processing. This call checks that any FK constraints that
72048     ** refer to this table (i.e. constraints attached to other tables) 
72049     ** are not violated by deleting this row.  */
72050     sqlite3FkCheck(pParse, pTab, iOld, 0);
72051   }
72052
72053   /* Delete the index and table entries. Skip this step if pTab is really
72054   ** a view (in which case the only effect of the DELETE statement is to
72055   ** fire the INSTEAD OF triggers).  */ 
72056   if( pTab->pSelect==0 ){
72057     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
72058     sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count?OPFLAG_NCHANGE:0));
72059     if( count ){
72060       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
72061     }
72062   }
72063
72064   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
72065   ** handle rows (possibly in other tables) that refer via a foreign key
72066   ** to the row just deleted. */ 
72067   sqlite3FkActions(pParse, pTab, 0, iOld);
72068
72069   /* Invoke AFTER DELETE trigger programs. */
72070   sqlite3CodeRowTrigger(pParse, pTrigger, 
72071       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
72072   );
72073
72074   /* Jump here if the row had already been deleted before any BEFORE
72075   ** trigger programs were invoked. Or if a trigger program throws a 
72076   ** RAISE(IGNORE) exception.  */
72077   sqlite3VdbeResolveLabel(v, iLabel);
72078 }
72079
72080 /*
72081 ** This routine generates VDBE code that causes the deletion of all
72082 ** index entries associated with a single row of a single table.
72083 **
72084 ** The VDBE must be in a particular state when this routine is called.
72085 ** These are the requirements:
72086 **
72087 **   1.  A read/write cursor pointing to pTab, the table containing the row
72088 **       to be deleted, must be opened as cursor number "iCur".
72089 **
72090 **   2.  Read/write cursors for all indices of pTab must be open as
72091 **       cursor number iCur+i for the i-th index.
72092 **
72093 **   3.  The "iCur" cursor must be pointing to the row that is to be
72094 **       deleted.
72095 */
72096 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
72097   Parse *pParse,     /* Parsing and code generating context */
72098   Table *pTab,       /* Table containing the row to be deleted */
72099   int iCur,          /* Cursor number for the table */
72100   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
72101 ){
72102   int i;
72103   Index *pIdx;
72104   int r1;
72105
72106   for(i=1, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
72107     if( aRegIdx!=0 && aRegIdx[i-1]==0 ) continue;
72108     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, 0);
72109     sqlite3VdbeAddOp3(pParse->pVdbe, OP_IdxDelete, iCur+i, r1,pIdx->nColumn+1);
72110   }
72111 }
72112
72113 /*
72114 ** Generate code that will assemble an index key and put it in register
72115 ** regOut.  The key with be for index pIdx which is an index on pTab.
72116 ** iCur is the index of a cursor open on the pTab table and pointing to
72117 ** the entry that needs indexing.
72118 **
72119 ** Return a register number which is the first in a block of
72120 ** registers that holds the elements of the index key.  The
72121 ** block of registers has already been deallocated by the time
72122 ** this routine returns.
72123 */
72124 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
72125   Parse *pParse,     /* Parsing context */
72126   Index *pIdx,       /* The index for which to generate a key */
72127   int iCur,          /* Cursor number for the pIdx->pTable table */
72128   int regOut,        /* Write the new index key to this register */
72129   int doMakeRec      /* Run the OP_MakeRecord instruction if true */
72130 ){
72131   Vdbe *v = pParse->pVdbe;
72132   int j;
72133   Table *pTab = pIdx->pTable;
72134   int regBase;
72135   int nCol;
72136
72137   nCol = pIdx->nColumn;
72138   regBase = sqlite3GetTempRange(pParse, nCol+1);
72139   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase+nCol);
72140   for(j=0; j<nCol; j++){
72141     int idx = pIdx->aiColumn[j];
72142     if( idx==pTab->iPKey ){
72143       sqlite3VdbeAddOp2(v, OP_SCopy, regBase+nCol, regBase+j);
72144     }else{
72145       sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase+j);
72146       sqlite3ColumnDefault(v, pTab, idx, -1);
72147     }
72148   }
72149   if( doMakeRec ){
72150     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol+1, regOut);
72151     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
72152   }
72153   sqlite3ReleaseTempRange(pParse, regBase, nCol+1);
72154   return regBase;
72155 }
72156
72157 /************** End of delete.c **********************************************/
72158 /************** Begin file func.c ********************************************/
72159 /*
72160 ** 2002 February 23
72161 **
72162 ** The author disclaims copyright to this source code.  In place of
72163 ** a legal notice, here is a blessing:
72164 **
72165 **    May you do good and not evil.
72166 **    May you find forgiveness for yourself and forgive others.
72167 **    May you share freely, never taking more than you give.
72168 **
72169 *************************************************************************
72170 ** This file contains the C functions that implement various SQL
72171 ** functions of SQLite.  
72172 **
72173 ** There is only one exported symbol in this file - the function
72174 ** sqliteRegisterBuildinFunctions() found at the bottom of the file.
72175 ** All other code has file scope.
72176 */
72177
72178 /*
72179 ** Return the collating function associated with a function.
72180 */
72181 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
72182   return context->pColl;
72183 }
72184
72185 /*
72186 ** Implementation of the non-aggregate min() and max() functions
72187 */
72188 static void minmaxFunc(
72189   sqlite3_context *context,
72190   int argc,
72191   sqlite3_value **argv
72192 ){
72193   int i;
72194   int mask;    /* 0 for min() or 0xffffffff for max() */
72195   int iBest;
72196   CollSeq *pColl;
72197
72198   assert( argc>1 );
72199   mask = sqlite3_user_data(context)==0 ? 0 : -1;
72200   pColl = sqlite3GetFuncCollSeq(context);
72201   assert( pColl );
72202   assert( mask==-1 || mask==0 );
72203   iBest = 0;
72204   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
72205   for(i=1; i<argc; i++){
72206     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
72207     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
72208       testcase( mask==0 );
72209       iBest = i;
72210     }
72211   }
72212   sqlite3_result_value(context, argv[iBest]);
72213 }
72214
72215 /*
72216 ** Return the type of the argument.
72217 */
72218 static void typeofFunc(
72219   sqlite3_context *context,
72220   int NotUsed,
72221   sqlite3_value **argv
72222 ){
72223   const char *z = 0;
72224   UNUSED_PARAMETER(NotUsed);
72225   switch( sqlite3_value_type(argv[0]) ){
72226     case SQLITE_INTEGER: z = "integer"; break;
72227     case SQLITE_TEXT:    z = "text";    break;
72228     case SQLITE_FLOAT:   z = "real";    break;
72229     case SQLITE_BLOB:    z = "blob";    break;
72230     default:             z = "null";    break;
72231   }
72232   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
72233 }
72234
72235
72236 /*
72237 ** Implementation of the length() function
72238 */
72239 static void lengthFunc(
72240   sqlite3_context *context,
72241   int argc,
72242   sqlite3_value **argv
72243 ){
72244   int len;
72245
72246   assert( argc==1 );
72247   UNUSED_PARAMETER(argc);
72248   switch( sqlite3_value_type(argv[0]) ){
72249     case SQLITE_BLOB:
72250     case SQLITE_INTEGER:
72251     case SQLITE_FLOAT: {
72252       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
72253       break;
72254     }
72255     case SQLITE_TEXT: {
72256       const unsigned char *z = sqlite3_value_text(argv[0]);
72257       if( z==0 ) return;
72258       len = 0;
72259       while( *z ){
72260         len++;
72261         SQLITE_SKIP_UTF8(z);
72262       }
72263       sqlite3_result_int(context, len);
72264       break;
72265     }
72266     default: {
72267       sqlite3_result_null(context);
72268       break;
72269     }
72270   }
72271 }
72272
72273 /*
72274 ** Implementation of the abs() function.
72275 **
72276 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
72277 ** the numeric argument X. 
72278 */
72279 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
72280   assert( argc==1 );
72281   UNUSED_PARAMETER(argc);
72282   switch( sqlite3_value_type(argv[0]) ){
72283     case SQLITE_INTEGER: {
72284       i64 iVal = sqlite3_value_int64(argv[0]);
72285       if( iVal<0 ){
72286         if( (iVal<<1)==0 ){
72287           /* IMP: R-35460-15084 If X is the integer -9223372036854775807 then
72288           ** abs(X) throws an integer overflow error since there is no
72289           ** equivalent positive 64-bit two complement value. */
72290           sqlite3_result_error(context, "integer overflow", -1);
72291           return;
72292         }
72293         iVal = -iVal;
72294       } 
72295       sqlite3_result_int64(context, iVal);
72296       break;
72297     }
72298     case SQLITE_NULL: {
72299       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
72300       sqlite3_result_null(context);
72301       break;
72302     }
72303     default: {
72304       /* Because sqlite3_value_double() returns 0.0 if the argument is not
72305       ** something that can be converted into a number, we have:
72306       ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
72307       ** cannot be converted to a numeric value. 
72308       */
72309       double rVal = sqlite3_value_double(argv[0]);
72310       if( rVal<0 ) rVal = -rVal;
72311       sqlite3_result_double(context, rVal);
72312       break;
72313     }
72314   }
72315 }
72316
72317 /*
72318 ** Implementation of the substr() function.
72319 **
72320 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
72321 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
72322 ** of x.  If x is text, then we actually count UTF-8 characters.
72323 ** If x is a blob, then we count bytes.
72324 **
72325 ** If p1 is negative, then we begin abs(p1) from the end of x[].
72326 **
72327 ** If p2 is negative, return the p2 characters preceeding p1.
72328 */
72329 static void substrFunc(
72330   sqlite3_context *context,
72331   int argc,
72332   sqlite3_value **argv
72333 ){
72334   const unsigned char *z;
72335   const unsigned char *z2;
72336   int len;
72337   int p0type;
72338   i64 p1, p2;
72339   int negP2 = 0;
72340
72341   assert( argc==3 || argc==2 );
72342   if( sqlite3_value_type(argv[1])==SQLITE_NULL
72343    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
72344   ){
72345     return;
72346   }
72347   p0type = sqlite3_value_type(argv[0]);
72348   p1 = sqlite3_value_int(argv[1]);
72349   if( p0type==SQLITE_BLOB ){
72350     len = sqlite3_value_bytes(argv[0]);
72351     z = sqlite3_value_blob(argv[0]);
72352     if( z==0 ) return;
72353     assert( len==sqlite3_value_bytes(argv[0]) );
72354   }else{
72355     z = sqlite3_value_text(argv[0]);
72356     if( z==0 ) return;
72357     len = 0;
72358     if( p1<0 ){
72359       for(z2=z; *z2; len++){
72360         SQLITE_SKIP_UTF8(z2);
72361       }
72362     }
72363   }
72364   if( argc==3 ){
72365     p2 = sqlite3_value_int(argv[2]);
72366     if( p2<0 ){
72367       p2 = -p2;
72368       negP2 = 1;
72369     }
72370   }else{
72371     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
72372   }
72373   if( p1<0 ){
72374     p1 += len;
72375     if( p1<0 ){
72376       p2 += p1;
72377       if( p2<0 ) p2 = 0;
72378       p1 = 0;
72379     }
72380   }else if( p1>0 ){
72381     p1--;
72382   }else if( p2>0 ){
72383     p2--;
72384   }
72385   if( negP2 ){
72386     p1 -= p2;
72387     if( p1<0 ){
72388       p2 += p1;
72389       p1 = 0;
72390     }
72391   }
72392   assert( p1>=0 && p2>=0 );
72393   if( p0type!=SQLITE_BLOB ){
72394     while( *z && p1 ){
72395       SQLITE_SKIP_UTF8(z);
72396       p1--;
72397     }
72398     for(z2=z; *z2 && p2; p2--){
72399       SQLITE_SKIP_UTF8(z2);
72400     }
72401     sqlite3_result_text(context, (char*)z, (int)(z2-z), SQLITE_TRANSIENT);
72402   }else{
72403     if( p1+p2>len ){
72404       p2 = len-p1;
72405       if( p2<0 ) p2 = 0;
72406     }
72407     sqlite3_result_blob(context, (char*)&z[p1], (int)p2, SQLITE_TRANSIENT);
72408   }
72409 }
72410
72411 /*
72412 ** Implementation of the round() function
72413 */
72414 #ifndef SQLITE_OMIT_FLOATING_POINT
72415 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
72416   int n = 0;
72417   double r;
72418   char *zBuf;
72419   assert( argc==1 || argc==2 );
72420   if( argc==2 ){
72421     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
72422     n = sqlite3_value_int(argv[1]);
72423     if( n>30 ) n = 30;
72424     if( n<0 ) n = 0;
72425   }
72426   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
72427   r = sqlite3_value_double(argv[0]);
72428   /* If Y==0 and X will fit in a 64-bit int,
72429   ** handle the rounding directly,
72430   ** otherwise use printf.
72431   */
72432   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
72433     r = (double)((sqlite_int64)(r+0.5));
72434   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
72435     r = -(double)((sqlite_int64)((-r)+0.5));
72436   }else{
72437     zBuf = sqlite3_mprintf("%.*f",n,r);
72438     if( zBuf==0 ){
72439       sqlite3_result_error_nomem(context);
72440       return;
72441     }
72442     sqlite3AtoF(zBuf, &r);
72443     sqlite3_free(zBuf);
72444   }
72445   sqlite3_result_double(context, r);
72446 }
72447 #endif
72448
72449 /*
72450 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
72451 ** allocation fails, call sqlite3_result_error_nomem() to notify
72452 ** the database handle that malloc() has failed and return NULL.
72453 ** If nByte is larger than the maximum string or blob length, then
72454 ** raise an SQLITE_TOOBIG exception and return NULL.
72455 */
72456 static void *contextMalloc(sqlite3_context *context, i64 nByte){
72457   char *z;
72458   sqlite3 *db = sqlite3_context_db_handle(context);
72459   assert( nByte>0 );
72460   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
72461   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
72462   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
72463     sqlite3_result_error_toobig(context);
72464     z = 0;
72465   }else{
72466     z = sqlite3Malloc((int)nByte);
72467     if( !z ){
72468       sqlite3_result_error_nomem(context);
72469     }
72470   }
72471   return z;
72472 }
72473
72474 /*
72475 ** Implementation of the upper() and lower() SQL functions.
72476 */
72477 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
72478   char *z1;
72479   const char *z2;
72480   int i, n;
72481   UNUSED_PARAMETER(argc);
72482   z2 = (char*)sqlite3_value_text(argv[0]);
72483   n = sqlite3_value_bytes(argv[0]);
72484   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
72485   assert( z2==(char*)sqlite3_value_text(argv[0]) );
72486   if( z2 ){
72487     z1 = contextMalloc(context, ((i64)n)+1);
72488     if( z1 ){
72489       memcpy(z1, z2, n+1);
72490       for(i=0; z1[i]; i++){
72491         z1[i] = (char)sqlite3Toupper(z1[i]);
72492       }
72493       sqlite3_result_text(context, z1, -1, sqlite3_free);
72494     }
72495   }
72496 }
72497 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
72498   u8 *z1;
72499   const char *z2;
72500   int i, n;
72501   UNUSED_PARAMETER(argc);
72502   z2 = (char*)sqlite3_value_text(argv[0]);
72503   n = sqlite3_value_bytes(argv[0]);
72504   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
72505   assert( z2==(char*)sqlite3_value_text(argv[0]) );
72506   if( z2 ){
72507     z1 = contextMalloc(context, ((i64)n)+1);
72508     if( z1 ){
72509       memcpy(z1, z2, n+1);
72510       for(i=0; z1[i]; i++){
72511         z1[i] = sqlite3Tolower(z1[i]);
72512       }
72513       sqlite3_result_text(context, (char *)z1, -1, sqlite3_free);
72514     }
72515   }
72516 }
72517
72518
72519 #if 0  /* This function is never used. */
72520 /*
72521 ** The COALESCE() and IFNULL() functions used to be implemented as shown
72522 ** here.  But now they are implemented as VDBE code so that unused arguments
72523 ** do not have to be computed.  This legacy implementation is retained as
72524 ** comment.
72525 */
72526 /*
72527 ** Implementation of the IFNULL(), NVL(), and COALESCE() functions.  
72528 ** All three do the same thing.  They return the first non-NULL
72529 ** argument.
72530 */
72531 static void ifnullFunc(
72532   sqlite3_context *context,
72533   int argc,
72534   sqlite3_value **argv
72535 ){
72536   int i;
72537   for(i=0; i<argc; i++){
72538     if( SQLITE_NULL!=sqlite3_value_type(argv[i]) ){
72539       sqlite3_result_value(context, argv[i]);
72540       break;
72541     }
72542   }
72543 }
72544 #endif /* NOT USED */
72545 #define ifnullFunc versionFunc   /* Substitute function - never called */
72546
72547 /*
72548 ** Implementation of random().  Return a random integer.  
72549 */
72550 static void randomFunc(
72551   sqlite3_context *context,
72552   int NotUsed,
72553   sqlite3_value **NotUsed2
72554 ){
72555   sqlite_int64 r;
72556   UNUSED_PARAMETER2(NotUsed, NotUsed2);
72557   sqlite3_randomness(sizeof(r), &r);
72558   if( r<0 ){
72559     /* We need to prevent a random number of 0x8000000000000000 
72560     ** (or -9223372036854775808) since when you do abs() of that
72561     ** number of you get the same value back again.  To do this
72562     ** in a way that is testable, mask the sign bit off of negative
72563     ** values, resulting in a positive value.  Then take the 
72564     ** 2s complement of that positive value.  The end result can
72565     ** therefore be no less than -9223372036854775807.
72566     */
72567     r = -(r ^ (((sqlite3_int64)1)<<63));
72568   }
72569   sqlite3_result_int64(context, r);
72570 }
72571
72572 /*
72573 ** Implementation of randomblob(N).  Return a random blob
72574 ** that is N bytes long.
72575 */
72576 static void randomBlob(
72577   sqlite3_context *context,
72578   int argc,
72579   sqlite3_value **argv
72580 ){
72581   int n;
72582   unsigned char *p;
72583   assert( argc==1 );
72584   UNUSED_PARAMETER(argc);
72585   n = sqlite3_value_int(argv[0]);
72586   if( n<1 ){
72587     n = 1;
72588   }
72589   p = contextMalloc(context, n);
72590   if( p ){
72591     sqlite3_randomness(n, p);
72592     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
72593   }
72594 }
72595
72596 /*
72597 ** Implementation of the last_insert_rowid() SQL function.  The return
72598 ** value is the same as the sqlite3_last_insert_rowid() API function.
72599 */
72600 static void last_insert_rowid(
72601   sqlite3_context *context, 
72602   int NotUsed, 
72603   sqlite3_value **NotUsed2
72604 ){
72605   sqlite3 *db = sqlite3_context_db_handle(context);
72606   UNUSED_PARAMETER2(NotUsed, NotUsed2);
72607   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
72608   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
72609   ** function. */
72610   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
72611 }
72612
72613 /*
72614 ** Implementation of the changes() SQL function.
72615 **
72616 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
72617 ** around the sqlite3_changes() C/C++ function and hence follows the same
72618 ** rules for counting changes.
72619 */
72620 static void changes(
72621   sqlite3_context *context,
72622   int NotUsed,
72623   sqlite3_value **NotUsed2
72624 ){
72625   sqlite3 *db = sqlite3_context_db_handle(context);
72626   UNUSED_PARAMETER2(NotUsed, NotUsed2);
72627   sqlite3_result_int(context, sqlite3_changes(db));
72628 }
72629
72630 /*
72631 ** Implementation of the total_changes() SQL function.  The return value is
72632 ** the same as the sqlite3_total_changes() API function.
72633 */
72634 static void total_changes(
72635   sqlite3_context *context,
72636   int NotUsed,
72637   sqlite3_value **NotUsed2
72638 ){
72639   sqlite3 *db = sqlite3_context_db_handle(context);
72640   UNUSED_PARAMETER2(NotUsed, NotUsed2);
72641   /* IMP: R-52756-41993 This function is a wrapper around the
72642   ** sqlite3_total_changes() C/C++ interface. */
72643   sqlite3_result_int(context, sqlite3_total_changes(db));
72644 }
72645
72646 /*
72647 ** A structure defining how to do GLOB-style comparisons.
72648 */
72649 struct compareInfo {
72650   u8 matchAll;
72651   u8 matchOne;
72652   u8 matchSet;
72653   u8 noCase;
72654 };
72655
72656 /*
72657 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
72658 ** character is exactly one byte in size.  Also, all characters are
72659 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
72660 ** whereas only characters less than 0x80 do in ASCII.
72661 */
72662 #if defined(SQLITE_EBCDIC)
72663 # define sqlite3Utf8Read(A,C)    (*(A++))
72664 # define GlogUpperToLower(A)     A = sqlite3UpperToLower[A]
72665 #else
72666 # define GlogUpperToLower(A)     if( A<0x80 ){ A = sqlite3UpperToLower[A]; }
72667 #endif
72668
72669 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
72670 /* The correct SQL-92 behavior is for the LIKE operator to ignore
72671 ** case.  Thus  'a' LIKE 'A' would be true. */
72672 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
72673 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
72674 ** is case sensitive causing 'a' LIKE 'A' to be false */
72675 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
72676
72677 /*
72678 ** Compare two UTF-8 strings for equality where the first string can
72679 ** potentially be a "glob" expression.  Return true (1) if they
72680 ** are the same and false (0) if they are different.
72681 **
72682 ** Globbing rules:
72683 **
72684 **      '*'       Matches any sequence of zero or more characters.
72685 **
72686 **      '?'       Matches exactly one character.
72687 **
72688 **     [...]      Matches one character from the enclosed list of
72689 **                characters.
72690 **
72691 **     [^...]     Matches one character not in the enclosed list.
72692 **
72693 ** With the [...] and [^...] matching, a ']' character can be included
72694 ** in the list by making it the first character after '[' or '^'.  A
72695 ** range of characters can be specified using '-'.  Example:
72696 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
72697 ** it the last character in the list.
72698 **
72699 ** This routine is usually quick, but can be N**2 in the worst case.
72700 **
72701 ** Hints: to match '*' or '?', put them in "[]".  Like this:
72702 **
72703 **         abc[*]xyz        Matches "abc*xyz" only
72704 */
72705 static int patternCompare(
72706   const u8 *zPattern,              /* The glob pattern */
72707   const u8 *zString,               /* The string to compare against the glob */
72708   const struct compareInfo *pInfo, /* Information about how to do the compare */
72709   const int esc                    /* The escape character */
72710 ){
72711   int c, c2;
72712   int invert;
72713   int seen;
72714   u8 matchOne = pInfo->matchOne;
72715   u8 matchAll = pInfo->matchAll;
72716   u8 matchSet = pInfo->matchSet;
72717   u8 noCase = pInfo->noCase; 
72718   int prevEscape = 0;     /* True if the previous character was 'escape' */
72719
72720   while( (c = sqlite3Utf8Read(zPattern,&zPattern))!=0 ){
72721     if( !prevEscape && c==matchAll ){
72722       while( (c=sqlite3Utf8Read(zPattern,&zPattern)) == matchAll
72723                || c == matchOne ){
72724         if( c==matchOne && sqlite3Utf8Read(zString, &zString)==0 ){
72725           return 0;
72726         }
72727       }
72728       if( c==0 ){
72729         return 1;
72730       }else if( c==esc ){
72731         c = sqlite3Utf8Read(zPattern, &zPattern);
72732         if( c==0 ){
72733           return 0;
72734         }
72735       }else if( c==matchSet ){
72736         assert( esc==0 );         /* This is GLOB, not LIKE */
72737         assert( matchSet<0x80 );  /* '[' is a single-byte character */
72738         while( *zString && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
72739           SQLITE_SKIP_UTF8(zString);
72740         }
72741         return *zString!=0;
72742       }
72743       while( (c2 = sqlite3Utf8Read(zString,&zString))!=0 ){
72744         if( noCase ){
72745           GlogUpperToLower(c2);
72746           GlogUpperToLower(c);
72747           while( c2 != 0 && c2 != c ){
72748             c2 = sqlite3Utf8Read(zString, &zString);
72749             GlogUpperToLower(c2);
72750           }
72751         }else{
72752           while( c2 != 0 && c2 != c ){
72753             c2 = sqlite3Utf8Read(zString, &zString);
72754           }
72755         }
72756         if( c2==0 ) return 0;
72757         if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
72758       }
72759       return 0;
72760     }else if( !prevEscape && c==matchOne ){
72761       if( sqlite3Utf8Read(zString, &zString)==0 ){
72762         return 0;
72763       }
72764     }else if( c==matchSet ){
72765       int prior_c = 0;
72766       assert( esc==0 );    /* This only occurs for GLOB, not LIKE */
72767       seen = 0;
72768       invert = 0;
72769       c = sqlite3Utf8Read(zString, &zString);
72770       if( c==0 ) return 0;
72771       c2 = sqlite3Utf8Read(zPattern, &zPattern);
72772       if( c2=='^' ){
72773         invert = 1;
72774         c2 = sqlite3Utf8Read(zPattern, &zPattern);
72775       }
72776       if( c2==']' ){
72777         if( c==']' ) seen = 1;
72778         c2 = sqlite3Utf8Read(zPattern, &zPattern);
72779       }
72780       while( c2 && c2!=']' ){
72781         if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
72782           c2 = sqlite3Utf8Read(zPattern, &zPattern);
72783           if( c>=prior_c && c<=c2 ) seen = 1;
72784           prior_c = 0;
72785         }else{
72786           if( c==c2 ){
72787             seen = 1;
72788           }
72789           prior_c = c2;
72790         }
72791         c2 = sqlite3Utf8Read(zPattern, &zPattern);
72792       }
72793       if( c2==0 || (seen ^ invert)==0 ){
72794         return 0;
72795       }
72796     }else if( esc==c && !prevEscape ){
72797       prevEscape = 1;
72798     }else{
72799       c2 = sqlite3Utf8Read(zString, &zString);
72800       if( noCase ){
72801         GlogUpperToLower(c);
72802         GlogUpperToLower(c2);
72803       }
72804       if( c!=c2 ){
72805         return 0;
72806       }
72807       prevEscape = 0;
72808     }
72809   }
72810   return *zString==0;
72811 }
72812
72813 /*
72814 ** Count the number of times that the LIKE operator (or GLOB which is
72815 ** just a variation of LIKE) gets called.  This is used for testing
72816 ** only.
72817 */
72818 #ifdef SQLITE_TEST
72819 SQLITE_API int sqlite3_like_count = 0;
72820 #endif
72821
72822
72823 /*
72824 ** Implementation of the like() SQL function.  This function implements
72825 ** the build-in LIKE operator.  The first argument to the function is the
72826 ** pattern and the second argument is the string.  So, the SQL statements:
72827 **
72828 **       A LIKE B
72829 **
72830 ** is implemented as like(B,A).
72831 **
72832 ** This same function (with a different compareInfo structure) computes
72833 ** the GLOB operator.
72834 */
72835 static void likeFunc(
72836   sqlite3_context *context, 
72837   int argc, 
72838   sqlite3_value **argv
72839 ){
72840   const unsigned char *zA, *zB;
72841   int escape = 0;
72842   int nPat;
72843   sqlite3 *db = sqlite3_context_db_handle(context);
72844
72845   zB = sqlite3_value_text(argv[0]);
72846   zA = sqlite3_value_text(argv[1]);
72847
72848   /* Limit the length of the LIKE or GLOB pattern to avoid problems
72849   ** of deep recursion and N*N behavior in patternCompare().
72850   */
72851   nPat = sqlite3_value_bytes(argv[0]);
72852   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
72853   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
72854   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
72855     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
72856     return;
72857   }
72858   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
72859
72860   if( argc==3 ){
72861     /* The escape character string must consist of a single UTF-8 character.
72862     ** Otherwise, return an error.
72863     */
72864     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
72865     if( zEsc==0 ) return;
72866     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
72867       sqlite3_result_error(context, 
72868           "ESCAPE expression must be a single character", -1);
72869       return;
72870     }
72871     escape = sqlite3Utf8Read(zEsc, &zEsc);
72872   }
72873   if( zA && zB ){
72874     struct compareInfo *pInfo = sqlite3_user_data(context);
72875 #ifdef SQLITE_TEST
72876     sqlite3_like_count++;
72877 #endif
72878     
72879     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
72880   }
72881 }
72882
72883 /*
72884 ** Implementation of the NULLIF(x,y) function.  The result is the first
72885 ** argument if the arguments are different.  The result is NULL if the
72886 ** arguments are equal to each other.
72887 */
72888 static void nullifFunc(
72889   sqlite3_context *context,
72890   int NotUsed,
72891   sqlite3_value **argv
72892 ){
72893   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
72894   UNUSED_PARAMETER(NotUsed);
72895   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
72896     sqlite3_result_value(context, argv[0]);
72897   }
72898 }
72899
72900 /*
72901 ** Implementation of the sqlite_version() function.  The result is the version
72902 ** of the SQLite library that is running.
72903 */
72904 static void versionFunc(
72905   sqlite3_context *context,
72906   int NotUsed,
72907   sqlite3_value **NotUsed2
72908 ){
72909   UNUSED_PARAMETER2(NotUsed, NotUsed2);
72910   /* IMP: R-48699-48617 This function is an SQL wrapper around the
72911   ** sqlite3_libversion() C-interface. */
72912   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
72913 }
72914
72915 /*
72916 ** Implementation of the sqlite_source_id() function. The result is a string
72917 ** that identifies the particular version of the source code used to build
72918 ** SQLite.
72919 */
72920 static void sourceidFunc(
72921   sqlite3_context *context,
72922   int NotUsed,
72923   sqlite3_value **NotUsed2
72924 ){
72925   UNUSED_PARAMETER2(NotUsed, NotUsed2);
72926   /* IMP: R-24470-31136 This function is an SQL wrapper around the
72927   ** sqlite3_sourceid() C interface. */
72928   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
72929 }
72930
72931 /*
72932 ** Implementation of the sqlite_compileoption_used() function.
72933 ** The result is an integer that identifies if the compiler option
72934 ** was used to build SQLite.
72935 */
72936 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
72937 static void compileoptionusedFunc(
72938   sqlite3_context *context,
72939   int argc,
72940   sqlite3_value **argv
72941 ){
72942   const char *zOptName;
72943   assert( argc==1 );
72944   UNUSED_PARAMETER(argc);
72945   /* IMP: R-xxxx This function is an SQL wrapper around the
72946   ** sqlite3_compileoption_used() C interface. */
72947   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
72948     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
72949   }
72950 }
72951 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
72952
72953 /*
72954 ** Implementation of the sqlite_compileoption_get() function. 
72955 ** The result is a string that identifies the compiler options 
72956 ** used to build SQLite.
72957 */
72958 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
72959 static void compileoptiongetFunc(
72960   sqlite3_context *context,
72961   int argc,
72962   sqlite3_value **argv
72963 ){
72964   int n;
72965   assert( argc==1 );
72966   UNUSED_PARAMETER(argc);
72967   /* IMP: R-xxxx This function is an SQL wrapper around the
72968   ** sqlite3_compileoption_get() C interface. */
72969   n = sqlite3_value_int(argv[0]);
72970   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
72971 }
72972 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
72973
72974 /* Array for converting from half-bytes (nybbles) into ASCII hex
72975 ** digits. */
72976 static const char hexdigits[] = {
72977   '0', '1', '2', '3', '4', '5', '6', '7',
72978   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
72979 };
72980
72981 /*
72982 ** EXPERIMENTAL - This is not an official function.  The interface may
72983 ** change.  This function may disappear.  Do not write code that depends
72984 ** on this function.
72985 **
72986 ** Implementation of the QUOTE() function.  This function takes a single
72987 ** argument.  If the argument is numeric, the return value is the same as
72988 ** the argument.  If the argument is NULL, the return value is the string
72989 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
72990 ** single-quote escapes.
72991 */
72992 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
72993   assert( argc==1 );
72994   UNUSED_PARAMETER(argc);
72995   switch( sqlite3_value_type(argv[0]) ){
72996     case SQLITE_INTEGER:
72997     case SQLITE_FLOAT: {
72998       sqlite3_result_value(context, argv[0]);
72999       break;
73000     }
73001     case SQLITE_BLOB: {
73002       char *zText = 0;
73003       char const *zBlob = sqlite3_value_blob(argv[0]);
73004       int nBlob = sqlite3_value_bytes(argv[0]);
73005       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
73006       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
73007       if( zText ){
73008         int i;
73009         for(i=0; i<nBlob; i++){
73010           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
73011           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
73012         }
73013         zText[(nBlob*2)+2] = '\'';
73014         zText[(nBlob*2)+3] = '\0';
73015         zText[0] = 'X';
73016         zText[1] = '\'';
73017         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
73018         sqlite3_free(zText);
73019       }
73020       break;
73021     }
73022     case SQLITE_TEXT: {
73023       int i,j;
73024       u64 n;
73025       const unsigned char *zArg = sqlite3_value_text(argv[0]);
73026       char *z;
73027
73028       if( zArg==0 ) return;
73029       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
73030       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
73031       if( z ){
73032         z[0] = '\'';
73033         for(i=0, j=1; zArg[i]; i++){
73034           z[j++] = zArg[i];
73035           if( zArg[i]=='\'' ){
73036             z[j++] = '\'';
73037           }
73038         }
73039         z[j++] = '\'';
73040         z[j] = 0;
73041         sqlite3_result_text(context, z, j, sqlite3_free);
73042       }
73043       break;
73044     }
73045     default: {
73046       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
73047       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
73048       break;
73049     }
73050   }
73051 }
73052
73053 /*
73054 ** The hex() function.  Interpret the argument as a blob.  Return
73055 ** a hexadecimal rendering as text.
73056 */
73057 static void hexFunc(
73058   sqlite3_context *context,
73059   int argc,
73060   sqlite3_value **argv
73061 ){
73062   int i, n;
73063   const unsigned char *pBlob;
73064   char *zHex, *z;
73065   assert( argc==1 );
73066   UNUSED_PARAMETER(argc);
73067   pBlob = sqlite3_value_blob(argv[0]);
73068   n = sqlite3_value_bytes(argv[0]);
73069   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
73070   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
73071   if( zHex ){
73072     for(i=0; i<n; i++, pBlob++){
73073       unsigned char c = *pBlob;
73074       *(z++) = hexdigits[(c>>4)&0xf];
73075       *(z++) = hexdigits[c&0xf];
73076     }
73077     *z = 0;
73078     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
73079   }
73080 }
73081
73082 /*
73083 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
73084 */
73085 static void zeroblobFunc(
73086   sqlite3_context *context,
73087   int argc,
73088   sqlite3_value **argv
73089 ){
73090   i64 n;
73091   sqlite3 *db = sqlite3_context_db_handle(context);
73092   assert( argc==1 );
73093   UNUSED_PARAMETER(argc);
73094   n = sqlite3_value_int64(argv[0]);
73095   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
73096   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
73097   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
73098     sqlite3_result_error_toobig(context);
73099   }else{
73100     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
73101   }
73102 }
73103
73104 /*
73105 ** The replace() function.  Three arguments are all strings: call
73106 ** them A, B, and C. The result is also a string which is derived
73107 ** from A by replacing every occurance of B with C.  The match
73108 ** must be exact.  Collating sequences are not used.
73109 */
73110 static void replaceFunc(
73111   sqlite3_context *context,
73112   int argc,
73113   sqlite3_value **argv
73114 ){
73115   const unsigned char *zStr;        /* The input string A */
73116   const unsigned char *zPattern;    /* The pattern string B */
73117   const unsigned char *zRep;        /* The replacement string C */
73118   unsigned char *zOut;              /* The output */
73119   int nStr;                /* Size of zStr */
73120   int nPattern;            /* Size of zPattern */
73121   int nRep;                /* Size of zRep */
73122   i64 nOut;                /* Maximum size of zOut */
73123   int loopLimit;           /* Last zStr[] that might match zPattern[] */
73124   int i, j;                /* Loop counters */
73125
73126   assert( argc==3 );
73127   UNUSED_PARAMETER(argc);
73128   zStr = sqlite3_value_text(argv[0]);
73129   if( zStr==0 ) return;
73130   nStr = sqlite3_value_bytes(argv[0]);
73131   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
73132   zPattern = sqlite3_value_text(argv[1]);
73133   if( zPattern==0 ){
73134     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
73135             || sqlite3_context_db_handle(context)->mallocFailed );
73136     return;
73137   }
73138   if( zPattern[0]==0 ){
73139     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
73140     sqlite3_result_value(context, argv[0]);
73141     return;
73142   }
73143   nPattern = sqlite3_value_bytes(argv[1]);
73144   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
73145   zRep = sqlite3_value_text(argv[2]);
73146   if( zRep==0 ) return;
73147   nRep = sqlite3_value_bytes(argv[2]);
73148   assert( zRep==sqlite3_value_text(argv[2]) );
73149   nOut = nStr + 1;
73150   assert( nOut<SQLITE_MAX_LENGTH );
73151   zOut = contextMalloc(context, (i64)nOut);
73152   if( zOut==0 ){
73153     return;
73154   }
73155   loopLimit = nStr - nPattern;  
73156   for(i=j=0; i<=loopLimit; i++){
73157     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
73158       zOut[j++] = zStr[i];
73159     }else{
73160       u8 *zOld;
73161       sqlite3 *db = sqlite3_context_db_handle(context);
73162       nOut += nRep - nPattern;
73163       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
73164       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
73165       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
73166         sqlite3_result_error_toobig(context);
73167         sqlite3DbFree(db, zOut);
73168         return;
73169       }
73170       zOld = zOut;
73171       zOut = sqlite3_realloc(zOut, (int)nOut);
73172       if( zOut==0 ){
73173         sqlite3_result_error_nomem(context);
73174         sqlite3DbFree(db, zOld);
73175         return;
73176       }
73177       memcpy(&zOut[j], zRep, nRep);
73178       j += nRep;
73179       i += nPattern-1;
73180     }
73181   }
73182   assert( j+nStr-i+1==nOut );
73183   memcpy(&zOut[j], &zStr[i], nStr-i);
73184   j += nStr - i;
73185   assert( j<=nOut );
73186   zOut[j] = 0;
73187   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
73188 }
73189
73190 /*
73191 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
73192 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
73193 */
73194 static void trimFunc(
73195   sqlite3_context *context,
73196   int argc,
73197   sqlite3_value **argv
73198 ){
73199   const unsigned char *zIn;         /* Input string */
73200   const unsigned char *zCharSet;    /* Set of characters to trim */
73201   int nIn;                          /* Number of bytes in input */
73202   int flags;                        /* 1: trimleft  2: trimright  3: trim */
73203   int i;                            /* Loop counter */
73204   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
73205   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
73206   int nChar;                        /* Number of characters in zCharSet */
73207
73208   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
73209     return;
73210   }
73211   zIn = sqlite3_value_text(argv[0]);
73212   if( zIn==0 ) return;
73213   nIn = sqlite3_value_bytes(argv[0]);
73214   assert( zIn==sqlite3_value_text(argv[0]) );
73215   if( argc==1 ){
73216     static const unsigned char lenOne[] = { 1 };
73217     static unsigned char * const azOne[] = { (u8*)" " };
73218     nChar = 1;
73219     aLen = (u8*)lenOne;
73220     azChar = (unsigned char **)azOne;
73221     zCharSet = 0;
73222   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
73223     return;
73224   }else{
73225     const unsigned char *z;
73226     for(z=zCharSet, nChar=0; *z; nChar++){
73227       SQLITE_SKIP_UTF8(z);
73228     }
73229     if( nChar>0 ){
73230       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
73231       if( azChar==0 ){
73232         return;
73233       }
73234       aLen = (unsigned char*)&azChar[nChar];
73235       for(z=zCharSet, nChar=0; *z; nChar++){
73236         azChar[nChar] = (unsigned char *)z;
73237         SQLITE_SKIP_UTF8(z);
73238         aLen[nChar] = (u8)(z - azChar[nChar]);
73239       }
73240     }
73241   }
73242   if( nChar>0 ){
73243     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
73244     if( flags & 1 ){
73245       while( nIn>0 ){
73246         int len = 0;
73247         for(i=0; i<nChar; i++){
73248           len = aLen[i];
73249           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
73250         }
73251         if( i>=nChar ) break;
73252         zIn += len;
73253         nIn -= len;
73254       }
73255     }
73256     if( flags & 2 ){
73257       while( nIn>0 ){
73258         int len = 0;
73259         for(i=0; i<nChar; i++){
73260           len = aLen[i];
73261           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
73262         }
73263         if( i>=nChar ) break;
73264         nIn -= len;
73265       }
73266     }
73267     if( zCharSet ){
73268       sqlite3_free(azChar);
73269     }
73270   }
73271   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
73272 }
73273
73274
73275 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
73276 ** is only available if the SQLITE_SOUNDEX compile-time option is used
73277 ** when SQLite is built.
73278 */
73279 #ifdef SQLITE_SOUNDEX
73280 /*
73281 ** Compute the soundex encoding of a word.
73282 **
73283 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
73284 ** soundex encoding of the string X. 
73285 */
73286 static void soundexFunc(
73287   sqlite3_context *context,
73288   int argc,
73289   sqlite3_value **argv
73290 ){
73291   char zResult[8];
73292   const u8 *zIn;
73293   int i, j;
73294   static const unsigned char iCode[] = {
73295     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
73296     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
73297     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
73298     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
73299     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
73300     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
73301     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
73302     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
73303   };
73304   assert( argc==1 );
73305   zIn = (u8*)sqlite3_value_text(argv[0]);
73306   if( zIn==0 ) zIn = (u8*)"";
73307   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
73308   if( zIn[i] ){
73309     u8 prevcode = iCode[zIn[i]&0x7f];
73310     zResult[0] = sqlite3Toupper(zIn[i]);
73311     for(j=1; j<4 && zIn[i]; i++){
73312       int code = iCode[zIn[i]&0x7f];
73313       if( code>0 ){
73314         if( code!=prevcode ){
73315           prevcode = code;
73316           zResult[j++] = code + '0';
73317         }
73318       }else{
73319         prevcode = 0;
73320       }
73321     }
73322     while( j<4 ){
73323       zResult[j++] = '0';
73324     }
73325     zResult[j] = 0;
73326     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
73327   }else{
73328     /* IMP: R-64894-50321 The string "?000" is returned if the argument
73329     ** is NULL or contains no ASCII alphabetic characters. */
73330     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
73331   }
73332 }
73333 #endif /* SQLITE_SOUNDEX */
73334
73335 #ifndef SQLITE_OMIT_LOAD_EXTENSION
73336 /*
73337 ** A function that loads a shared-library extension then returns NULL.
73338 */
73339 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
73340   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
73341   const char *zProc;
73342   sqlite3 *db = sqlite3_context_db_handle(context);
73343   char *zErrMsg = 0;
73344
73345   if( argc==2 ){
73346     zProc = (const char *)sqlite3_value_text(argv[1]);
73347   }else{
73348     zProc = 0;
73349   }
73350   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
73351     sqlite3_result_error(context, zErrMsg, -1);
73352     sqlite3_free(zErrMsg);
73353   }
73354 }
73355 #endif
73356
73357
73358 /*
73359 ** An instance of the following structure holds the context of a
73360 ** sum() or avg() aggregate computation.
73361 */
73362 typedef struct SumCtx SumCtx;
73363 struct SumCtx {
73364   double rSum;      /* Floating point sum */
73365   i64 iSum;         /* Integer sum */   
73366   i64 cnt;          /* Number of elements summed */
73367   u8 overflow;      /* True if integer overflow seen */
73368   u8 approx;        /* True if non-integer value was input to the sum */
73369 };
73370
73371 /*
73372 ** Routines used to compute the sum, average, and total.
73373 **
73374 ** The SUM() function follows the (broken) SQL standard which means
73375 ** that it returns NULL if it sums over no inputs.  TOTAL returns
73376 ** 0.0 in that case.  In addition, TOTAL always returns a float where
73377 ** SUM might return an integer if it never encounters a floating point
73378 ** value.  TOTAL never fails, but SUM might through an exception if
73379 ** it overflows an integer.
73380 */
73381 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
73382   SumCtx *p;
73383   int type;
73384   assert( argc==1 );
73385   UNUSED_PARAMETER(argc);
73386   p = sqlite3_aggregate_context(context, sizeof(*p));
73387   type = sqlite3_value_numeric_type(argv[0]);
73388   if( p && type!=SQLITE_NULL ){
73389     p->cnt++;
73390     if( type==SQLITE_INTEGER ){
73391       i64 v = sqlite3_value_int64(argv[0]);
73392       p->rSum += v;
73393       if( (p->approx|p->overflow)==0 ){
73394         i64 iNewSum = p->iSum + v;
73395         int s1 = (int)(p->iSum >> (sizeof(i64)*8-1));
73396         int s2 = (int)(v       >> (sizeof(i64)*8-1));
73397         int s3 = (int)(iNewSum >> (sizeof(i64)*8-1));
73398         p->overflow = ((s1&s2&~s3) | (~s1&~s2&s3))?1:0;
73399         p->iSum = iNewSum;
73400       }
73401     }else{
73402       p->rSum += sqlite3_value_double(argv[0]);
73403       p->approx = 1;
73404     }
73405   }
73406 }
73407 static void sumFinalize(sqlite3_context *context){
73408   SumCtx *p;
73409   p = sqlite3_aggregate_context(context, 0);
73410   if( p && p->cnt>0 ){
73411     if( p->overflow ){
73412       sqlite3_result_error(context,"integer overflow",-1);
73413     }else if( p->approx ){
73414       sqlite3_result_double(context, p->rSum);
73415     }else{
73416       sqlite3_result_int64(context, p->iSum);
73417     }
73418   }
73419 }
73420 static void avgFinalize(sqlite3_context *context){
73421   SumCtx *p;
73422   p = sqlite3_aggregate_context(context, 0);
73423   if( p && p->cnt>0 ){
73424     sqlite3_result_double(context, p->rSum/(double)p->cnt);
73425   }
73426 }
73427 static void totalFinalize(sqlite3_context *context){
73428   SumCtx *p;
73429   p = sqlite3_aggregate_context(context, 0);
73430   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
73431   sqlite3_result_double(context, p ? p->rSum : (double)0);
73432 }
73433
73434 /*
73435 ** The following structure keeps track of state information for the
73436 ** count() aggregate function.
73437 */
73438 typedef struct CountCtx CountCtx;
73439 struct CountCtx {
73440   i64 n;
73441 };
73442
73443 /*
73444 ** Routines to implement the count() aggregate function.
73445 */
73446 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
73447   CountCtx *p;
73448   p = sqlite3_aggregate_context(context, sizeof(*p));
73449   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
73450     p->n++;
73451   }
73452
73453 #ifndef SQLITE_OMIT_DEPRECATED
73454   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
73455   ** sure it still operates correctly, verify that its count agrees with our 
73456   ** internal count when using count(*) and when the total count can be
73457   ** expressed as a 32-bit integer. */
73458   assert( argc==1 || p==0 || p->n>0x7fffffff
73459           || p->n==sqlite3_aggregate_count(context) );
73460 #endif
73461 }   
73462 static void countFinalize(sqlite3_context *context){
73463   CountCtx *p;
73464   p = sqlite3_aggregate_context(context, 0);
73465   sqlite3_result_int64(context, p ? p->n : 0);
73466 }
73467
73468 /*
73469 ** Routines to implement min() and max() aggregate functions.
73470 */
73471 static void minmaxStep(
73472   sqlite3_context *context, 
73473   int NotUsed, 
73474   sqlite3_value **argv
73475 ){
73476   Mem *pArg  = (Mem *)argv[0];
73477   Mem *pBest;
73478   UNUSED_PARAMETER(NotUsed);
73479
73480   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
73481   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
73482   if( !pBest ) return;
73483
73484   if( pBest->flags ){
73485     int max;
73486     int cmp;
73487     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
73488     /* This step function is used for both the min() and max() aggregates,
73489     ** the only difference between the two being that the sense of the
73490     ** comparison is inverted. For the max() aggregate, the
73491     ** sqlite3_user_data() function returns (void *)-1. For min() it
73492     ** returns (void *)db, where db is the sqlite3* database pointer.
73493     ** Therefore the next statement sets variable 'max' to 1 for the max()
73494     ** aggregate, or 0 for min().
73495     */
73496     max = sqlite3_user_data(context)!=0;
73497     cmp = sqlite3MemCompare(pBest, pArg, pColl);
73498     if( (max && cmp<0) || (!max && cmp>0) ){
73499       sqlite3VdbeMemCopy(pBest, pArg);
73500     }
73501   }else{
73502     sqlite3VdbeMemCopy(pBest, pArg);
73503   }
73504 }
73505 static void minMaxFinalize(sqlite3_context *context){
73506   sqlite3_value *pRes;
73507   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
73508   if( pRes ){
73509     if( ALWAYS(pRes->flags) ){
73510       sqlite3_result_value(context, pRes);
73511     }
73512     sqlite3VdbeMemRelease(pRes);
73513   }
73514 }
73515
73516 /*
73517 ** group_concat(EXPR, ?SEPARATOR?)
73518 */
73519 static void groupConcatStep(
73520   sqlite3_context *context,
73521   int argc,
73522   sqlite3_value **argv
73523 ){
73524   const char *zVal;
73525   StrAccum *pAccum;
73526   const char *zSep;
73527   int nVal, nSep;
73528   assert( argc==1 || argc==2 );
73529   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
73530   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
73531
73532   if( pAccum ){
73533     sqlite3 *db = sqlite3_context_db_handle(context);
73534     int firstTerm = pAccum->useMalloc==0;
73535     pAccum->useMalloc = 1;
73536     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
73537     if( !firstTerm ){
73538       if( argc==2 ){
73539         zSep = (char*)sqlite3_value_text(argv[1]);
73540         nSep = sqlite3_value_bytes(argv[1]);
73541       }else{
73542         zSep = ",";
73543         nSep = 1;
73544       }
73545       sqlite3StrAccumAppend(pAccum, zSep, nSep);
73546     }
73547     zVal = (char*)sqlite3_value_text(argv[0]);
73548     nVal = sqlite3_value_bytes(argv[0]);
73549     sqlite3StrAccumAppend(pAccum, zVal, nVal);
73550   }
73551 }
73552 static void groupConcatFinalize(sqlite3_context *context){
73553   StrAccum *pAccum;
73554   pAccum = sqlite3_aggregate_context(context, 0);
73555   if( pAccum ){
73556     if( pAccum->tooBig ){
73557       sqlite3_result_error_toobig(context);
73558     }else if( pAccum->mallocFailed ){
73559       sqlite3_result_error_nomem(context);
73560     }else{    
73561       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
73562                           sqlite3_free);
73563     }
73564   }
73565 }
73566
73567 /*
73568 ** This function registered all of the above C functions as SQL
73569 ** functions.  This should be the only routine in this file with
73570 ** external linkage.
73571 */
73572 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
73573 #ifndef SQLITE_OMIT_ALTERTABLE
73574   sqlite3AlterFunctions(db);
73575 #endif
73576   if( !db->mallocFailed ){
73577     int rc = sqlite3_overload_function(db, "MATCH", 2);
73578     assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
73579     if( rc==SQLITE_NOMEM ){
73580       db->mallocFailed = 1;
73581     }
73582   }
73583 }
73584
73585 /*
73586 ** Set the LIKEOPT flag on the 2-argument function with the given name.
73587 */
73588 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
73589   FuncDef *pDef;
73590   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
73591                              2, SQLITE_UTF8, 0);
73592   if( ALWAYS(pDef) ){
73593     pDef->flags = flagVal;
73594   }
73595 }
73596
73597 /*
73598 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
73599 ** parameter determines whether or not the LIKE operator is case
73600 ** sensitive.  GLOB is always case sensitive.
73601 */
73602 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
73603   struct compareInfo *pInfo;
73604   if( caseSensitive ){
73605     pInfo = (struct compareInfo*)&likeInfoAlt;
73606   }else{
73607     pInfo = (struct compareInfo*)&likeInfoNorm;
73608   }
73609   sqlite3CreateFunc(db, "like", 2, SQLITE_ANY, pInfo, likeFunc, 0, 0);
73610   sqlite3CreateFunc(db, "like", 3, SQLITE_ANY, pInfo, likeFunc, 0, 0);
73611   sqlite3CreateFunc(db, "glob", 2, SQLITE_ANY, 
73612       (struct compareInfo*)&globInfo, likeFunc, 0,0);
73613   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
73614   setLikeOptFlag(db, "like", 
73615       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
73616 }
73617
73618 /*
73619 ** pExpr points to an expression which implements a function.  If
73620 ** it is appropriate to apply the LIKE optimization to that function
73621 ** then set aWc[0] through aWc[2] to the wildcard characters and
73622 ** return TRUE.  If the function is not a LIKE-style function then
73623 ** return FALSE.
73624 */
73625 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
73626   FuncDef *pDef;
73627   if( pExpr->op!=TK_FUNCTION 
73628    || !pExpr->x.pList 
73629    || pExpr->x.pList->nExpr!=2
73630   ){
73631     return 0;
73632   }
73633   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
73634   pDef = sqlite3FindFunction(db, pExpr->u.zToken, 
73635                              sqlite3Strlen30(pExpr->u.zToken),
73636                              2, SQLITE_UTF8, 0);
73637   if( NEVER(pDef==0) || (pDef->flags & SQLITE_FUNC_LIKE)==0 ){
73638     return 0;
73639   }
73640
73641   /* The memcpy() statement assumes that the wildcard characters are
73642   ** the first three statements in the compareInfo structure.  The
73643   ** asserts() that follow verify that assumption
73644   */
73645   memcpy(aWc, pDef->pUserData, 3);
73646   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
73647   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
73648   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
73649   *pIsNocase = (pDef->flags & SQLITE_FUNC_CASE)==0;
73650   return 1;
73651 }
73652
73653 /*
73654 ** All all of the FuncDef structures in the aBuiltinFunc[] array above
73655 ** to the global function hash table.  This occurs at start-time (as
73656 ** a consequence of calling sqlite3_initialize()).
73657 **
73658 ** After this routine runs
73659 */
73660 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
73661   /*
73662   ** The following array holds FuncDef structures for all of the functions
73663   ** defined in this file.
73664   **
73665   ** The array cannot be constant since changes are made to the
73666   ** FuncDef.pHash elements at start-time.  The elements of this array
73667   ** are read-only after initialization is complete.
73668   */
73669   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
73670     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
73671     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
73672     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
73673     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
73674     FUNCTION(trim,               1, 3, 0, trimFunc         ),
73675     FUNCTION(trim,               2, 3, 0, trimFunc         ),
73676     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
73677     FUNCTION(min,                0, 0, 1, 0                ),
73678     AGGREGATE(min,               1, 0, 1, minmaxStep,      minMaxFinalize ),
73679     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
73680     FUNCTION(max,                0, 1, 1, 0                ),
73681     AGGREGATE(max,               1, 1, 1, minmaxStep,      minMaxFinalize ),
73682     FUNCTION(typeof,             1, 0, 0, typeofFunc       ),
73683     FUNCTION(length,             1, 0, 0, lengthFunc       ),
73684     FUNCTION(substr,             2, 0, 0, substrFunc       ),
73685     FUNCTION(substr,             3, 0, 0, substrFunc       ),
73686     FUNCTION(abs,                1, 0, 0, absFunc          ),
73687 #ifndef SQLITE_OMIT_FLOATING_POINT
73688     FUNCTION(round,              1, 0, 0, roundFunc        ),
73689     FUNCTION(round,              2, 0, 0, roundFunc        ),
73690 #endif
73691     FUNCTION(upper,              1, 0, 0, upperFunc        ),
73692     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
73693     FUNCTION(coalesce,           1, 0, 0, 0                ),
73694     FUNCTION(coalesce,           0, 0, 0, 0                ),
73695 /*  FUNCTION(coalesce,          -1, 0, 0, ifnullFunc       ), */
73696     {-1,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"coalesce",0},
73697     FUNCTION(hex,                1, 0, 0, hexFunc          ),
73698 /*  FUNCTION(ifnull,             2, 0, 0, ifnullFunc       ), */
73699     {2,SQLITE_UTF8,SQLITE_FUNC_COALESCE,0,0,ifnullFunc,0,0,"ifnull",0},
73700     FUNCTION(random,             0, 0, 0, randomFunc       ),
73701     FUNCTION(randomblob,         1, 0, 0, randomBlob       ),
73702     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
73703     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
73704     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
73705 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
73706     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
73707     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
73708 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
73709     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
73710     FUNCTION(last_insert_rowid,  0, 0, 0, last_insert_rowid),
73711     FUNCTION(changes,            0, 0, 0, changes          ),
73712     FUNCTION(total_changes,      0, 0, 0, total_changes    ),
73713     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
73714     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
73715   #ifdef SQLITE_SOUNDEX
73716     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
73717   #endif
73718   #ifndef SQLITE_OMIT_LOAD_EXTENSION
73719     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
73720     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
73721   #endif
73722     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
73723     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
73724     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
73725  /* AGGREGATE(count,             0, 0, 0, countStep,       countFinalize  ), */
73726     {0,SQLITE_UTF8,SQLITE_FUNC_COUNT,0,0,0,countStep,countFinalize,"count",0},
73727     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
73728     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
73729     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
73730   
73731     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
73732   #ifdef SQLITE_CASE_SENSITIVE_LIKE
73733     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
73734     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
73735   #else
73736     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
73737     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
73738   #endif
73739   };
73740
73741   int i;
73742   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
73743   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
73744
73745   for(i=0; i<ArraySize(aBuiltinFunc); i++){
73746     sqlite3FuncDefInsert(pHash, &aFunc[i]);
73747   }
73748   sqlite3RegisterDateTimeFunctions();
73749 }
73750
73751 /************** End of func.c ************************************************/
73752 /************** Begin file fkey.c ********************************************/
73753 /*
73754 **
73755 ** The author disclaims copyright to this source code.  In place of
73756 ** a legal notice, here is a blessing:
73757 **
73758 **    May you do good and not evil.
73759 **    May you find forgiveness for yourself and forgive others.
73760 **    May you share freely, never taking more than you give.
73761 **
73762 *************************************************************************
73763 ** This file contains code used by the compiler to add foreign key
73764 ** support to compiled SQL statements.
73765 */
73766
73767 #ifndef SQLITE_OMIT_FOREIGN_KEY
73768 #ifndef SQLITE_OMIT_TRIGGER
73769
73770 /*
73771 ** Deferred and Immediate FKs
73772 ** --------------------------
73773 **
73774 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
73775 ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
73776 ** is returned and the current statement transaction rolled back. If a 
73777 ** deferred foreign key constraint is violated, no action is taken 
73778 ** immediately. However if the application attempts to commit the 
73779 ** transaction before fixing the constraint violation, the attempt fails.
73780 **
73781 ** Deferred constraints are implemented using a simple counter associated
73782 ** with the database handle. The counter is set to zero each time a 
73783 ** database transaction is opened. Each time a statement is executed 
73784 ** that causes a foreign key violation, the counter is incremented. Each
73785 ** time a statement is executed that removes an existing violation from
73786 ** the database, the counter is decremented. When the transaction is
73787 ** committed, the commit fails if the current value of the counter is
73788 ** greater than zero. This scheme has two big drawbacks:
73789 **
73790 **   * When a commit fails due to a deferred foreign key constraint, 
73791 **     there is no way to tell which foreign constraint is not satisfied,
73792 **     or which row it is not satisfied for.
73793 **
73794 **   * If the database contains foreign key violations when the 
73795 **     transaction is opened, this may cause the mechanism to malfunction.
73796 **
73797 ** Despite these problems, this approach is adopted as it seems simpler
73798 ** than the alternatives.
73799 **
73800 ** INSERT operations:
73801 **
73802 **   I.1) For each FK for which the table is the child table, search
73803 **        the parent table for a match. If none is found increment the
73804 **        constraint counter.
73805 **
73806 **   I.2) For each FK for which the table is the parent table, 
73807 **        search the child table for rows that correspond to the new
73808 **        row in the parent table. Decrement the counter for each row
73809 **        found (as the constraint is now satisfied).
73810 **
73811 ** DELETE operations:
73812 **
73813 **   D.1) For each FK for which the table is the child table, 
73814 **        search the parent table for a row that corresponds to the 
73815 **        deleted row in the child table. If such a row is not found, 
73816 **        decrement the counter.
73817 **
73818 **   D.2) For each FK for which the table is the parent table, search 
73819 **        the child table for rows that correspond to the deleted row 
73820 **        in the parent table. For each found increment the counter.
73821 **
73822 ** UPDATE operations:
73823 **
73824 **   An UPDATE command requires that all 4 steps above are taken, but only
73825 **   for FK constraints for which the affected columns are actually 
73826 **   modified (values must be compared at runtime).
73827 **
73828 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
73829 ** This simplifies the implementation a bit.
73830 **
73831 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
73832 ** resolution is considered to delete rows before the new row is inserted.
73833 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
73834 ** is thrown, even if the FK constraint would be satisfied after the new 
73835 ** row is inserted.
73836 **
73837 ** Immediate constraints are usually handled similarly. The only difference 
73838 ** is that the counter used is stored as part of each individual statement
73839 ** object (struct Vdbe). If, after the statement has run, its immediate
73840 ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
73841 ** and the statement transaction is rolled back. An exception is an INSERT
73842 ** statement that inserts a single row only (no triggers). In this case,
73843 ** instead of using a counter, an exception is thrown immediately if the
73844 ** INSERT violates a foreign key constraint. This is necessary as such
73845 ** an INSERT does not open a statement transaction.
73846 **
73847 ** TODO: How should dropping a table be handled? How should renaming a 
73848 ** table be handled?
73849 **
73850 **
73851 ** Query API Notes
73852 ** ---------------
73853 **
73854 ** Before coding an UPDATE or DELETE row operation, the code-generator
73855 ** for those two operations needs to know whether or not the operation
73856 ** requires any FK processing and, if so, which columns of the original
73857 ** row are required by the FK processing VDBE code (i.e. if FKs were
73858 ** implemented using triggers, which of the old.* columns would be 
73859 ** accessed). No information is required by the code-generator before
73860 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
73861 ** generation code to query for this information are:
73862 **
73863 **   sqlite3FkRequired() - Test to see if FK processing is required.
73864 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
73865 **
73866 **
73867 ** Externally accessible module functions
73868 ** --------------------------------------
73869 **
73870 **   sqlite3FkCheck()    - Check for foreign key violations.
73871 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
73872 **   sqlite3FkDelete()   - Delete an FKey structure.
73873 */
73874
73875 /*
73876 ** VDBE Calling Convention
73877 ** -----------------------
73878 **
73879 ** Example:
73880 **
73881 **   For the following INSERT statement:
73882 **
73883 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
73884 **     INSERT INTO t1 VALUES(1, 2, 3.1);
73885 **
73886 **   Register (x):        2    (type integer)
73887 **   Register (x+1):      1    (type integer)
73888 **   Register (x+2):      NULL (type NULL)
73889 **   Register (x+3):      3.1  (type real)
73890 */
73891
73892 /*
73893 ** A foreign key constraint requires that the key columns in the parent
73894 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
73895 ** Given that pParent is the parent table for foreign key constraint pFKey, 
73896 ** search the schema a unique index on the parent key columns. 
73897 **
73898 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
73899 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
73900 ** is set to point to the unique index. 
73901 ** 
73902 ** If the parent key consists of a single column (the foreign key constraint
73903 ** is not a composite foreign key), output variable *paiCol is set to NULL.
73904 ** Otherwise, it is set to point to an allocated array of size N, where
73905 ** N is the number of columns in the parent key. The first element of the
73906 ** array is the index of the child table column that is mapped by the FK
73907 ** constraint to the parent table column stored in the left-most column
73908 ** of index *ppIdx. The second element of the array is the index of the
73909 ** child table column that corresponds to the second left-most column of
73910 ** *ppIdx, and so on.
73911 **
73912 ** If the required index cannot be found, either because:
73913 **
73914 **   1) The named parent key columns do not exist, or
73915 **
73916 **   2) The named parent key columns do exist, but are not subject to a
73917 **      UNIQUE or PRIMARY KEY constraint, or
73918 **
73919 **   3) No parent key columns were provided explicitly as part of the
73920 **      foreign key definition, and the parent table does not have a
73921 **      PRIMARY KEY, or
73922 **
73923 **   4) No parent key columns were provided explicitly as part of the
73924 **      foreign key definition, and the PRIMARY KEY of the parent table 
73925 **      consists of a a different number of columns to the child key in 
73926 **      the child table.
73927 **
73928 ** then non-zero is returned, and a "foreign key mismatch" error loaded
73929 ** into pParse. If an OOM error occurs, non-zero is returned and the
73930 ** pParse->db->mallocFailed flag is set.
73931 */
73932 static int locateFkeyIndex(
73933   Parse *pParse,                  /* Parse context to store any error in */
73934   Table *pParent,                 /* Parent table of FK constraint pFKey */
73935   FKey *pFKey,                    /* Foreign key to find index for */
73936   Index **ppIdx,                  /* OUT: Unique index on parent table */
73937   int **paiCol                    /* OUT: Map of index columns in pFKey */
73938 ){
73939   Index *pIdx = 0;                    /* Value to return via *ppIdx */
73940   int *aiCol = 0;                     /* Value to return via *paiCol */
73941   int nCol = pFKey->nCol;             /* Number of columns in parent key */
73942   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
73943
73944   /* The caller is responsible for zeroing output parameters. */
73945   assert( ppIdx && *ppIdx==0 );
73946   assert( !paiCol || *paiCol==0 );
73947   assert( pParse );
73948
73949   /* If this is a non-composite (single column) foreign key, check if it 
73950   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
73951   ** and *paiCol set to zero and return early. 
73952   **
73953   ** Otherwise, for a composite foreign key (more than one column), allocate
73954   ** space for the aiCol array (returned via output parameter *paiCol).
73955   ** Non-composite foreign keys do not require the aiCol array.
73956   */
73957   if( nCol==1 ){
73958     /* The FK maps to the IPK if any of the following are true:
73959     **
73960     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
73961     **      mapped to the primary key of table pParent, or
73962     **   2) The FK is explicitly mapped to a column declared as INTEGER
73963     **      PRIMARY KEY.
73964     */
73965     if( pParent->iPKey>=0 ){
73966       if( !zKey ) return 0;
73967       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
73968     }
73969   }else if( paiCol ){
73970     assert( nCol>1 );
73971     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
73972     if( !aiCol ) return 1;
73973     *paiCol = aiCol;
73974   }
73975
73976   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
73977     if( pIdx->nColumn==nCol && pIdx->onError!=OE_None ){ 
73978       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
73979       ** of columns. If each indexed column corresponds to a foreign key
73980       ** column of pFKey, then this index is a winner.  */
73981
73982       if( zKey==0 ){
73983         /* If zKey is NULL, then this foreign key is implicitly mapped to 
73984         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
73985         ** identified by the test (Index.autoIndex==2).  */
73986         if( pIdx->autoIndex==2 ){
73987           if( aiCol ){
73988             int i;
73989             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
73990           }
73991           break;
73992         }
73993       }else{
73994         /* If zKey is non-NULL, then this foreign key was declared to
73995         ** map to an explicit list of columns in table pParent. Check if this
73996         ** index matches those columns. Also, check that the index uses
73997         ** the default collation sequences for each column. */
73998         int i, j;
73999         for(i=0; i<nCol; i++){
74000           int iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
74001           char *zDfltColl;                  /* Def. collation for column */
74002           char *zIdxCol;                    /* Name of indexed column */
74003
74004           /* If the index uses a collation sequence that is different from
74005           ** the default collation sequence for the column, this index is
74006           ** unusable. Bail out early in this case.  */
74007           zDfltColl = pParent->aCol[iCol].zColl;
74008           if( !zDfltColl ){
74009             zDfltColl = "BINARY";
74010           }
74011           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
74012
74013           zIdxCol = pParent->aCol[iCol].zName;
74014           for(j=0; j<nCol; j++){
74015             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
74016               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
74017               break;
74018             }
74019           }
74020           if( j==nCol ) break;
74021         }
74022         if( i==nCol ) break;      /* pIdx is usable */
74023       }
74024     }
74025   }
74026
74027   if( !pIdx ){
74028     if( !pParse->disableTriggers ){
74029       sqlite3ErrorMsg(pParse, "foreign key mismatch");
74030     }
74031     sqlite3DbFree(pParse->db, aiCol);
74032     return 1;
74033   }
74034
74035   *ppIdx = pIdx;
74036   return 0;
74037 }
74038
74039 /*
74040 ** This function is called when a row is inserted into or deleted from the 
74041 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
74042 ** on the child table of pFKey, this function is invoked twice for each row
74043 ** affected - once to "delete" the old row, and then again to "insert" the
74044 ** new row.
74045 **
74046 ** Each time it is called, this function generates VDBE code to locate the
74047 ** row in the parent table that corresponds to the row being inserted into 
74048 ** or deleted from the child table. If the parent row can be found, no 
74049 ** special action is taken. Otherwise, if the parent row can *not* be
74050 ** found in the parent table:
74051 **
74052 **   Operation | FK type   | Action taken
74053 **   --------------------------------------------------------------------------
74054 **   INSERT      immediate   Increment the "immediate constraint counter".
74055 **
74056 **   DELETE      immediate   Decrement the "immediate constraint counter".
74057 **
74058 **   INSERT      deferred    Increment the "deferred constraint counter".
74059 **
74060 **   DELETE      deferred    Decrement the "deferred constraint counter".
74061 **
74062 ** These operations are identified in the comment at the top of this file 
74063 ** (fkey.c) as "I.1" and "D.1".
74064 */
74065 static void fkLookupParent(
74066   Parse *pParse,        /* Parse context */
74067   int iDb,              /* Index of database housing pTab */
74068   Table *pTab,          /* Parent table of FK pFKey */
74069   Index *pIdx,          /* Unique index on parent key columns in pTab */
74070   FKey *pFKey,          /* Foreign key constraint */
74071   int *aiCol,           /* Map from parent key columns to child table columns */
74072   int regData,          /* Address of array containing child table row */
74073   int nIncr,            /* Increment constraint counter by this */
74074   int isIgnore          /* If true, pretend pTab contains all NULL values */
74075 ){
74076   int i;                                    /* Iterator variable */
74077   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
74078   int iCur = pParse->nTab - 1;              /* Cursor number to use */
74079   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
74080
74081   /* If nIncr is less than zero, then check at runtime if there are any
74082   ** outstanding constraints to resolve. If there are not, there is no need
74083   ** to check if deleting this row resolves any outstanding violations.
74084   **
74085   ** Check if any of the key columns in the child table row are NULL. If 
74086   ** any are, then the constraint is considered satisfied. No need to 
74087   ** search for a matching row in the parent table.  */
74088   if( nIncr<0 ){
74089     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
74090   }
74091   for(i=0; i<pFKey->nCol; i++){
74092     int iReg = aiCol[i] + regData + 1;
74093     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
74094   }
74095
74096   if( isIgnore==0 ){
74097     if( pIdx==0 ){
74098       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
74099       ** column of the parent table (table pTab).  */
74100       int iMustBeInt;               /* Address of MustBeInt instruction */
74101       int regTemp = sqlite3GetTempReg(pParse);
74102   
74103       /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
74104       ** apply the affinity of the parent key). If this fails, then there
74105       ** is no matching parent key. Before using MustBeInt, make a copy of
74106       ** the value. Otherwise, the value inserted into the child key column
74107       ** will have INTEGER affinity applied to it, which may not be correct.  */
74108       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
74109       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
74110   
74111       /* If the parent table is the same as the child table, and we are about
74112       ** to increment the constraint-counter (i.e. this is an INSERT operation),
74113       ** then check if the row being inserted matches itself. If so, do not
74114       ** increment the constraint-counter.  */
74115       if( pTab==pFKey->pFrom && nIncr==1 ){
74116         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
74117       }
74118   
74119       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
74120       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
74121       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
74122       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
74123       sqlite3VdbeJumpHere(v, iMustBeInt);
74124       sqlite3ReleaseTempReg(pParse, regTemp);
74125     }else{
74126       int nCol = pFKey->nCol;
74127       int regTemp = sqlite3GetTempRange(pParse, nCol);
74128       int regRec = sqlite3GetTempReg(pParse);
74129       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
74130   
74131       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
74132       sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
74133       for(i=0; i<nCol; i++){
74134         sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[i]+1+regData, regTemp+i);
74135       }
74136   
74137       /* If the parent table is the same as the child table, and we are about
74138       ** to increment the constraint-counter (i.e. this is an INSERT operation),
74139       ** then check if the row being inserted matches itself. If so, do not
74140       ** increment the constraint-counter.  */
74141       if( pTab==pFKey->pFrom && nIncr==1 ){
74142         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
74143         for(i=0; i<nCol; i++){
74144           int iChild = aiCol[i]+1+regData;
74145           int iParent = pIdx->aiColumn[i]+1+regData;
74146           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
74147         }
74148         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
74149       }
74150   
74151       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
74152       sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
74153       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
74154   
74155       sqlite3ReleaseTempReg(pParse, regRec);
74156       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
74157     }
74158   }
74159
74160   if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
74161     /* Special case: If this is an INSERT statement that will insert exactly
74162     ** one row into the table, raise a constraint immediately instead of
74163     ** incrementing a counter. This is necessary as the VM code is being
74164     ** generated for will not open a statement transaction.  */
74165     assert( nIncr==1 );
74166     sqlite3HaltConstraint(
74167         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
74168     );
74169   }else{
74170     if( nIncr>0 && pFKey->isDeferred==0 ){
74171       sqlite3ParseToplevel(pParse)->mayAbort = 1;
74172     }
74173     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
74174   }
74175
74176   sqlite3VdbeResolveLabel(v, iOk);
74177   sqlite3VdbeAddOp1(v, OP_Close, iCur);
74178 }
74179
74180 /*
74181 ** This function is called to generate code executed when a row is deleted
74182 ** from the parent table of foreign key constraint pFKey and, if pFKey is 
74183 ** deferred, when a row is inserted into the same table. When generating
74184 ** code for an SQL UPDATE operation, this function may be called twice -
74185 ** once to "delete" the old row and once to "insert" the new row.
74186 **
74187 ** The code generated by this function scans through the rows in the child
74188 ** table that correspond to the parent table row being deleted or inserted.
74189 ** For each child row found, one of the following actions is taken:
74190 **
74191 **   Operation | FK type   | Action taken
74192 **   --------------------------------------------------------------------------
74193 **   DELETE      immediate   Increment the "immediate constraint counter".
74194 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
74195 **                           throw a "foreign key constraint failed" exception.
74196 **
74197 **   INSERT      immediate   Decrement the "immediate constraint counter".
74198 **
74199 **   DELETE      deferred    Increment the "deferred constraint counter".
74200 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
74201 **                           throw a "foreign key constraint failed" exception.
74202 **
74203 **   INSERT      deferred    Decrement the "deferred constraint counter".
74204 **
74205 ** These operations are identified in the comment at the top of this file 
74206 ** (fkey.c) as "I.2" and "D.2".
74207 */
74208 static void fkScanChildren(
74209   Parse *pParse,                  /* Parse context */
74210   SrcList *pSrc,                  /* SrcList containing the table to scan */
74211   Table *pTab,
74212   Index *pIdx,                    /* Foreign key index */
74213   FKey *pFKey,                    /* Foreign key relationship */
74214   int *aiCol,                     /* Map from pIdx cols to child table cols */
74215   int regData,                    /* Referenced table data starts here */
74216   int nIncr                       /* Amount to increment deferred counter by */
74217 ){
74218   sqlite3 *db = pParse->db;       /* Database handle */
74219   int i;                          /* Iterator variable */
74220   Expr *pWhere = 0;               /* WHERE clause to scan with */
74221   NameContext sNameContext;       /* Context used to resolve WHERE clause */
74222   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
74223   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
74224   Vdbe *v = sqlite3GetVdbe(pParse);
74225
74226   assert( !pIdx || pIdx->pTable==pTab );
74227
74228   if( nIncr<0 ){
74229     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
74230   }
74231
74232   /* Create an Expr object representing an SQL expression like:
74233   **
74234   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
74235   **
74236   ** The collation sequence used for the comparison should be that of
74237   ** the parent key columns. The affinity of the parent key column should
74238   ** be applied to each child key value before the comparison takes place.
74239   */
74240   for(i=0; i<pFKey->nCol; i++){
74241     Expr *pLeft;                  /* Value from parent table row */
74242     Expr *pRight;                 /* Column ref to child table */
74243     Expr *pEq;                    /* Expression (pLeft = pRight) */
74244     int iCol;                     /* Index of column in child table */ 
74245     const char *zCol;             /* Name of column in child table */
74246
74247     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
74248     if( pLeft ){
74249       /* Set the collation sequence and affinity of the LHS of each TK_EQ
74250       ** expression to the parent key column defaults.  */
74251       if( pIdx ){
74252         Column *pCol;
74253         iCol = pIdx->aiColumn[i];
74254         pCol = &pIdx->pTable->aCol[iCol];
74255         pLeft->iTable = regData+iCol+1;
74256         pLeft->affinity = pCol->affinity;
74257         pLeft->pColl = sqlite3LocateCollSeq(pParse, pCol->zColl);
74258       }else{
74259         pLeft->iTable = regData;
74260         pLeft->affinity = SQLITE_AFF_INTEGER;
74261       }
74262     }
74263     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
74264     assert( iCol>=0 );
74265     zCol = pFKey->pFrom->aCol[iCol].zName;
74266     pRight = sqlite3Expr(db, TK_ID, zCol);
74267     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
74268     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
74269   }
74270
74271   /* If the child table is the same as the parent table, and this scan
74272   ** is taking place as part of a DELETE operation (operation D.2), omit the
74273   ** row being deleted from the scan by adding ($rowid != rowid) to the WHERE 
74274   ** clause, where $rowid is the rowid of the row being deleted.  */
74275   if( pTab==pFKey->pFrom && nIncr>0 ){
74276     Expr *pEq;                    /* Expression (pLeft = pRight) */
74277     Expr *pLeft;                  /* Value from parent table row */
74278     Expr *pRight;                 /* Column ref to child table */
74279     pLeft = sqlite3Expr(db, TK_REGISTER, 0);
74280     pRight = sqlite3Expr(db, TK_COLUMN, 0);
74281     if( pLeft && pRight ){
74282       pLeft->iTable = regData;
74283       pLeft->affinity = SQLITE_AFF_INTEGER;
74284       pRight->iTable = pSrc->a[0].iCursor;
74285       pRight->iColumn = -1;
74286     }
74287     pEq = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
74288     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
74289   }
74290
74291   /* Resolve the references in the WHERE clause. */
74292   memset(&sNameContext, 0, sizeof(NameContext));
74293   sNameContext.pSrcList = pSrc;
74294   sNameContext.pParse = pParse;
74295   sqlite3ResolveExprNames(&sNameContext, pWhere);
74296
74297   /* Create VDBE to loop through the entries in pSrc that match the WHERE
74298   ** clause. If the constraint is not deferred, throw an exception for
74299   ** each row found. Otherwise, for deferred constraints, increment the
74300   ** deferred constraint counter by nIncr for each row selected.  */
74301   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0);
74302   if( nIncr>0 && pFKey->isDeferred==0 ){
74303     sqlite3ParseToplevel(pParse)->mayAbort = 1;
74304   }
74305   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
74306   if( pWInfo ){
74307     sqlite3WhereEnd(pWInfo);
74308   }
74309
74310   /* Clean up the WHERE clause constructed above. */
74311   sqlite3ExprDelete(db, pWhere);
74312   if( iFkIfZero ){
74313     sqlite3VdbeJumpHere(v, iFkIfZero);
74314   }
74315 }
74316
74317 /*
74318 ** This function returns a pointer to the head of a linked list of FK
74319 ** constraints for which table pTab is the parent table. For example,
74320 ** given the following schema:
74321 **
74322 **   CREATE TABLE t1(a PRIMARY KEY);
74323 **   CREATE TABLE t2(b REFERENCES t1(a);
74324 **
74325 ** Calling this function with table "t1" as an argument returns a pointer
74326 ** to the FKey structure representing the foreign key constraint on table
74327 ** "t2". Calling this function with "t2" as the argument would return a
74328 ** NULL pointer (as there are no FK constraints for which t2 is the parent
74329 ** table).
74330 */
74331 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
74332   int nName = sqlite3Strlen30(pTab->zName);
74333   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName, nName);
74334 }
74335
74336 /*
74337 ** The second argument is a Trigger structure allocated by the 
74338 ** fkActionTrigger() routine. This function deletes the Trigger structure
74339 ** and all of its sub-components.
74340 **
74341 ** The Trigger structure or any of its sub-components may be allocated from
74342 ** the lookaside buffer belonging to database handle dbMem.
74343 */
74344 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
74345   if( p ){
74346     TriggerStep *pStep = p->step_list;
74347     sqlite3ExprDelete(dbMem, pStep->pWhere);
74348     sqlite3ExprListDelete(dbMem, pStep->pExprList);
74349     sqlite3SelectDelete(dbMem, pStep->pSelect);
74350     sqlite3ExprDelete(dbMem, p->pWhen);
74351     sqlite3DbFree(dbMem, p);
74352   }
74353 }
74354
74355 /*
74356 ** This function is called to generate code that runs when table pTab is
74357 ** being dropped from the database. The SrcList passed as the second argument
74358 ** to this function contains a single entry guaranteed to resolve to
74359 ** table pTab.
74360 **
74361 ** Normally, no code is required. However, if either
74362 **
74363 **   (a) The table is the parent table of a FK constraint, or
74364 **   (b) The table is the child table of a deferred FK constraint and it is
74365 **       determined at runtime that there are outstanding deferred FK 
74366 **       constraint violations in the database,
74367 **
74368 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
74369 ** the table from the database. Triggers are disabled while running this
74370 ** DELETE, but foreign key actions are not.
74371 */
74372 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
74373   sqlite3 *db = pParse->db;
74374   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
74375     int iSkip = 0;
74376     Vdbe *v = sqlite3GetVdbe(pParse);
74377
74378     assert( v );                  /* VDBE has already been allocated */
74379     if( sqlite3FkReferences(pTab)==0 ){
74380       /* Search for a deferred foreign key constraint for which this table
74381       ** is the child table. If one cannot be found, return without 
74382       ** generating any VDBE code. If one can be found, then jump over
74383       ** the entire DELETE if there are no outstanding deferred constraints
74384       ** when this statement is run.  */
74385       FKey *p;
74386       for(p=pTab->pFKey; p; p=p->pNextFrom){
74387         if( p->isDeferred ) break;
74388       }
74389       if( !p ) return;
74390       iSkip = sqlite3VdbeMakeLabel(v);
74391       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip);
74392     }
74393
74394     pParse->disableTriggers = 1;
74395     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
74396     pParse->disableTriggers = 0;
74397
74398     /* If the DELETE has generated immediate foreign key constraint 
74399     ** violations, halt the VDBE and return an error at this point, before
74400     ** any modifications to the schema are made. This is because statement
74401     ** transactions are not able to rollback schema changes.  */
74402     sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
74403     sqlite3HaltConstraint(
74404         pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
74405     );
74406
74407     if( iSkip ){
74408       sqlite3VdbeResolveLabel(v, iSkip);
74409     }
74410   }
74411 }
74412
74413 /*
74414 ** This function is called when inserting, deleting or updating a row of
74415 ** table pTab to generate VDBE code to perform foreign key constraint 
74416 ** processing for the operation.
74417 **
74418 ** For a DELETE operation, parameter regOld is passed the index of the
74419 ** first register in an array of (pTab->nCol+1) registers containing the
74420 ** rowid of the row being deleted, followed by each of the column values
74421 ** of the row being deleted, from left to right. Parameter regNew is passed
74422 ** zero in this case.
74423 **
74424 ** For an INSERT operation, regOld is passed zero and regNew is passed the
74425 ** first register of an array of (pTab->nCol+1) registers containing the new
74426 ** row data.
74427 **
74428 ** For an UPDATE operation, this function is called twice. Once before
74429 ** the original record is deleted from the table using the calling convention
74430 ** described for DELETE. Then again after the original record is deleted
74431 ** but before the new record is inserted using the INSERT convention. 
74432 */
74433 SQLITE_PRIVATE void sqlite3FkCheck(
74434   Parse *pParse,                  /* Parse context */
74435   Table *pTab,                    /* Row is being deleted from this table */ 
74436   int regOld,                     /* Previous row data is stored here */
74437   int regNew                      /* New row data is stored here */
74438 ){
74439   sqlite3 *db = pParse->db;       /* Database handle */
74440   Vdbe *v;                        /* VM to write code to */
74441   FKey *pFKey;                    /* Used to iterate through FKs */
74442   int iDb;                        /* Index of database containing pTab */
74443   const char *zDb;                /* Name of database containing pTab */
74444   int isIgnoreErrors = pParse->disableTriggers;
74445
74446   /* Exactly one of regOld and regNew should be non-zero. */
74447   assert( (regOld==0)!=(regNew==0) );
74448
74449   /* If foreign-keys are disabled, this function is a no-op. */
74450   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
74451
74452   v = sqlite3GetVdbe(pParse);
74453   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
74454   zDb = db->aDb[iDb].zName;
74455
74456   /* Loop through all the foreign key constraints for which pTab is the
74457   ** child table (the table that the foreign key definition is part of).  */
74458   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
74459     Table *pTo;                   /* Parent table of foreign key pFKey */
74460     Index *pIdx = 0;              /* Index on key columns in pTo */
74461     int *aiFree = 0;
74462     int *aiCol;
74463     int iCol;
74464     int i;
74465     int isIgnore = 0;
74466
74467     /* Find the parent table of this foreign key. Also find a unique index 
74468     ** on the parent key columns in the parent table. If either of these 
74469     ** schema items cannot be located, set an error in pParse and return 
74470     ** early.  */
74471     if( pParse->disableTriggers ){
74472       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
74473     }else{
74474       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
74475     }
74476     if( !pTo || locateFkeyIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
74477       if( !isIgnoreErrors || db->mallocFailed ) return;
74478       continue;
74479     }
74480     assert( pFKey->nCol==1 || (aiFree && pIdx) );
74481
74482     if( aiFree ){
74483       aiCol = aiFree;
74484     }else{
74485       iCol = pFKey->aCol[0].iFrom;
74486       aiCol = &iCol;
74487     }
74488     for(i=0; i<pFKey->nCol; i++){
74489       if( aiCol[i]==pTab->iPKey ){
74490         aiCol[i] = -1;
74491       }
74492 #ifndef SQLITE_OMIT_AUTHORIZATION
74493       /* Request permission to read the parent key columns. If the 
74494       ** authorization callback returns SQLITE_IGNORE, behave as if any
74495       ** values read from the parent table are NULL. */
74496       if( db->xAuth ){
74497         int rcauth;
74498         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
74499         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
74500         isIgnore = (rcauth==SQLITE_IGNORE);
74501       }
74502 #endif
74503     }
74504
74505     /* Take a shared-cache advisory read-lock on the parent table. Allocate 
74506     ** a cursor to use to search the unique index on the parent key columns 
74507     ** in the parent table.  */
74508     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
74509     pParse->nTab++;
74510
74511     if( regOld!=0 ){
74512       /* A row is being removed from the child table. Search for the parent.
74513       ** If the parent does not exist, removing the child row resolves an 
74514       ** outstanding foreign key constraint violation. */
74515       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
74516     }
74517     if( regNew!=0 ){
74518       /* A row is being added to the child table. If a parent row cannot
74519       ** be found, adding the child row has violated the FK constraint. */ 
74520       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
74521     }
74522
74523     sqlite3DbFree(db, aiFree);
74524   }
74525
74526   /* Loop through all the foreign key constraints that refer to this table */
74527   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
74528     Index *pIdx = 0;              /* Foreign key index for pFKey */
74529     SrcList *pSrc;
74530     int *aiCol = 0;
74531
74532     if( !pFKey->isDeferred && !pParse->pToplevel && !pParse->isMultiWrite ){
74533       assert( regOld==0 && regNew!=0 );
74534       /* Inserting a single row into a parent table cannot cause an immediate
74535       ** foreign key violation. So do nothing in this case.  */
74536       continue;
74537     }
74538
74539     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
74540       if( !isIgnoreErrors || db->mallocFailed ) return;
74541       continue;
74542     }
74543     assert( aiCol || pFKey->nCol==1 );
74544
74545     /* Create a SrcList structure containing a single table (the table 
74546     ** the foreign key that refers to this table is attached to). This
74547     ** is required for the sqlite3WhereXXX() interface.  */
74548     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
74549     if( pSrc ){
74550       struct SrcList_item *pItem = pSrc->a;
74551       pItem->pTab = pFKey->pFrom;
74552       pItem->zName = pFKey->pFrom->zName;
74553       pItem->pTab->nRef++;
74554       pItem->iCursor = pParse->nTab++;
74555   
74556       if( regNew!=0 ){
74557         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
74558       }
74559       if( regOld!=0 ){
74560         /* If there is a RESTRICT action configured for the current operation
74561         ** on the parent table of this FK, then throw an exception 
74562         ** immediately if the FK constraint is violated, even if this is a
74563         ** deferred trigger. That's what RESTRICT means. To defer checking
74564         ** the constraint, the FK should specify NO ACTION (represented
74565         ** using OE_None). NO ACTION is the default.  */
74566         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
74567       }
74568       pItem->zName = 0;
74569       sqlite3SrcListDelete(db, pSrc);
74570     }
74571     sqlite3DbFree(db, aiCol);
74572   }
74573 }
74574
74575 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
74576
74577 /*
74578 ** This function is called before generating code to update or delete a 
74579 ** row contained in table pTab.
74580 */
74581 SQLITE_PRIVATE u32 sqlite3FkOldmask(
74582   Parse *pParse,                  /* Parse context */
74583   Table *pTab                     /* Table being modified */
74584 ){
74585   u32 mask = 0;
74586   if( pParse->db->flags&SQLITE_ForeignKeys ){
74587     FKey *p;
74588     int i;
74589     for(p=pTab->pFKey; p; p=p->pNextFrom){
74590       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
74591     }
74592     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
74593       Index *pIdx = 0;
74594       locateFkeyIndex(pParse, pTab, p, &pIdx, 0);
74595       if( pIdx ){
74596         for(i=0; i<pIdx->nColumn; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
74597       }
74598     }
74599   }
74600   return mask;
74601 }
74602
74603 /*
74604 ** This function is called before generating code to update or delete a 
74605 ** row contained in table pTab. If the operation is a DELETE, then
74606 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
74607 ** to an array of size N, where N is the number of columns in table pTab.
74608 ** If the i'th column is not modified by the UPDATE, then the corresponding 
74609 ** entry in the aChange[] array is set to -1. If the column is modified,
74610 ** the value is 0 or greater. Parameter chngRowid is set to true if the
74611 ** UPDATE statement modifies the rowid fields of the table.
74612 **
74613 ** If any foreign key processing will be required, this function returns
74614 ** true. If there is no foreign key related processing, this function 
74615 ** returns false.
74616 */
74617 SQLITE_PRIVATE int sqlite3FkRequired(
74618   Parse *pParse,                  /* Parse context */
74619   Table *pTab,                    /* Table being modified */
74620   int *aChange,                   /* Non-NULL for UPDATE operations */
74621   int chngRowid                   /* True for UPDATE that affects rowid */
74622 ){
74623   if( pParse->db->flags&SQLITE_ForeignKeys ){
74624     if( !aChange ){
74625       /* A DELETE operation. Foreign key processing is required if the 
74626       ** table in question is either the child or parent table for any 
74627       ** foreign key constraint.  */
74628       return (sqlite3FkReferences(pTab) || pTab->pFKey);
74629     }else{
74630       /* This is an UPDATE. Foreign key processing is only required if the
74631       ** operation modifies one or more child or parent key columns. */
74632       int i;
74633       FKey *p;
74634
74635       /* Check if any child key columns are being modified. */
74636       for(p=pTab->pFKey; p; p=p->pNextFrom){
74637         for(i=0; i<p->nCol; i++){
74638           int iChildKey = p->aCol[i].iFrom;
74639           if( aChange[iChildKey]>=0 ) return 1;
74640           if( iChildKey==pTab->iPKey && chngRowid ) return 1;
74641         }
74642       }
74643
74644       /* Check if any parent key columns are being modified. */
74645       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
74646         for(i=0; i<p->nCol; i++){
74647           char *zKey = p->aCol[i].zCol;
74648           int iKey;
74649           for(iKey=0; iKey<pTab->nCol; iKey++){
74650             Column *pCol = &pTab->aCol[iKey];
74651             if( (zKey ? !sqlite3StrICmp(pCol->zName, zKey) : pCol->isPrimKey) ){
74652               if( aChange[iKey]>=0 ) return 1;
74653               if( iKey==pTab->iPKey && chngRowid ) return 1;
74654             }
74655           }
74656         }
74657       }
74658     }
74659   }
74660   return 0;
74661 }
74662
74663 /*
74664 ** This function is called when an UPDATE or DELETE operation is being 
74665 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
74666 ** If the current operation is an UPDATE, then the pChanges parameter is
74667 ** passed a pointer to the list of columns being modified. If it is a
74668 ** DELETE, pChanges is passed a NULL pointer.
74669 **
74670 ** It returns a pointer to a Trigger structure containing a trigger
74671 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
74672 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
74673 ** returned (these actions require no special handling by the triggers
74674 ** sub-system, code for them is created by fkScanChildren()).
74675 **
74676 ** For example, if pFKey is the foreign key and pTab is table "p" in 
74677 ** the following schema:
74678 **
74679 **   CREATE TABLE p(pk PRIMARY KEY);
74680 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
74681 **
74682 ** then the returned trigger structure is equivalent to:
74683 **
74684 **   CREATE TRIGGER ... DELETE ON p BEGIN
74685 **     DELETE FROM c WHERE ck = old.pk;
74686 **   END;
74687 **
74688 ** The returned pointer is cached as part of the foreign key object. It
74689 ** is eventually freed along with the rest of the foreign key object by 
74690 ** sqlite3FkDelete().
74691 */
74692 static Trigger *fkActionTrigger(
74693   Parse *pParse,                  /* Parse context */
74694   Table *pTab,                    /* Table being updated or deleted from */
74695   FKey *pFKey,                    /* Foreign key to get action for */
74696   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
74697 ){
74698   sqlite3 *db = pParse->db;       /* Database handle */
74699   int action;                     /* One of OE_None, OE_Cascade etc. */
74700   Trigger *pTrigger;              /* Trigger definition to return */
74701   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
74702
74703   action = pFKey->aAction[iAction];
74704   pTrigger = pFKey->apTrigger[iAction];
74705
74706   if( action!=OE_None && !pTrigger ){
74707     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
74708     char const *zFrom;            /* Name of child table */
74709     int nFrom;                    /* Length in bytes of zFrom */
74710     Index *pIdx = 0;              /* Parent key index for this FK */
74711     int *aiCol = 0;               /* child table cols -> parent key cols */
74712     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
74713     Expr *pWhere = 0;             /* WHERE clause of trigger step */
74714     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
74715     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
74716     int i;                        /* Iterator variable */
74717     Expr *pWhen = 0;              /* WHEN clause for the trigger */
74718
74719     if( locateFkeyIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
74720     assert( aiCol || pFKey->nCol==1 );
74721
74722     for(i=0; i<pFKey->nCol; i++){
74723       Token tOld = { "old", 3 };  /* Literal "old" token */
74724       Token tNew = { "new", 3 };  /* Literal "new" token */
74725       Token tFromCol;             /* Name of column in child table */
74726       Token tToCol;               /* Name of column in parent table */
74727       int iFromCol;               /* Idx of column in child table */
74728       Expr *pEq;                  /* tFromCol = OLD.tToCol */
74729
74730       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
74731       assert( iFromCol>=0 );
74732       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
74733       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
74734
74735       tToCol.n = sqlite3Strlen30(tToCol.z);
74736       tFromCol.n = sqlite3Strlen30(tFromCol.z);
74737
74738       /* Create the expression "OLD.zToCol = zFromCol". It is important
74739       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
74740       ** that the affinity and collation sequence associated with the
74741       ** parent table are used for the comparison. */
74742       pEq = sqlite3PExpr(pParse, TK_EQ,
74743           sqlite3PExpr(pParse, TK_DOT, 
74744             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
74745             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
74746           , 0),
74747           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
74748       , 0);
74749       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
74750
74751       /* For ON UPDATE, construct the next term of the WHEN clause.
74752       ** The final WHEN clause will be like this:
74753       **
74754       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
74755       */
74756       if( pChanges ){
74757         pEq = sqlite3PExpr(pParse, TK_IS,
74758             sqlite3PExpr(pParse, TK_DOT, 
74759               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
74760               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
74761               0),
74762             sqlite3PExpr(pParse, TK_DOT, 
74763               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
74764               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
74765               0),
74766             0);
74767         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
74768       }
74769   
74770       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
74771         Expr *pNew;
74772         if( action==OE_Cascade ){
74773           pNew = sqlite3PExpr(pParse, TK_DOT, 
74774             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
74775             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
74776           , 0);
74777         }else if( action==OE_SetDflt ){
74778           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
74779           if( pDflt ){
74780             pNew = sqlite3ExprDup(db, pDflt, 0);
74781           }else{
74782             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
74783           }
74784         }else{
74785           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
74786         }
74787         pList = sqlite3ExprListAppend(pParse, pList, pNew);
74788         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
74789       }
74790     }
74791     sqlite3DbFree(db, aiCol);
74792
74793     zFrom = pFKey->pFrom->zName;
74794     nFrom = sqlite3Strlen30(zFrom);
74795
74796     if( action==OE_Restrict ){
74797       Token tFrom;
74798       Expr *pRaise; 
74799
74800       tFrom.z = zFrom;
74801       tFrom.n = nFrom;
74802       pRaise = sqlite3Expr(db, TK_RAISE, "foreign key constraint failed");
74803       if( pRaise ){
74804         pRaise->affinity = OE_Abort;
74805       }
74806       pSelect = sqlite3SelectNew(pParse, 
74807           sqlite3ExprListAppend(pParse, 0, pRaise),
74808           sqlite3SrcListAppend(db, 0, &tFrom, 0),
74809           pWhere,
74810           0, 0, 0, 0, 0, 0
74811       );
74812       pWhere = 0;
74813     }
74814
74815     /* In the current implementation, pTab->dbMem==0 for all tables except
74816     ** for temporary tables used to describe subqueries.  And temporary
74817     ** tables do not have foreign key constraints.  Hence, pTab->dbMem
74818     ** should always be 0 there.
74819     */
74820     enableLookaside = db->lookaside.bEnabled;
74821     db->lookaside.bEnabled = 0;
74822
74823     pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
74824         sizeof(Trigger) +         /* struct Trigger */
74825         sizeof(TriggerStep) +     /* Single step in trigger program */
74826         nFrom + 1                 /* Space for pStep->target.z */
74827     );
74828     if( pTrigger ){
74829       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
74830       pStep->target.z = (char *)&pStep[1];
74831       pStep->target.n = nFrom;
74832       memcpy((char *)pStep->target.z, zFrom, nFrom);
74833   
74834       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
74835       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
74836       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
74837       if( pWhen ){
74838         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
74839         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
74840       }
74841     }
74842
74843     /* Re-enable the lookaside buffer, if it was disabled earlier. */
74844     db->lookaside.bEnabled = enableLookaside;
74845
74846     sqlite3ExprDelete(db, pWhere);
74847     sqlite3ExprDelete(db, pWhen);
74848     sqlite3ExprListDelete(db, pList);
74849     sqlite3SelectDelete(db, pSelect);
74850     if( db->mallocFailed==1 ){
74851       fkTriggerDelete(db, pTrigger);
74852       return 0;
74853     }
74854
74855     switch( action ){
74856       case OE_Restrict:
74857         pStep->op = TK_SELECT; 
74858         break;
74859       case OE_Cascade: 
74860         if( !pChanges ){ 
74861           pStep->op = TK_DELETE; 
74862           break; 
74863         }
74864       default:
74865         pStep->op = TK_UPDATE;
74866     }
74867     pStep->pTrig = pTrigger;
74868     pTrigger->pSchema = pTab->pSchema;
74869     pTrigger->pTabSchema = pTab->pSchema;
74870     pFKey->apTrigger[iAction] = pTrigger;
74871     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
74872   }
74873
74874   return pTrigger;
74875 }
74876
74877 /*
74878 ** This function is called when deleting or updating a row to implement
74879 ** any required CASCADE, SET NULL or SET DEFAULT actions.
74880 */
74881 SQLITE_PRIVATE void sqlite3FkActions(
74882   Parse *pParse,                  /* Parse context */
74883   Table *pTab,                    /* Table being updated or deleted from */
74884   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
74885   int regOld                      /* Address of array containing old row */
74886 ){
74887   /* If foreign-key support is enabled, iterate through all FKs that 
74888   ** refer to table pTab. If there is an action associated with the FK 
74889   ** for this operation (either update or delete), invoke the associated 
74890   ** trigger sub-program.  */
74891   if( pParse->db->flags&SQLITE_ForeignKeys ){
74892     FKey *pFKey;                  /* Iterator variable */
74893     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
74894       Trigger *pAction = fkActionTrigger(pParse, pTab, pFKey, pChanges);
74895       if( pAction ){
74896         sqlite3CodeRowTriggerDirect(pParse, pAction, pTab, regOld, OE_Abort, 0);
74897       }
74898     }
74899   }
74900 }
74901
74902 #endif /* ifndef SQLITE_OMIT_TRIGGER */
74903
74904 /*
74905 ** Free all memory associated with foreign key definitions attached to
74906 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
74907 ** hash table.
74908 */
74909 SQLITE_PRIVATE void sqlite3FkDelete(Table *pTab){
74910   FKey *pFKey;                    /* Iterator variable */
74911   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
74912
74913   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
74914
74915     /* Remove the FK from the fkeyHash hash table. */
74916     if( pFKey->pPrevTo ){
74917       pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
74918     }else{
74919       void *data = (void *)pFKey->pNextTo;
74920       const char *z = (data ? pFKey->pNextTo->zTo : pFKey->zTo);
74921       sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, sqlite3Strlen30(z), data);
74922     }
74923     if( pFKey->pNextTo ){
74924       pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
74925     }
74926
74927     /* Delete any triggers created to implement actions for this FK. */
74928 #ifndef SQLITE_OMIT_TRIGGER
74929     fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[0]);
74930     fkTriggerDelete(pTab->dbMem, pFKey->apTrigger[1]);
74931 #endif
74932
74933     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
74934     ** classified as either immediate or deferred.
74935     */
74936     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
74937
74938     pNext = pFKey->pNextFrom;
74939     sqlite3DbFree(pTab->dbMem, pFKey);
74940   }
74941 }
74942 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
74943
74944 /************** End of fkey.c ************************************************/
74945 /************** Begin file insert.c ******************************************/
74946 /*
74947 ** 2001 September 15
74948 **
74949 ** The author disclaims copyright to this source code.  In place of
74950 ** a legal notice, here is a blessing:
74951 **
74952 **    May you do good and not evil.
74953 **    May you find forgiveness for yourself and forgive others.
74954 **    May you share freely, never taking more than you give.
74955 **
74956 *************************************************************************
74957 ** This file contains C code routines that are called by the parser
74958 ** to handle INSERT statements in SQLite.
74959 */
74960
74961 /*
74962 ** Generate code that will open a table for reading.
74963 */
74964 SQLITE_PRIVATE void sqlite3OpenTable(
74965   Parse *p,       /* Generate code into this VDBE */
74966   int iCur,       /* The cursor number of the table */
74967   int iDb,        /* The database index in sqlite3.aDb[] */
74968   Table *pTab,    /* The table to be opened */
74969   int opcode      /* OP_OpenRead or OP_OpenWrite */
74970 ){
74971   Vdbe *v;
74972   if( IsVirtual(pTab) ) return;
74973   v = sqlite3GetVdbe(p);
74974   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
74975   sqlite3TableLock(p, iDb, pTab->tnum, (opcode==OP_OpenWrite)?1:0, pTab->zName);
74976   sqlite3VdbeAddOp3(v, opcode, iCur, pTab->tnum, iDb);
74977   sqlite3VdbeChangeP4(v, -1, SQLITE_INT_TO_PTR(pTab->nCol), P4_INT32);
74978   VdbeComment((v, "%s", pTab->zName));
74979 }
74980
74981 /*
74982 ** Return a pointer to the column affinity string associated with index
74983 ** pIdx. A column affinity string has one character for each column in 
74984 ** the table, according to the affinity of the column:
74985 **
74986 **  Character      Column affinity
74987 **  ------------------------------
74988 **  'a'            TEXT
74989 **  'b'            NONE
74990 **  'c'            NUMERIC
74991 **  'd'            INTEGER
74992 **  'e'            REAL
74993 **
74994 ** An extra 'b' is appended to the end of the string to cover the
74995 ** rowid that appears as the last column in every index.
74996 **
74997 ** Memory for the buffer containing the column index affinity string
74998 ** is managed along with the rest of the Index structure. It will be
74999 ** released when sqlite3DeleteIndex() is called.
75000 */
75001 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
75002   if( !pIdx->zColAff ){
75003     /* The first time a column affinity string for a particular index is
75004     ** required, it is allocated and populated here. It is then stored as
75005     ** a member of the Index structure for subsequent use.
75006     **
75007     ** The column affinity string will eventually be deleted by
75008     ** sqliteDeleteIndex() when the Index structure itself is cleaned
75009     ** up.
75010     */
75011     int n;
75012     Table *pTab = pIdx->pTable;
75013     sqlite3 *db = sqlite3VdbeDb(v);
75014     pIdx->zColAff = (char *)sqlite3Malloc(pIdx->nColumn+2);
75015     if( !pIdx->zColAff ){
75016       db->mallocFailed = 1;
75017       return 0;
75018     }
75019     for(n=0; n<pIdx->nColumn; n++){
75020       pIdx->zColAff[n] = pTab->aCol[pIdx->aiColumn[n]].affinity;
75021     }
75022     pIdx->zColAff[n++] = SQLITE_AFF_NONE;
75023     pIdx->zColAff[n] = 0;
75024   }
75025  
75026   return pIdx->zColAff;
75027 }
75028
75029 /*
75030 ** Set P4 of the most recently inserted opcode to a column affinity
75031 ** string for table pTab. A column affinity string has one character
75032 ** for each column indexed by the index, according to the affinity of the
75033 ** column:
75034 **
75035 **  Character      Column affinity
75036 **  ------------------------------
75037 **  'a'            TEXT
75038 **  'b'            NONE
75039 **  'c'            NUMERIC
75040 **  'd'            INTEGER
75041 **  'e'            REAL
75042 */
75043 SQLITE_PRIVATE void sqlite3TableAffinityStr(Vdbe *v, Table *pTab){
75044   /* The first time a column affinity string for a particular table
75045   ** is required, it is allocated and populated here. It is then 
75046   ** stored as a member of the Table structure for subsequent use.
75047   **
75048   ** The column affinity string will eventually be deleted by
75049   ** sqlite3DeleteTable() when the Table structure itself is cleaned up.
75050   */
75051   if( !pTab->zColAff ){
75052     char *zColAff;
75053     int i;
75054     sqlite3 *db = sqlite3VdbeDb(v);
75055
75056     zColAff = (char *)sqlite3Malloc(pTab->nCol+1);
75057     if( !zColAff ){
75058       db->mallocFailed = 1;
75059       return;
75060     }
75061
75062     for(i=0; i<pTab->nCol; i++){
75063       zColAff[i] = pTab->aCol[i].affinity;
75064     }
75065     zColAff[pTab->nCol] = '\0';
75066
75067     pTab->zColAff = zColAff;
75068   }
75069
75070   sqlite3VdbeChangeP4(v, -1, pTab->zColAff, 0);
75071 }
75072
75073 /*
75074 ** Return non-zero if the table pTab in database iDb or any of its indices
75075 ** have been opened at any point in the VDBE program beginning at location
75076 ** iStartAddr throught the end of the program.  This is used to see if 
75077 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
75078 ** run without using temporary table for the results of the SELECT. 
75079 */
75080 static int readsTable(Parse *p, int iStartAddr, int iDb, Table *pTab){
75081   Vdbe *v = sqlite3GetVdbe(p);
75082   int i;
75083   int iEnd = sqlite3VdbeCurrentAddr(v);
75084 #ifndef SQLITE_OMIT_VIRTUALTABLE
75085   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
75086 #endif
75087
75088   for(i=iStartAddr; i<iEnd; i++){
75089     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
75090     assert( pOp!=0 );
75091     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
75092       Index *pIndex;
75093       int tnum = pOp->p2;
75094       if( tnum==pTab->tnum ){
75095         return 1;
75096       }
75097       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
75098         if( tnum==pIndex->tnum ){
75099           return 1;
75100         }
75101       }
75102     }
75103 #ifndef SQLITE_OMIT_VIRTUALTABLE
75104     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
75105       assert( pOp->p4.pVtab!=0 );
75106       assert( pOp->p4type==P4_VTAB );
75107       return 1;
75108     }
75109 #endif
75110   }
75111   return 0;
75112 }
75113
75114 #ifndef SQLITE_OMIT_AUTOINCREMENT
75115 /*
75116 ** Locate or create an AutoincInfo structure associated with table pTab
75117 ** which is in database iDb.  Return the register number for the register
75118 ** that holds the maximum rowid.
75119 **
75120 ** There is at most one AutoincInfo structure per table even if the
75121 ** same table is autoincremented multiple times due to inserts within
75122 ** triggers.  A new AutoincInfo structure is created if this is the
75123 ** first use of table pTab.  On 2nd and subsequent uses, the original
75124 ** AutoincInfo structure is used.
75125 **
75126 ** Three memory locations are allocated:
75127 **
75128 **   (1)  Register to hold the name of the pTab table.
75129 **   (2)  Register to hold the maximum ROWID of pTab.
75130 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
75131 **
75132 ** The 2nd register is the one that is returned.  That is all the
75133 ** insert routine needs to know about.
75134 */
75135 static int autoIncBegin(
75136   Parse *pParse,      /* Parsing context */
75137   int iDb,            /* Index of the database holding pTab */
75138   Table *pTab         /* The table we are writing to */
75139 ){
75140   int memId = 0;      /* Register holding maximum rowid */
75141   if( pTab->tabFlags & TF_Autoincrement ){
75142     Parse *pToplevel = sqlite3ParseToplevel(pParse);
75143     AutoincInfo *pInfo;
75144
75145     pInfo = pToplevel->pAinc;
75146     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
75147     if( pInfo==0 ){
75148       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
75149       if( pInfo==0 ) return 0;
75150       pInfo->pNext = pToplevel->pAinc;
75151       pToplevel->pAinc = pInfo;
75152       pInfo->pTab = pTab;
75153       pInfo->iDb = iDb;
75154       pToplevel->nMem++;                  /* Register to hold name of table */
75155       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
75156       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
75157     }
75158     memId = pInfo->regCtr;
75159   }
75160   return memId;
75161 }
75162
75163 /*
75164 ** This routine generates code that will initialize all of the
75165 ** register used by the autoincrement tracker.  
75166 */
75167 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
75168   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
75169   sqlite3 *db = pParse->db;  /* The database connection */
75170   Db *pDb;                   /* Database only autoinc table */
75171   int memId;                 /* Register holding max rowid */
75172   int addr;                  /* A VDBE address */
75173   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
75174
75175   /* This routine is never called during trigger-generation.  It is
75176   ** only called from the top-level */
75177   assert( pParse->pTriggerTab==0 );
75178   assert( pParse==sqlite3ParseToplevel(pParse) );
75179
75180   assert( v );   /* We failed long ago if this is not so */
75181   for(p = pParse->pAinc; p; p = p->pNext){
75182     pDb = &db->aDb[p->iDb];
75183     memId = p->regCtr;
75184     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
75185     addr = sqlite3VdbeCurrentAddr(v);
75186     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
75187     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9);
75188     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
75189     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId);
75190     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
75191     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
75192     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
75193     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
75194     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2);
75195     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
75196     sqlite3VdbeAddOp0(v, OP_Close);
75197   }
75198 }
75199
75200 /*
75201 ** Update the maximum rowid for an autoincrement calculation.
75202 **
75203 ** This routine should be called when the top of the stack holds a
75204 ** new rowid that is about to be inserted.  If that new rowid is
75205 ** larger than the maximum rowid in the memId memory cell, then the
75206 ** memory cell is updated.  The stack is unchanged.
75207 */
75208 static void autoIncStep(Parse *pParse, int memId, int regRowid){
75209   if( memId>0 ){
75210     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
75211   }
75212 }
75213
75214 /*
75215 ** This routine generates the code needed to write autoincrement
75216 ** maximum rowid values back into the sqlite_sequence register.
75217 ** Every statement that might do an INSERT into an autoincrement
75218 ** table (either directly or through triggers) needs to call this
75219 ** routine just before the "exit" code.
75220 */
75221 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
75222   AutoincInfo *p;
75223   Vdbe *v = pParse->pVdbe;
75224   sqlite3 *db = pParse->db;
75225
75226   assert( v );
75227   for(p = pParse->pAinc; p; p = p->pNext){
75228     Db *pDb = &db->aDb[p->iDb];
75229     int j1, j2, j3, j4, j5;
75230     int iRec;
75231     int memId = p->regCtr;
75232
75233     iRec = sqlite3GetTempReg(pParse);
75234     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
75235     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1);
75236     j2 = sqlite3VdbeAddOp0(v, OP_Rewind);
75237     j3 = sqlite3VdbeAddOp3(v, OP_Column, 0, 0, iRec);
75238     j4 = sqlite3VdbeAddOp3(v, OP_Eq, memId-1, 0, iRec);
75239     sqlite3VdbeAddOp2(v, OP_Next, 0, j3);
75240     sqlite3VdbeJumpHere(v, j2);
75241     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
75242     j5 = sqlite3VdbeAddOp0(v, OP_Goto);
75243     sqlite3VdbeJumpHere(v, j4);
75244     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
75245     sqlite3VdbeJumpHere(v, j1);
75246     sqlite3VdbeJumpHere(v, j5);
75247     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
75248     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
75249     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
75250     sqlite3VdbeAddOp0(v, OP_Close);
75251     sqlite3ReleaseTempReg(pParse, iRec);
75252   }
75253 }
75254 #else
75255 /*
75256 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
75257 ** above are all no-ops
75258 */
75259 # define autoIncBegin(A,B,C) (0)
75260 # define autoIncStep(A,B,C)
75261 #endif /* SQLITE_OMIT_AUTOINCREMENT */
75262
75263
75264 /* Forward declaration */
75265 static int xferOptimization(
75266   Parse *pParse,        /* Parser context */
75267   Table *pDest,         /* The table we are inserting into */
75268   Select *pSelect,      /* A SELECT statement to use as the data source */
75269   int onError,          /* How to handle constraint errors */
75270   int iDbDest           /* The database of pDest */
75271 );
75272
75273 /*
75274 ** This routine is call to handle SQL of the following forms:
75275 **
75276 **    insert into TABLE (IDLIST) values(EXPRLIST)
75277 **    insert into TABLE (IDLIST) select
75278 **
75279 ** The IDLIST following the table name is always optional.  If omitted,
75280 ** then a list of all columns for the table is substituted.  The IDLIST
75281 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
75282 **
75283 ** The pList parameter holds EXPRLIST in the first form of the INSERT
75284 ** statement above, and pSelect is NULL.  For the second form, pList is
75285 ** NULL and pSelect is a pointer to the select statement used to generate
75286 ** data for the insert.
75287 **
75288 ** The code generated follows one of four templates.  For a simple
75289 ** select with data coming from a VALUES clause, the code executes
75290 ** once straight down through.  Pseudo-code follows (we call this
75291 ** the "1st template"):
75292 **
75293 **         open write cursor to <table> and its indices
75294 **         puts VALUES clause expressions onto the stack
75295 **         write the resulting record into <table>
75296 **         cleanup
75297 **
75298 ** The three remaining templates assume the statement is of the form
75299 **
75300 **   INSERT INTO <table> SELECT ...
75301 **
75302 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
75303 ** in other words if the SELECT pulls all columns from a single table
75304 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
75305 ** if <table2> and <table1> are distinct tables but have identical
75306 ** schemas, including all the same indices, then a special optimization
75307 ** is invoked that copies raw records from <table2> over to <table1>.
75308 ** See the xferOptimization() function for the implementation of this
75309 ** template.  This is the 2nd template.
75310 **
75311 **         open a write cursor to <table>
75312 **         open read cursor on <table2>
75313 **         transfer all records in <table2> over to <table>
75314 **         close cursors
75315 **         foreach index on <table>
75316 **           open a write cursor on the <table> index
75317 **           open a read cursor on the corresponding <table2> index
75318 **           transfer all records from the read to the write cursors
75319 **           close cursors
75320 **         end foreach
75321 **
75322 ** The 3rd template is for when the second template does not apply
75323 ** and the SELECT clause does not read from <table> at any time.
75324 ** The generated code follows this template:
75325 **
75326 **         EOF <- 0
75327 **         X <- A
75328 **         goto B
75329 **      A: setup for the SELECT
75330 **         loop over the rows in the SELECT
75331 **           load values into registers R..R+n
75332 **           yield X
75333 **         end loop
75334 **         cleanup after the SELECT
75335 **         EOF <- 1
75336 **         yield X
75337 **         goto A
75338 **      B: open write cursor to <table> and its indices
75339 **      C: yield X
75340 **         if EOF goto D
75341 **         insert the select result into <table> from R..R+n
75342 **         goto C
75343 **      D: cleanup
75344 **
75345 ** The 4th template is used if the insert statement takes its
75346 ** values from a SELECT but the data is being inserted into a table
75347 ** that is also read as part of the SELECT.  In the third form,
75348 ** we have to use a intermediate table to store the results of
75349 ** the select.  The template is like this:
75350 **
75351 **         EOF <- 0
75352 **         X <- A
75353 **         goto B
75354 **      A: setup for the SELECT
75355 **         loop over the tables in the SELECT
75356 **           load value into register R..R+n
75357 **           yield X
75358 **         end loop
75359 **         cleanup after the SELECT
75360 **         EOF <- 1
75361 **         yield X
75362 **         halt-error
75363 **      B: open temp table
75364 **      L: yield X
75365 **         if EOF goto M
75366 **         insert row from R..R+n into temp table
75367 **         goto L
75368 **      M: open write cursor to <table> and its indices
75369 **         rewind temp table
75370 **      C: loop over rows of intermediate table
75371 **           transfer values form intermediate table into <table>
75372 **         end loop
75373 **      D: cleanup
75374 */
75375 SQLITE_PRIVATE void sqlite3Insert(
75376   Parse *pParse,        /* Parser context */
75377   SrcList *pTabList,    /* Name of table into which we are inserting */
75378   ExprList *pList,      /* List of values to be inserted */
75379   Select *pSelect,      /* A SELECT statement to use as the data source */
75380   IdList *pColumn,      /* Column names corresponding to IDLIST. */
75381   int onError           /* How to handle constraint errors */
75382 ){
75383   sqlite3 *db;          /* The main database structure */
75384   Table *pTab;          /* The table to insert into.  aka TABLE */
75385   char *zTab;           /* Name of the table into which we are inserting */
75386   const char *zDb;      /* Name of the database holding this table */
75387   int i, j, idx;        /* Loop counters */
75388   Vdbe *v;              /* Generate code into this virtual machine */
75389   Index *pIdx;          /* For looping over indices of the table */
75390   int nColumn;          /* Number of columns in the data */
75391   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
75392   int baseCur = 0;      /* VDBE Cursor number for pTab */
75393   int keyColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
75394   int endOfLoop;        /* Label for the end of the insertion loop */
75395   int useTempTable = 0; /* Store SELECT results in intermediate table */
75396   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
75397   int addrInsTop = 0;   /* Jump to label "D" */
75398   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
75399   int addrSelect = 0;   /* Address of coroutine that implements the SELECT */
75400   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
75401   int iDb;              /* Index of database holding TABLE */
75402   Db *pDb;              /* The database containing table being inserted into */
75403   int appendFlag = 0;   /* True if the insert is likely to be an append */
75404
75405   /* Register allocations */
75406   int regFromSelect = 0;/* Base register for data coming from SELECT */
75407   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
75408   int regRowCount = 0;  /* Memory cell used for the row counter */
75409   int regIns;           /* Block of regs holding rowid+data being inserted */
75410   int regRowid;         /* registers holding insert rowid */
75411   int regData;          /* register holding first column to insert */
75412   int regRecord;        /* Holds the assemblied row record */
75413   int regEof = 0;       /* Register recording end of SELECT data */
75414   int *aRegIdx = 0;     /* One register allocated to each index */
75415
75416 #ifndef SQLITE_OMIT_TRIGGER
75417   int isView;                 /* True if attempting to insert into a view */
75418   Trigger *pTrigger;          /* List of triggers on pTab, if required */
75419   int tmask;                  /* Mask of trigger times */
75420 #endif
75421
75422   db = pParse->db;
75423   memset(&dest, 0, sizeof(dest));
75424   if( pParse->nErr || db->mallocFailed ){
75425     goto insert_cleanup;
75426   }
75427
75428   /* Locate the table into which we will be inserting new information.
75429   */
75430   assert( pTabList->nSrc==1 );
75431   zTab = pTabList->a[0].zName;
75432   if( NEVER(zTab==0) ) goto insert_cleanup;
75433   pTab = sqlite3SrcListLookup(pParse, pTabList);
75434   if( pTab==0 ){
75435     goto insert_cleanup;
75436   }
75437   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
75438   assert( iDb<db->nDb );
75439   pDb = &db->aDb[iDb];
75440   zDb = pDb->zName;
75441   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
75442     goto insert_cleanup;
75443   }
75444
75445   /* Figure out if we have any triggers and if the table being
75446   ** inserted into is a view
75447   */
75448 #ifndef SQLITE_OMIT_TRIGGER
75449   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
75450   isView = pTab->pSelect!=0;
75451 #else
75452 # define pTrigger 0
75453 # define tmask 0
75454 # define isView 0
75455 #endif
75456 #ifdef SQLITE_OMIT_VIEW
75457 # undef isView
75458 # define isView 0
75459 #endif
75460   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
75461
75462   /* If pTab is really a view, make sure it has been initialized.
75463   ** ViewGetColumnNames() is a no-op if pTab is not a view (or virtual 
75464   ** module table).
75465   */
75466   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
75467     goto insert_cleanup;
75468   }
75469
75470   /* Ensure that:
75471   *  (a) the table is not read-only, 
75472   *  (b) that if it is a view then ON INSERT triggers exist
75473   */
75474   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
75475     goto insert_cleanup;
75476   }
75477
75478   /* Allocate a VDBE
75479   */
75480   v = sqlite3GetVdbe(pParse);
75481   if( v==0 ) goto insert_cleanup;
75482   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
75483   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
75484
75485 #ifndef SQLITE_OMIT_XFER_OPT
75486   /* If the statement is of the form
75487   **
75488   **       INSERT INTO <table1> SELECT * FROM <table2>;
75489   **
75490   ** Then special optimizations can be applied that make the transfer
75491   ** very fast and which reduce fragmentation of indices.
75492   **
75493   ** This is the 2nd template.
75494   */
75495   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
75496     assert( !pTrigger );
75497     assert( pList==0 );
75498     goto insert_end;
75499   }
75500 #endif /* SQLITE_OMIT_XFER_OPT */
75501
75502   /* If this is an AUTOINCREMENT table, look up the sequence number in the
75503   ** sqlite_sequence table and store it in memory cell regAutoinc.
75504   */
75505   regAutoinc = autoIncBegin(pParse, iDb, pTab);
75506
75507   /* Figure out how many columns of data are supplied.  If the data
75508   ** is coming from a SELECT statement, then generate a co-routine that
75509   ** produces a single row of the SELECT on each invocation.  The
75510   ** co-routine is the common header to the 3rd and 4th templates.
75511   */
75512   if( pSelect ){
75513     /* Data is coming from a SELECT.  Generate code to implement that SELECT
75514     ** as a co-routine.  The code is common to both the 3rd and 4th
75515     ** templates:
75516     **
75517     **         EOF <- 0
75518     **         X <- A
75519     **         goto B
75520     **      A: setup for the SELECT
75521     **         loop over the tables in the SELECT
75522     **           load value into register R..R+n
75523     **           yield X
75524     **         end loop
75525     **         cleanup after the SELECT
75526     **         EOF <- 1
75527     **         yield X
75528     **         halt-error
75529     **
75530     ** On each invocation of the co-routine, it puts a single row of the
75531     ** SELECT result into registers dest.iMem...dest.iMem+dest.nMem-1.
75532     ** (These output registers are allocated by sqlite3Select().)  When
75533     ** the SELECT completes, it sets the EOF flag stored in regEof.
75534     */
75535     int rc, j1;
75536
75537     regEof = ++pParse->nMem;
75538     sqlite3VdbeAddOp2(v, OP_Integer, 0, regEof);      /* EOF <- 0 */
75539     VdbeComment((v, "SELECT eof flag"));
75540     sqlite3SelectDestInit(&dest, SRT_Coroutine, ++pParse->nMem);
75541     addrSelect = sqlite3VdbeCurrentAddr(v)+2;
75542     sqlite3VdbeAddOp2(v, OP_Integer, addrSelect-1, dest.iParm);
75543     j1 = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
75544     VdbeComment((v, "Jump over SELECT coroutine"));
75545
75546     /* Resolve the expressions in the SELECT statement and execute it. */
75547     rc = sqlite3Select(pParse, pSelect, &dest);
75548     assert( pParse->nErr==0 || rc );
75549     if( rc || NEVER(pParse->nErr) || db->mallocFailed ){
75550       goto insert_cleanup;
75551     }
75552     sqlite3VdbeAddOp2(v, OP_Integer, 1, regEof);         /* EOF <- 1 */
75553     sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);   /* yield X */
75554     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_INTERNAL, OE_Abort);
75555     VdbeComment((v, "End of SELECT coroutine"));
75556     sqlite3VdbeJumpHere(v, j1);                          /* label B: */
75557
75558     regFromSelect = dest.iMem;
75559     assert( pSelect->pEList );
75560     nColumn = pSelect->pEList->nExpr;
75561     assert( dest.nMem==nColumn );
75562
75563     /* Set useTempTable to TRUE if the result of the SELECT statement
75564     ** should be written into a temporary table (template 4).  Set to
75565     ** FALSE if each* row of the SELECT can be written directly into
75566     ** the destination table (template 3).
75567     **
75568     ** A temp table must be used if the table being updated is also one
75569     ** of the tables being read by the SELECT statement.  Also use a 
75570     ** temp table in the case of row triggers.
75571     */
75572     if( pTrigger || readsTable(pParse, addrSelect, iDb, pTab) ){
75573       useTempTable = 1;
75574     }
75575
75576     if( useTempTable ){
75577       /* Invoke the coroutine to extract information from the SELECT
75578       ** and add it to a transient table srcTab.  The code generated
75579       ** here is from the 4th template:
75580       **
75581       **      B: open temp table
75582       **      L: yield X
75583       **         if EOF goto M
75584       **         insert row from R..R+n into temp table
75585       **         goto L
75586       **      M: ...
75587       */
75588       int regRec;          /* Register to hold packed record */
75589       int regTempRowid;    /* Register to hold temp table ROWID */
75590       int addrTop;         /* Label "L" */
75591       int addrIf;          /* Address of jump to M */
75592
75593       srcTab = pParse->nTab++;
75594       regRec = sqlite3GetTempReg(pParse);
75595       regTempRowid = sqlite3GetTempReg(pParse);
75596       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
75597       addrTop = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
75598       addrIf = sqlite3VdbeAddOp1(v, OP_If, regEof);
75599       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
75600       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
75601       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
75602       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
75603       sqlite3VdbeJumpHere(v, addrIf);
75604       sqlite3ReleaseTempReg(pParse, regRec);
75605       sqlite3ReleaseTempReg(pParse, regTempRowid);
75606     }
75607   }else{
75608     /* This is the case if the data for the INSERT is coming from a VALUES
75609     ** clause
75610     */
75611     NameContext sNC;
75612     memset(&sNC, 0, sizeof(sNC));
75613     sNC.pParse = pParse;
75614     srcTab = -1;
75615     assert( useTempTable==0 );
75616     nColumn = pList ? pList->nExpr : 0;
75617     for(i=0; i<nColumn; i++){
75618       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
75619         goto insert_cleanup;
75620       }
75621     }
75622   }
75623
75624   /* Make sure the number of columns in the source data matches the number
75625   ** of columns to be inserted into the table.
75626   */
75627   if( IsVirtual(pTab) ){
75628     for(i=0; i<pTab->nCol; i++){
75629       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
75630     }
75631   }
75632   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
75633     sqlite3ErrorMsg(pParse, 
75634        "table %S has %d columns but %d values were supplied",
75635        pTabList, 0, pTab->nCol-nHidden, nColumn);
75636     goto insert_cleanup;
75637   }
75638   if( pColumn!=0 && nColumn!=pColumn->nId ){
75639     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
75640     goto insert_cleanup;
75641   }
75642
75643   /* If the INSERT statement included an IDLIST term, then make sure
75644   ** all elements of the IDLIST really are columns of the table and 
75645   ** remember the column indices.
75646   **
75647   ** If the table has an INTEGER PRIMARY KEY column and that column
75648   ** is named in the IDLIST, then record in the keyColumn variable
75649   ** the index into IDLIST of the primary key column.  keyColumn is
75650   ** the index of the primary key as it appears in IDLIST, not as
75651   ** is appears in the original table.  (The index of the primary
75652   ** key in the original table is pTab->iPKey.)
75653   */
75654   if( pColumn ){
75655     for(i=0; i<pColumn->nId; i++){
75656       pColumn->a[i].idx = -1;
75657     }
75658     for(i=0; i<pColumn->nId; i++){
75659       for(j=0; j<pTab->nCol; j++){
75660         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
75661           pColumn->a[i].idx = j;
75662           if( j==pTab->iPKey ){
75663             keyColumn = i;
75664           }
75665           break;
75666         }
75667       }
75668       if( j>=pTab->nCol ){
75669         if( sqlite3IsRowid(pColumn->a[i].zName) ){
75670           keyColumn = i;
75671         }else{
75672           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
75673               pTabList, 0, pColumn->a[i].zName);
75674           pParse->nErr++;
75675           goto insert_cleanup;
75676         }
75677       }
75678     }
75679   }
75680
75681   /* If there is no IDLIST term but the table has an integer primary
75682   ** key, the set the keyColumn variable to the primary key column index
75683   ** in the original table definition.
75684   */
75685   if( pColumn==0 && nColumn>0 ){
75686     keyColumn = pTab->iPKey;
75687   }
75688     
75689   /* Initialize the count of rows to be inserted
75690   */
75691   if( db->flags & SQLITE_CountRows ){
75692     regRowCount = ++pParse->nMem;
75693     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
75694   }
75695
75696   /* If this is not a view, open the table and and all indices */
75697   if( !isView ){
75698     int nIdx;
75699
75700     baseCur = pParse->nTab;
75701     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, baseCur, OP_OpenWrite);
75702     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
75703     if( aRegIdx==0 ){
75704       goto insert_cleanup;
75705     }
75706     for(i=0; i<nIdx; i++){
75707       aRegIdx[i] = ++pParse->nMem;
75708     }
75709   }
75710
75711   /* This is the top of the main insertion loop */
75712   if( useTempTable ){
75713     /* This block codes the top of loop only.  The complete loop is the
75714     ** following pseudocode (template 4):
75715     **
75716     **         rewind temp table
75717     **      C: loop over rows of intermediate table
75718     **           transfer values form intermediate table into <table>
75719     **         end loop
75720     **      D: ...
75721     */
75722     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab);
75723     addrCont = sqlite3VdbeCurrentAddr(v);
75724   }else if( pSelect ){
75725     /* This block codes the top of loop only.  The complete loop is the
75726     ** following pseudocode (template 3):
75727     **
75728     **      C: yield X
75729     **         if EOF goto D
75730     **         insert the select result into <table> from R..R+n
75731     **         goto C
75732     **      D: ...
75733     */
75734     addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iParm);
75735     addrInsTop = sqlite3VdbeAddOp1(v, OP_If, regEof);
75736   }
75737
75738   /* Allocate registers for holding the rowid of the new row,
75739   ** the content of the new row, and the assemblied row record.
75740   */
75741   regRecord = ++pParse->nMem;
75742   regRowid = regIns = pParse->nMem+1;
75743   pParse->nMem += pTab->nCol + 1;
75744   if( IsVirtual(pTab) ){
75745     regRowid++;
75746     pParse->nMem++;
75747   }
75748   regData = regRowid+1;
75749
75750   /* Run the BEFORE and INSTEAD OF triggers, if there are any
75751   */
75752   endOfLoop = sqlite3VdbeMakeLabel(v);
75753   if( tmask & TRIGGER_BEFORE ){
75754     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
75755
75756     /* build the NEW.* reference row.  Note that if there is an INTEGER
75757     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
75758     ** translated into a unique ID for the row.  But on a BEFORE trigger,
75759     ** we do not know what the unique ID will be (because the insert has
75760     ** not happened yet) so we substitute a rowid of -1
75761     */
75762     if( keyColumn<0 ){
75763       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
75764     }else{
75765       int j1;
75766       if( useTempTable ){
75767         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regCols);
75768       }else{
75769         assert( pSelect==0 );  /* Otherwise useTempTable is true */
75770         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regCols);
75771       }
75772       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols);
75773       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
75774       sqlite3VdbeJumpHere(v, j1);
75775       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols);
75776     }
75777
75778     /* Cannot have triggers on a virtual table. If it were possible,
75779     ** this block would have to account for hidden column.
75780     */
75781     assert( !IsVirtual(pTab) );
75782
75783     /* Create the new column data
75784     */
75785     for(i=0; i<pTab->nCol; i++){
75786       if( pColumn==0 ){
75787         j = i;
75788       }else{
75789         for(j=0; j<pColumn->nId; j++){
75790           if( pColumn->a[j].idx==i ) break;
75791         }
75792       }
75793       if( pColumn && j>=pColumn->nId ){
75794         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
75795       }else if( useTempTable ){
75796         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
75797       }else{
75798         assert( pSelect==0 ); /* Otherwise useTempTable is true */
75799         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
75800       }
75801     }
75802
75803     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
75804     ** do not attempt any conversions before assembling the record.
75805     ** If this is a real table, attempt conversions as required by the
75806     ** table column affinities.
75807     */
75808     if( !isView ){
75809       sqlite3VdbeAddOp2(v, OP_Affinity, regCols+1, pTab->nCol);
75810       sqlite3TableAffinityStr(v, pTab);
75811     }
75812
75813     /* Fire BEFORE or INSTEAD OF triggers */
75814     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
75815         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
75816
75817     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
75818   }
75819
75820   /* Push the record number for the new entry onto the stack.  The
75821   ** record number is a randomly generate integer created by NewRowid
75822   ** except when the table has an INTEGER PRIMARY KEY column, in which
75823   ** case the record number is the same as that column. 
75824   */
75825   if( !isView ){
75826     if( IsVirtual(pTab) ){
75827       /* The row that the VUpdate opcode will delete: none */
75828       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
75829     }
75830     if( keyColumn>=0 ){
75831       if( useTempTable ){
75832         sqlite3VdbeAddOp3(v, OP_Column, srcTab, keyColumn, regRowid);
75833       }else if( pSelect ){
75834         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+keyColumn, regRowid);
75835       }else{
75836         VdbeOp *pOp;
75837         sqlite3ExprCode(pParse, pList->a[keyColumn].pExpr, regRowid);
75838         pOp = sqlite3VdbeGetOp(v, -1);
75839         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
75840           appendFlag = 1;
75841           pOp->opcode = OP_NewRowid;
75842           pOp->p1 = baseCur;
75843           pOp->p2 = regRowid;
75844           pOp->p3 = regAutoinc;
75845         }
75846       }
75847       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
75848       ** to generate a unique primary key value.
75849       */
75850       if( !appendFlag ){
75851         int j1;
75852         if( !IsVirtual(pTab) ){
75853           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid);
75854           sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
75855           sqlite3VdbeJumpHere(v, j1);
75856         }else{
75857           j1 = sqlite3VdbeCurrentAddr(v);
75858           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2);
75859         }
75860         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid);
75861       }
75862     }else if( IsVirtual(pTab) ){
75863       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
75864     }else{
75865       sqlite3VdbeAddOp3(v, OP_NewRowid, baseCur, regRowid, regAutoinc);
75866       appendFlag = 1;
75867     }
75868     autoIncStep(pParse, regAutoinc, regRowid);
75869
75870     /* Push onto the stack, data for all columns of the new entry, beginning
75871     ** with the first column.
75872     */
75873     nHidden = 0;
75874     for(i=0; i<pTab->nCol; i++){
75875       int iRegStore = regRowid+1+i;
75876       if( i==pTab->iPKey ){
75877         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
75878         ** Whenever this column is read, the record number will be substituted
75879         ** in its place.  So will fill this column with a NULL to avoid
75880         ** taking up data space with information that will never be used. */
75881         sqlite3VdbeAddOp2(v, OP_Null, 0, iRegStore);
75882         continue;
75883       }
75884       if( pColumn==0 ){
75885         if( IsHiddenColumn(&pTab->aCol[i]) ){
75886           assert( IsVirtual(pTab) );
75887           j = -1;
75888           nHidden++;
75889         }else{
75890           j = i - nHidden;
75891         }
75892       }else{
75893         for(j=0; j<pColumn->nId; j++){
75894           if( pColumn->a[j].idx==i ) break;
75895         }
75896       }
75897       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
75898         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, iRegStore);
75899       }else if( useTempTable ){
75900         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
75901       }else if( pSelect ){
75902         sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
75903       }else{
75904         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
75905       }
75906     }
75907
75908     /* Generate code to check constraints and generate index keys and
75909     ** do the insertion.
75910     */
75911 #ifndef SQLITE_OMIT_VIRTUALTABLE
75912     if( IsVirtual(pTab) ){
75913       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
75914       sqlite3VtabMakeWritable(pParse, pTab);
75915       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
75916       sqlite3MayAbort(pParse);
75917     }else
75918 #endif
75919     {
75920       int isReplace;    /* Set to true if constraints may cause a replace */
75921       sqlite3GenerateConstraintChecks(pParse, pTab, baseCur, regIns, aRegIdx,
75922           keyColumn>=0, 0, onError, endOfLoop, &isReplace
75923       );
75924       sqlite3FkCheck(pParse, pTab, 0, regIns);
75925       sqlite3CompleteInsertion(
75926           pParse, pTab, baseCur, regIns, aRegIdx, 0, appendFlag, isReplace==0
75927       );
75928     }
75929   }
75930
75931   /* Update the count of rows that are inserted
75932   */
75933   if( (db->flags & SQLITE_CountRows)!=0 ){
75934     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
75935   }
75936
75937   if( pTrigger ){
75938     /* Code AFTER triggers */
75939     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
75940         pTab, regData-2-pTab->nCol, onError, endOfLoop);
75941   }
75942
75943   /* The bottom of the main insertion loop, if the data source
75944   ** is a SELECT statement.
75945   */
75946   sqlite3VdbeResolveLabel(v, endOfLoop);
75947   if( useTempTable ){
75948     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont);
75949     sqlite3VdbeJumpHere(v, addrInsTop);
75950     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
75951   }else if( pSelect ){
75952     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
75953     sqlite3VdbeJumpHere(v, addrInsTop);
75954   }
75955
75956   if( !IsVirtual(pTab) && !isView ){
75957     /* Close all tables opened */
75958     sqlite3VdbeAddOp1(v, OP_Close, baseCur);
75959     for(idx=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
75960       sqlite3VdbeAddOp1(v, OP_Close, idx+baseCur);
75961     }
75962   }
75963
75964 insert_end:
75965   /* Update the sqlite_sequence table by storing the content of the
75966   ** maximum rowid counter values recorded while inserting into
75967   ** autoincrement tables.
75968   */
75969   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
75970     sqlite3AutoincrementEnd(pParse);
75971   }
75972
75973   /*
75974   ** Return the number of rows inserted. If this routine is 
75975   ** generating code because of a call to sqlite3NestedParse(), do not
75976   ** invoke the callback function.
75977   */
75978   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
75979     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
75980     sqlite3VdbeSetNumCols(v, 1);
75981     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
75982   }
75983
75984 insert_cleanup:
75985   sqlite3SrcListDelete(db, pTabList);
75986   sqlite3ExprListDelete(db, pList);
75987   sqlite3SelectDelete(db, pSelect);
75988   sqlite3IdListDelete(db, pColumn);
75989   sqlite3DbFree(db, aRegIdx);
75990 }
75991
75992 /* Make sure "isView" and other macros defined above are undefined. Otherwise
75993 ** thely may interfere with compilation of other functions in this file
75994 ** (or in another file, if this file becomes part of the amalgamation).  */
75995 #ifdef isView
75996  #undef isView
75997 #endif
75998 #ifdef pTrigger
75999  #undef pTrigger
76000 #endif
76001 #ifdef tmask
76002  #undef tmask
76003 #endif
76004
76005
76006 /*
76007 ** Generate code to do constraint checks prior to an INSERT or an UPDATE.
76008 **
76009 ** The input is a range of consecutive registers as follows:
76010 **
76011 **    1.  The rowid of the row after the update.
76012 **
76013 **    2.  The data in the first column of the entry after the update.
76014 **
76015 **    i.  Data from middle columns...
76016 **
76017 **    N.  The data in the last column of the entry after the update.
76018 **
76019 ** The regRowid parameter is the index of the register containing (1).
76020 **
76021 ** If isUpdate is true and rowidChng is non-zero, then rowidChng contains
76022 ** the address of a register containing the rowid before the update takes
76023 ** place. isUpdate is true for UPDATEs and false for INSERTs. If isUpdate
76024 ** is false, indicating an INSERT statement, then a non-zero rowidChng 
76025 ** indicates that the rowid was explicitly specified as part of the
76026 ** INSERT statement. If rowidChng is false, it means that  the rowid is
76027 ** computed automatically in an insert or that the rowid value is not 
76028 ** modified by an update.
76029 **
76030 ** The code generated by this routine store new index entries into
76031 ** registers identified by aRegIdx[].  No index entry is created for
76032 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
76033 ** the same as the order of indices on the linked list of indices
76034 ** attached to the table.
76035 **
76036 ** This routine also generates code to check constraints.  NOT NULL,
76037 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
76038 ** then the appropriate action is performed.  There are five possible
76039 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
76040 **
76041 **  Constraint type  Action       What Happens
76042 **  ---------------  ----------   ----------------------------------------
76043 **  any              ROLLBACK     The current transaction is rolled back and
76044 **                                sqlite3_exec() returns immediately with a
76045 **                                return code of SQLITE_CONSTRAINT.
76046 **
76047 **  any              ABORT        Back out changes from the current command
76048 **                                only (do not do a complete rollback) then
76049 **                                cause sqlite3_exec() to return immediately
76050 **                                with SQLITE_CONSTRAINT.
76051 **
76052 **  any              FAIL         Sqlite_exec() returns immediately with a
76053 **                                return code of SQLITE_CONSTRAINT.  The
76054 **                                transaction is not rolled back and any
76055 **                                prior changes are retained.
76056 **
76057 **  any              IGNORE       The record number and data is popped from
76058 **                                the stack and there is an immediate jump
76059 **                                to label ignoreDest.
76060 **
76061 **  NOT NULL         REPLACE      The NULL value is replace by the default
76062 **                                value for that column.  If the default value
76063 **                                is NULL, the action is the same as ABORT.
76064 **
76065 **  UNIQUE           REPLACE      The other row that conflicts with the row
76066 **                                being inserted is removed.
76067 **
76068 **  CHECK            REPLACE      Illegal.  The results in an exception.
76069 **
76070 ** Which action to take is determined by the overrideError parameter.
76071 ** Or if overrideError==OE_Default, then the pParse->onError parameter
76072 ** is used.  Or if pParse->onError==OE_Default then the onError value
76073 ** for the constraint is used.
76074 **
76075 ** The calling routine must open a read/write cursor for pTab with
76076 ** cursor number "baseCur".  All indices of pTab must also have open
76077 ** read/write cursors with cursor number baseCur+i for the i-th cursor.
76078 ** Except, if there is no possibility of a REPLACE action then
76079 ** cursors do not need to be open for indices where aRegIdx[i]==0.
76080 */
76081 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
76082   Parse *pParse,      /* The parser context */
76083   Table *pTab,        /* the table into which we are inserting */
76084   int baseCur,        /* Index of a read/write cursor pointing at pTab */
76085   int regRowid,       /* Index of the range of input registers */
76086   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
76087   int rowidChng,      /* True if the rowid might collide with existing entry */
76088   int isUpdate,       /* True for UPDATE, False for INSERT */
76089   int overrideError,  /* Override onError to this if not OE_Default */
76090   int ignoreDest,     /* Jump to this label on an OE_Ignore resolution */
76091   int *pbMayReplace   /* OUT: Set to true if constraint may cause a replace */
76092 ){
76093   int i;              /* loop counter */
76094   Vdbe *v;            /* VDBE under constrution */
76095   int nCol;           /* Number of columns */
76096   int onError;        /* Conflict resolution strategy */
76097   int j1;             /* Addresss of jump instruction */
76098   int j2 = 0, j3;     /* Addresses of jump instructions */
76099   int regData;        /* Register containing first data column */
76100   int iCur;           /* Table cursor number */
76101   Index *pIdx;         /* Pointer to one of the indices */
76102   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
76103   int regOldRowid = (rowidChng && isUpdate) ? rowidChng : regRowid;
76104
76105   v = sqlite3GetVdbe(pParse);
76106   assert( v!=0 );
76107   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
76108   nCol = pTab->nCol;
76109   regData = regRowid + 1;
76110
76111   /* Test all NOT NULL constraints.
76112   */
76113   for(i=0; i<nCol; i++){
76114     if( i==pTab->iPKey ){
76115       continue;
76116     }
76117     onError = pTab->aCol[i].notNull;
76118     if( onError==OE_None ) continue;
76119     if( overrideError!=OE_Default ){
76120       onError = overrideError;
76121     }else if( onError==OE_Default ){
76122       onError = OE_Abort;
76123     }
76124     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
76125       onError = OE_Abort;
76126     }
76127     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
76128         || onError==OE_Ignore || onError==OE_Replace );
76129     switch( onError ){
76130       case OE_Abort:
76131         sqlite3MayAbort(pParse);
76132       case OE_Rollback:
76133       case OE_Fail: {
76134         char *zMsg;
76135         j1 = sqlite3VdbeAddOp3(v, OP_HaltIfNull,
76136                                   SQLITE_CONSTRAINT, onError, regData+i);
76137         zMsg = sqlite3MPrintf(pParse->db, "%s.%s may not be NULL",
76138                               pTab->zName, pTab->aCol[i].zName);
76139         sqlite3VdbeChangeP4(v, -1, zMsg, P4_DYNAMIC);
76140         break;
76141       }
76142       case OE_Ignore: {
76143         sqlite3VdbeAddOp2(v, OP_IsNull, regData+i, ignoreDest);
76144         break;
76145       }
76146       default: {
76147         assert( onError==OE_Replace );
76148         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regData+i);
76149         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regData+i);
76150         sqlite3VdbeJumpHere(v, j1);
76151         break;
76152       }
76153     }
76154   }
76155
76156   /* Test all CHECK constraints
76157   */
76158 #ifndef SQLITE_OMIT_CHECK
76159   if( pTab->pCheck && (pParse->db->flags & SQLITE_IgnoreChecks)==0 ){
76160     int allOk = sqlite3VdbeMakeLabel(v);
76161     pParse->ckBase = regData;
76162     sqlite3ExprIfTrue(pParse, pTab->pCheck, allOk, SQLITE_JUMPIFNULL);
76163     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
76164     if( onError==OE_Ignore ){
76165       sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
76166     }else{
76167       sqlite3HaltConstraint(pParse, onError, 0, 0);
76168     }
76169     sqlite3VdbeResolveLabel(v, allOk);
76170   }
76171 #endif /* !defined(SQLITE_OMIT_CHECK) */
76172
76173   /* If we have an INTEGER PRIMARY KEY, make sure the primary key
76174   ** of the new record does not previously exist.  Except, if this
76175   ** is an UPDATE and the primary key is not changing, that is OK.
76176   */
76177   if( rowidChng ){
76178     onError = pTab->keyConf;
76179     if( overrideError!=OE_Default ){
76180       onError = overrideError;
76181     }else if( onError==OE_Default ){
76182       onError = OE_Abort;
76183     }
76184     
76185     if( isUpdate ){
76186       j2 = sqlite3VdbeAddOp3(v, OP_Eq, regRowid, 0, rowidChng);
76187     }
76188     j3 = sqlite3VdbeAddOp3(v, OP_NotExists, baseCur, 0, regRowid);
76189     switch( onError ){
76190       default: {
76191         onError = OE_Abort;
76192         /* Fall thru into the next case */
76193       }
76194       case OE_Rollback:
76195       case OE_Abort:
76196       case OE_Fail: {
76197         sqlite3HaltConstraint(
76198           pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
76199         break;
76200       }
76201       case OE_Replace: {
76202         /* If there are DELETE triggers on this table and the
76203         ** recursive-triggers flag is set, call GenerateRowDelete() to
76204         ** remove the conflicting row from the the table. This will fire
76205         ** the triggers and remove both the table and index b-tree entries.
76206         **
76207         ** Otherwise, if there are no triggers or the recursive-triggers
76208         ** flag is not set, but the table has one or more indexes, call 
76209         ** GenerateRowIndexDelete(). This removes the index b-tree entries 
76210         ** only. The table b-tree entry will be replaced by the new entry 
76211         ** when it is inserted.  
76212         **
76213         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
76214         ** also invoke MultiWrite() to indicate that this VDBE may require
76215         ** statement rollback (if the statement is aborted after the delete
76216         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
76217         ** but being more selective here allows statements like:
76218         **
76219         **   REPLACE INTO t(rowid) VALUES($newrowid)
76220         **
76221         ** to run without a statement journal if there are no indexes on the
76222         ** table.
76223         */
76224         Trigger *pTrigger = 0;
76225         if( pParse->db->flags&SQLITE_RecTriggers ){
76226           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
76227         }
76228         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
76229           sqlite3MultiWrite(pParse);
76230           sqlite3GenerateRowDelete(
76231               pParse, pTab, baseCur, regRowid, 0, pTrigger, OE_Replace
76232           );
76233         }else if( pTab->pIndex ){
76234           sqlite3MultiWrite(pParse);
76235           sqlite3GenerateRowIndexDelete(pParse, pTab, baseCur, 0);
76236         }
76237         seenReplace = 1;
76238         break;
76239       }
76240       case OE_Ignore: {
76241         assert( seenReplace==0 );
76242         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
76243         break;
76244       }
76245     }
76246     sqlite3VdbeJumpHere(v, j3);
76247     if( isUpdate ){
76248       sqlite3VdbeJumpHere(v, j2);
76249     }
76250   }
76251
76252   /* Test all UNIQUE constraints by creating entries for each UNIQUE
76253   ** index and making sure that duplicate entries do not already exist.
76254   ** Add the new records to the indices as we go.
76255   */
76256   for(iCur=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, iCur++){
76257     int regIdx;
76258     int regR;
76259
76260     if( aRegIdx[iCur]==0 ) continue;  /* Skip unused indices */
76261
76262     /* Create a key for accessing the index entry */
76263     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn+1);
76264     for(i=0; i<pIdx->nColumn; i++){
76265       int idx = pIdx->aiColumn[i];
76266       if( idx==pTab->iPKey ){
76267         sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
76268       }else{
76269         sqlite3VdbeAddOp2(v, OP_SCopy, regData+idx, regIdx+i);
76270       }
76271     }
76272     sqlite3VdbeAddOp2(v, OP_SCopy, regRowid, regIdx+i);
76273     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn+1, aRegIdx[iCur]);
76274     sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), 0);
76275     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn+1);
76276
76277     /* Find out what action to take in case there is an indexing conflict */
76278     onError = pIdx->onError;
76279     if( onError==OE_None ){ 
76280       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
76281       continue;  /* pIdx is not a UNIQUE index */
76282     }
76283     if( overrideError!=OE_Default ){
76284       onError = overrideError;
76285     }else if( onError==OE_Default ){
76286       onError = OE_Abort;
76287     }
76288     if( seenReplace ){
76289       if( onError==OE_Ignore ) onError = OE_Replace;
76290       else if( onError==OE_Fail ) onError = OE_Abort;
76291     }
76292     
76293     /* Check to see if the new index entry will be unique */
76294     regR = sqlite3GetTempReg(pParse);
76295     sqlite3VdbeAddOp2(v, OP_SCopy, regOldRowid, regR);
76296     j3 = sqlite3VdbeAddOp4(v, OP_IsUnique, baseCur+iCur+1, 0,
76297                            regR, SQLITE_INT_TO_PTR(regIdx),
76298                            P4_INT32);
76299     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn+1);
76300
76301     /* Generate code that executes if the new index entry is not unique */
76302     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
76303         || onError==OE_Ignore || onError==OE_Replace );
76304     switch( onError ){
76305       case OE_Rollback:
76306       case OE_Abort:
76307       case OE_Fail: {
76308         int j;
76309         StrAccum errMsg;
76310         const char *zSep;
76311         char *zErr;
76312
76313         sqlite3StrAccumInit(&errMsg, 0, 0, 200);
76314         errMsg.db = pParse->db;
76315         zSep = pIdx->nColumn>1 ? "columns " : "column ";
76316         for(j=0; j<pIdx->nColumn; j++){
76317           char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
76318           sqlite3StrAccumAppend(&errMsg, zSep, -1);
76319           zSep = ", ";
76320           sqlite3StrAccumAppend(&errMsg, zCol, -1);
76321         }
76322         sqlite3StrAccumAppend(&errMsg,
76323             pIdx->nColumn>1 ? " are not unique" : " is not unique", -1);
76324         zErr = sqlite3StrAccumFinish(&errMsg);
76325         sqlite3HaltConstraint(pParse, onError, zErr, 0);
76326         sqlite3DbFree(errMsg.db, zErr);
76327         break;
76328       }
76329       case OE_Ignore: {
76330         assert( seenReplace==0 );
76331         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
76332         break;
76333       }
76334       default: {
76335         Trigger *pTrigger = 0;
76336         assert( onError==OE_Replace );
76337         sqlite3MultiWrite(pParse);
76338         if( pParse->db->flags&SQLITE_RecTriggers ){
76339           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
76340         }
76341         sqlite3GenerateRowDelete(
76342             pParse, pTab, baseCur, regR, 0, pTrigger, OE_Replace
76343         );
76344         seenReplace = 1;
76345         break;
76346       }
76347     }
76348     sqlite3VdbeJumpHere(v, j3);
76349     sqlite3ReleaseTempReg(pParse, regR);
76350   }
76351   
76352   if( pbMayReplace ){
76353     *pbMayReplace = seenReplace;
76354   }
76355 }
76356
76357 /*
76358 ** This routine generates code to finish the INSERT or UPDATE operation
76359 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
76360 ** A consecutive range of registers starting at regRowid contains the
76361 ** rowid and the content to be inserted.
76362 **
76363 ** The arguments to this routine should be the same as the first six
76364 ** arguments to sqlite3GenerateConstraintChecks.
76365 */
76366 SQLITE_PRIVATE void sqlite3CompleteInsertion(
76367   Parse *pParse,      /* The parser context */
76368   Table *pTab,        /* the table into which we are inserting */
76369   int baseCur,        /* Index of a read/write cursor pointing at pTab */
76370   int regRowid,       /* Range of content */
76371   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
76372   int isUpdate,       /* True for UPDATE, False for INSERT */
76373   int appendBias,     /* True if this is likely to be an append */
76374   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
76375 ){
76376   int i;
76377   Vdbe *v;
76378   int nIdx;
76379   Index *pIdx;
76380   u8 pik_flags;
76381   int regData;
76382   int regRec;
76383
76384   v = sqlite3GetVdbe(pParse);
76385   assert( v!=0 );
76386   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
76387   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
76388   for(i=nIdx-1; i>=0; i--){
76389     if( aRegIdx[i]==0 ) continue;
76390     sqlite3VdbeAddOp2(v, OP_IdxInsert, baseCur+i+1, aRegIdx[i]);
76391     if( useSeekResult ){
76392       sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
76393     }
76394   }
76395   regData = regRowid + 1;
76396   regRec = sqlite3GetTempReg(pParse);
76397   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
76398   sqlite3TableAffinityStr(v, pTab);
76399   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
76400   if( pParse->nested ){
76401     pik_flags = 0;
76402   }else{
76403     pik_flags = OPFLAG_NCHANGE;
76404     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
76405   }
76406   if( appendBias ){
76407     pik_flags |= OPFLAG_APPEND;
76408   }
76409   if( useSeekResult ){
76410     pik_flags |= OPFLAG_USESEEKRESULT;
76411   }
76412   sqlite3VdbeAddOp3(v, OP_Insert, baseCur, regRec, regRowid);
76413   if( !pParse->nested ){
76414     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_STATIC);
76415   }
76416   sqlite3VdbeChangeP5(v, pik_flags);
76417 }
76418
76419 /*
76420 ** Generate code that will open cursors for a table and for all
76421 ** indices of that table.  The "baseCur" parameter is the cursor number used
76422 ** for the table.  Indices are opened on subsequent cursors.
76423 **
76424 ** Return the number of indices on the table.
76425 */
76426 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
76427   Parse *pParse,   /* Parsing context */
76428   Table *pTab,     /* Table to be opened */
76429   int baseCur,     /* Cursor number assigned to the table */
76430   int op           /* OP_OpenRead or OP_OpenWrite */
76431 ){
76432   int i;
76433   int iDb;
76434   Index *pIdx;
76435   Vdbe *v;
76436
76437   if( IsVirtual(pTab) ) return 0;
76438   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
76439   v = sqlite3GetVdbe(pParse);
76440   assert( v!=0 );
76441   sqlite3OpenTable(pParse, baseCur, iDb, pTab, op);
76442   for(i=1, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
76443     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
76444     assert( pIdx->pSchema==pTab->pSchema );
76445     sqlite3VdbeAddOp4(v, op, i+baseCur, pIdx->tnum, iDb,
76446                       (char*)pKey, P4_KEYINFO_HANDOFF);
76447     VdbeComment((v, "%s", pIdx->zName));
76448   }
76449   if( pParse->nTab<baseCur+i ){
76450     pParse->nTab = baseCur+i;
76451   }
76452   return i-1;
76453 }
76454
76455
76456 #ifdef SQLITE_TEST
76457 /*
76458 ** The following global variable is incremented whenever the
76459 ** transfer optimization is used.  This is used for testing
76460 ** purposes only - to make sure the transfer optimization really
76461 ** is happening when it is suppose to.
76462 */
76463 SQLITE_API int sqlite3_xferopt_count;
76464 #endif /* SQLITE_TEST */
76465
76466
76467 #ifndef SQLITE_OMIT_XFER_OPT
76468 /*
76469 ** Check to collation names to see if they are compatible.
76470 */
76471 static int xferCompatibleCollation(const char *z1, const char *z2){
76472   if( z1==0 ){
76473     return z2==0;
76474   }
76475   if( z2==0 ){
76476     return 0;
76477   }
76478   return sqlite3StrICmp(z1, z2)==0;
76479 }
76480
76481
76482 /*
76483 ** Check to see if index pSrc is compatible as a source of data
76484 ** for index pDest in an insert transfer optimization.  The rules
76485 ** for a compatible index:
76486 **
76487 **    *   The index is over the same set of columns
76488 **    *   The same DESC and ASC markings occurs on all columns
76489 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
76490 **    *   The same collating sequence on each column
76491 */
76492 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
76493   int i;
76494   assert( pDest && pSrc );
76495   assert( pDest->pTable!=pSrc->pTable );
76496   if( pDest->nColumn!=pSrc->nColumn ){
76497     return 0;   /* Different number of columns */
76498   }
76499   if( pDest->onError!=pSrc->onError ){
76500     return 0;   /* Different conflict resolution strategies */
76501   }
76502   for(i=0; i<pSrc->nColumn; i++){
76503     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
76504       return 0;   /* Different columns indexed */
76505     }
76506     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
76507       return 0;   /* Different sort orders */
76508     }
76509     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
76510       return 0;   /* Different collating sequences */
76511     }
76512   }
76513
76514   /* If no test above fails then the indices must be compatible */
76515   return 1;
76516 }
76517
76518 /*
76519 ** Attempt the transfer optimization on INSERTs of the form
76520 **
76521 **     INSERT INTO tab1 SELECT * FROM tab2;
76522 **
76523 ** This optimization is only attempted if
76524 **
76525 **    (1)  tab1 and tab2 have identical schemas including all the
76526 **         same indices and constraints
76527 **
76528 **    (2)  tab1 and tab2 are different tables
76529 **
76530 **    (3)  There must be no triggers on tab1
76531 **
76532 **    (4)  The result set of the SELECT statement is "*"
76533 **
76534 **    (5)  The SELECT statement has no WHERE, HAVING, ORDER BY, GROUP BY,
76535 **         or LIMIT clause.
76536 **
76537 **    (6)  The SELECT statement is a simple (not a compound) select that
76538 **         contains only tab2 in its FROM clause
76539 **
76540 ** This method for implementing the INSERT transfers raw records from
76541 ** tab2 over to tab1.  The columns are not decoded.  Raw records from
76542 ** the indices of tab2 are transfered to tab1 as well.  In so doing,
76543 ** the resulting tab1 has much less fragmentation.
76544 **
76545 ** This routine returns TRUE if the optimization is attempted.  If any
76546 ** of the conditions above fail so that the optimization should not
76547 ** be attempted, then this routine returns FALSE.
76548 */
76549 static int xferOptimization(
76550   Parse *pParse,        /* Parser context */
76551   Table *pDest,         /* The table we are inserting into */
76552   Select *pSelect,      /* A SELECT statement to use as the data source */
76553   int onError,          /* How to handle constraint errors */
76554   int iDbDest           /* The database of pDest */
76555 ){
76556   ExprList *pEList;                /* The result set of the SELECT */
76557   Table *pSrc;                     /* The table in the FROM clause of SELECT */
76558   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
76559   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
76560   int i;                           /* Loop counter */
76561   int iDbSrc;                      /* The database of pSrc */
76562   int iSrc, iDest;                 /* Cursors from source and destination */
76563   int addr1, addr2;                /* Loop addresses */
76564   int emptyDestTest;               /* Address of test for empty pDest */
76565   int emptySrcTest;                /* Address of test for empty pSrc */
76566   Vdbe *v;                         /* The VDBE we are building */
76567   KeyInfo *pKey;                   /* Key information for an index */
76568   int regAutoinc;                  /* Memory register used by AUTOINC */
76569   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
76570   int regData, regRowid;           /* Registers holding data and rowid */
76571
76572   if( pSelect==0 ){
76573     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
76574   }
76575   if( sqlite3TriggerList(pParse, pDest) ){
76576     return 0;   /* tab1 must not have triggers */
76577   }
76578 #ifndef SQLITE_OMIT_VIRTUALTABLE
76579   if( pDest->tabFlags & TF_Virtual ){
76580     return 0;   /* tab1 must not be a virtual table */
76581   }
76582 #endif
76583   if( onError==OE_Default ){
76584     onError = OE_Abort;
76585   }
76586   if( onError!=OE_Abort && onError!=OE_Rollback ){
76587     return 0;   /* Cannot do OR REPLACE or OR IGNORE or OR FAIL */
76588   }
76589   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
76590   if( pSelect->pSrc->nSrc!=1 ){
76591     return 0;   /* FROM clause must have exactly one term */
76592   }
76593   if( pSelect->pSrc->a[0].pSelect ){
76594     return 0;   /* FROM clause cannot contain a subquery */
76595   }
76596   if( pSelect->pWhere ){
76597     return 0;   /* SELECT may not have a WHERE clause */
76598   }
76599   if( pSelect->pOrderBy ){
76600     return 0;   /* SELECT may not have an ORDER BY clause */
76601   }
76602   /* Do not need to test for a HAVING clause.  If HAVING is present but
76603   ** there is no ORDER BY, we will get an error. */
76604   if( pSelect->pGroupBy ){
76605     return 0;   /* SELECT may not have a GROUP BY clause */
76606   }
76607   if( pSelect->pLimit ){
76608     return 0;   /* SELECT may not have a LIMIT clause */
76609   }
76610   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
76611   if( pSelect->pPrior ){
76612     return 0;   /* SELECT may not be a compound query */
76613   }
76614   if( pSelect->selFlags & SF_Distinct ){
76615     return 0;   /* SELECT may not be DISTINCT */
76616   }
76617   pEList = pSelect->pEList;
76618   assert( pEList!=0 );
76619   if( pEList->nExpr!=1 ){
76620     return 0;   /* The result set must have exactly one column */
76621   }
76622   assert( pEList->a[0].pExpr );
76623   if( pEList->a[0].pExpr->op!=TK_ALL ){
76624     return 0;   /* The result set must be the special operator "*" */
76625   }
76626
76627   /* At this point we have established that the statement is of the
76628   ** correct syntactic form to participate in this optimization.  Now
76629   ** we have to check the semantics.
76630   */
76631   pItem = pSelect->pSrc->a;
76632   pSrc = sqlite3LocateTable(pParse, 0, pItem->zName, pItem->zDatabase);
76633   if( pSrc==0 ){
76634     return 0;   /* FROM clause does not contain a real table */
76635   }
76636   if( pSrc==pDest ){
76637     return 0;   /* tab1 and tab2 may not be the same table */
76638   }
76639 #ifndef SQLITE_OMIT_VIRTUALTABLE
76640   if( pSrc->tabFlags & TF_Virtual ){
76641     return 0;   /* tab2 must not be a virtual table */
76642   }
76643 #endif
76644   if( pSrc->pSelect ){
76645     return 0;   /* tab2 may not be a view */
76646   }
76647   if( pDest->nCol!=pSrc->nCol ){
76648     return 0;   /* Number of columns must be the same in tab1 and tab2 */
76649   }
76650   if( pDest->iPKey!=pSrc->iPKey ){
76651     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
76652   }
76653   for(i=0; i<pDest->nCol; i++){
76654     if( pDest->aCol[i].affinity!=pSrc->aCol[i].affinity ){
76655       return 0;    /* Affinity must be the same on all columns */
76656     }
76657     if( !xferCompatibleCollation(pDest->aCol[i].zColl, pSrc->aCol[i].zColl) ){
76658       return 0;    /* Collating sequence must be the same on all columns */
76659     }
76660     if( pDest->aCol[i].notNull && !pSrc->aCol[i].notNull ){
76661       return 0;    /* tab2 must be NOT NULL if tab1 is */
76662     }
76663   }
76664   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
76665     if( pDestIdx->onError!=OE_None ){
76666       destHasUniqueIdx = 1;
76667     }
76668     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
76669       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
76670     }
76671     if( pSrcIdx==0 ){
76672       return 0;    /* pDestIdx has no corresponding index in pSrc */
76673     }
76674   }
76675 #ifndef SQLITE_OMIT_CHECK
76676   if( pDest->pCheck && sqlite3ExprCompare(pSrc->pCheck, pDest->pCheck) ){
76677     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
76678   }
76679 #endif
76680
76681   /* If we get this far, it means either:
76682   **
76683   **    *   We can always do the transfer if the table contains an
76684   **        an integer primary key
76685   **
76686   **    *   We can conditionally do the transfer if the destination
76687   **        table is empty.
76688   */
76689 #ifdef SQLITE_TEST
76690   sqlite3_xferopt_count++;
76691 #endif
76692   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
76693   v = sqlite3GetVdbe(pParse);
76694   sqlite3CodeVerifySchema(pParse, iDbSrc);
76695   iSrc = pParse->nTab++;
76696   iDest = pParse->nTab++;
76697   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
76698   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
76699   if( (pDest->iPKey<0 && pDest->pIndex!=0) || destHasUniqueIdx ){
76700     /* If tables do not have an INTEGER PRIMARY KEY and there
76701     ** are indices to be copied and the destination is not empty,
76702     ** we have to disallow the transfer optimization because the
76703     ** the rowids might change which will mess up indexing.
76704     **
76705     ** Or if the destination has a UNIQUE index and is not empty,
76706     ** we also disallow the transfer optimization because we cannot
76707     ** insure that all entries in the union of DEST and SRC will be
76708     ** unique.
76709     */
76710     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0);
76711     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
76712     sqlite3VdbeJumpHere(v, addr1);
76713   }else{
76714     emptyDestTest = 0;
76715   }
76716   sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
76717   emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
76718   regData = sqlite3GetTempReg(pParse);
76719   regRowid = sqlite3GetTempReg(pParse);
76720   if( pDest->iPKey>=0 ){
76721     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
76722     addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
76723     sqlite3HaltConstraint(
76724         pParse, onError, "PRIMARY KEY must be unique", P4_STATIC);
76725     sqlite3VdbeJumpHere(v, addr2);
76726     autoIncStep(pParse, regAutoinc, regRowid);
76727   }else if( pDest->pIndex==0 ){
76728     addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
76729   }else{
76730     addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
76731     assert( (pDest->tabFlags & TF_Autoincrement)==0 );
76732   }
76733   sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
76734   sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
76735   sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
76736   sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
76737   sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1);
76738   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
76739     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
76740       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
76741     }
76742     assert( pSrcIdx );
76743     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
76744     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
76745     pKey = sqlite3IndexKeyinfo(pParse, pSrcIdx);
76746     sqlite3VdbeAddOp4(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc,
76747                       (char*)pKey, P4_KEYINFO_HANDOFF);
76748     VdbeComment((v, "%s", pSrcIdx->zName));
76749     pKey = sqlite3IndexKeyinfo(pParse, pDestIdx);
76750     sqlite3VdbeAddOp4(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest,
76751                       (char*)pKey, P4_KEYINFO_HANDOFF);
76752     VdbeComment((v, "%s", pDestIdx->zName));
76753     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0);
76754     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
76755     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
76756     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1);
76757     sqlite3VdbeJumpHere(v, addr1);
76758   }
76759   sqlite3VdbeJumpHere(v, emptySrcTest);
76760   sqlite3ReleaseTempReg(pParse, regRowid);
76761   sqlite3ReleaseTempReg(pParse, regData);
76762   sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
76763   sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
76764   if( emptyDestTest ){
76765     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
76766     sqlite3VdbeJumpHere(v, emptyDestTest);
76767     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
76768     return 0;
76769   }else{
76770     return 1;
76771   }
76772 }
76773 #endif /* SQLITE_OMIT_XFER_OPT */
76774
76775 /************** End of insert.c **********************************************/
76776 /************** Begin file legacy.c ******************************************/
76777 /*
76778 ** 2001 September 15
76779 **
76780 ** The author disclaims copyright to this source code.  In place of
76781 ** a legal notice, here is a blessing:
76782 **
76783 **    May you do good and not evil.
76784 **    May you find forgiveness for yourself and forgive others.
76785 **    May you share freely, never taking more than you give.
76786 **
76787 *************************************************************************
76788 ** Main file for the SQLite library.  The routines in this file
76789 ** implement the programmer interface to the library.  Routines in
76790 ** other files are for internal use by SQLite and should not be
76791 ** accessed by users of the library.
76792 */
76793
76794
76795 /*
76796 ** Execute SQL code.  Return one of the SQLITE_ success/failure
76797 ** codes.  Also write an error message into memory obtained from
76798 ** malloc() and make *pzErrMsg point to that message.
76799 **
76800 ** If the SQL is a query, then for each row in the query result
76801 ** the xCallback() function is called.  pArg becomes the first
76802 ** argument to xCallback().  If xCallback=NULL then no callback
76803 ** is invoked, even for queries.
76804 */
76805 SQLITE_API int sqlite3_exec(
76806   sqlite3 *db,                /* The database on which the SQL executes */
76807   const char *zSql,           /* The SQL to be executed */
76808   sqlite3_callback xCallback, /* Invoke this callback routine */
76809   void *pArg,                 /* First argument to xCallback() */
76810   char **pzErrMsg             /* Write error messages here */
76811 ){
76812   int rc = SQLITE_OK;         /* Return code */
76813   const char *zLeftover;      /* Tail of unprocessed SQL */
76814   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
76815   char **azCols = 0;          /* Names of result columns */
76816   int nRetry = 0;             /* Number of retry attempts */
76817   int callbackIsInit;         /* True if callback data is initialized */
76818
76819   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
76820   if( zSql==0 ) zSql = "";
76821
76822   sqlite3_mutex_enter(db->mutex);
76823   sqlite3Error(db, SQLITE_OK, 0);
76824   while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
76825     int nCol;
76826     char **azVals = 0;
76827
76828     pStmt = 0;
76829     rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
76830     assert( rc==SQLITE_OK || pStmt==0 );
76831     if( rc!=SQLITE_OK ){
76832       continue;
76833     }
76834     if( !pStmt ){
76835       /* this happens for a comment or white-space */
76836       zSql = zLeftover;
76837       continue;
76838     }
76839
76840     callbackIsInit = 0;
76841     nCol = sqlite3_column_count(pStmt);
76842
76843     while( 1 ){
76844       int i;
76845       rc = sqlite3_step(pStmt);
76846
76847       /* Invoke the callback function if required */
76848       if( xCallback && (SQLITE_ROW==rc || 
76849           (SQLITE_DONE==rc && !callbackIsInit
76850                            && db->flags&SQLITE_NullCallback)) ){
76851         if( !callbackIsInit ){
76852           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
76853           if( azCols==0 ){
76854             goto exec_out;
76855           }
76856           for(i=0; i<nCol; i++){
76857             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
76858             /* sqlite3VdbeSetColName() installs column names as UTF8
76859             ** strings so there is no way for sqlite3_column_name() to fail. */
76860             assert( azCols[i]!=0 );
76861           }
76862           callbackIsInit = 1;
76863         }
76864         if( rc==SQLITE_ROW ){
76865           azVals = &azCols[nCol];
76866           for(i=0; i<nCol; i++){
76867             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
76868             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
76869               db->mallocFailed = 1;
76870               goto exec_out;
76871             }
76872           }
76873         }
76874         if( xCallback(pArg, nCol, azVals, azCols) ){
76875           rc = SQLITE_ABORT;
76876           sqlite3VdbeFinalize((Vdbe *)pStmt);
76877           pStmt = 0;
76878           sqlite3Error(db, SQLITE_ABORT, 0);
76879           goto exec_out;
76880         }
76881       }
76882
76883       if( rc!=SQLITE_ROW ){
76884         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
76885         pStmt = 0;
76886         if( rc!=SQLITE_SCHEMA ){
76887           nRetry = 0;
76888           zSql = zLeftover;
76889           while( sqlite3Isspace(zSql[0]) ) zSql++;
76890         }
76891         break;
76892       }
76893     }
76894
76895     sqlite3DbFree(db, azCols);
76896     azCols = 0;
76897   }
76898
76899 exec_out:
76900   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
76901   sqlite3DbFree(db, azCols);
76902
76903   rc = sqlite3ApiExit(db, rc);
76904   if( rc!=SQLITE_OK && ALWAYS(rc==sqlite3_errcode(db)) && pzErrMsg ){
76905     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
76906     *pzErrMsg = sqlite3Malloc(nErrMsg);
76907     if( *pzErrMsg ){
76908       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
76909     }else{
76910       rc = SQLITE_NOMEM;
76911       sqlite3Error(db, SQLITE_NOMEM, 0);
76912     }
76913   }else if( pzErrMsg ){
76914     *pzErrMsg = 0;
76915   }
76916
76917   assert( (rc&db->errMask)==rc );
76918   sqlite3_mutex_leave(db->mutex);
76919   return rc;
76920 }
76921
76922 /************** End of legacy.c **********************************************/
76923 /************** Begin file loadext.c *****************************************/
76924 /*
76925 ** 2006 June 7
76926 **
76927 ** The author disclaims copyright to this source code.  In place of
76928 ** a legal notice, here is a blessing:
76929 **
76930 **    May you do good and not evil.
76931 **    May you find forgiveness for yourself and forgive others.
76932 **    May you share freely, never taking more than you give.
76933 **
76934 *************************************************************************
76935 ** This file contains code used to dynamically load extensions into
76936 ** the SQLite library.
76937 */
76938
76939 #ifndef SQLITE_CORE
76940   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
76941 #endif
76942 /************** Include sqlite3ext.h in the middle of loadext.c **************/
76943 /************** Begin file sqlite3ext.h **************************************/
76944 /*
76945 ** 2006 June 7
76946 **
76947 ** The author disclaims copyright to this source code.  In place of
76948 ** a legal notice, here is a blessing:
76949 **
76950 **    May you do good and not evil.
76951 **    May you find forgiveness for yourself and forgive others.
76952 **    May you share freely, never taking more than you give.
76953 **
76954 *************************************************************************
76955 ** This header file defines the SQLite interface for use by
76956 ** shared libraries that want to be imported as extensions into
76957 ** an SQLite instance.  Shared libraries that intend to be loaded
76958 ** as extensions by SQLite should #include this file instead of 
76959 ** sqlite3.h.
76960 */
76961 #ifndef _SQLITE3EXT_H_
76962 #define _SQLITE3EXT_H_
76963
76964 typedef struct sqlite3_api_routines sqlite3_api_routines;
76965
76966 /*
76967 ** The following structure holds pointers to all of the SQLite API
76968 ** routines.
76969 **
76970 ** WARNING:  In order to maintain backwards compatibility, add new
76971 ** interfaces to the end of this structure only.  If you insert new
76972 ** interfaces in the middle of this structure, then older different
76973 ** versions of SQLite will not be able to load each others' shared
76974 ** libraries!
76975 */
76976 struct sqlite3_api_routines {
76977   void * (*aggregate_context)(sqlite3_context*,int nBytes);
76978   int  (*aggregate_count)(sqlite3_context*);
76979   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
76980   int  (*bind_double)(sqlite3_stmt*,int,double);
76981   int  (*bind_int)(sqlite3_stmt*,int,int);
76982   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
76983   int  (*bind_null)(sqlite3_stmt*,int);
76984   int  (*bind_parameter_count)(sqlite3_stmt*);
76985   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
76986   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
76987   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
76988   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
76989   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
76990   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
76991   int  (*busy_timeout)(sqlite3*,int ms);
76992   int  (*changes)(sqlite3*);
76993   int  (*close)(sqlite3*);
76994   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const char*));
76995   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,int eTextRep,const void*));
76996   const void * (*column_blob)(sqlite3_stmt*,int iCol);
76997   int  (*column_bytes)(sqlite3_stmt*,int iCol);
76998   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
76999   int  (*column_count)(sqlite3_stmt*pStmt);
77000   const char * (*column_database_name)(sqlite3_stmt*,int);
77001   const void * (*column_database_name16)(sqlite3_stmt*,int);
77002   const char * (*column_decltype)(sqlite3_stmt*,int i);
77003   const void * (*column_decltype16)(sqlite3_stmt*,int);
77004   double  (*column_double)(sqlite3_stmt*,int iCol);
77005   int  (*column_int)(sqlite3_stmt*,int iCol);
77006   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
77007   const char * (*column_name)(sqlite3_stmt*,int);
77008   const void * (*column_name16)(sqlite3_stmt*,int);
77009   const char * (*column_origin_name)(sqlite3_stmt*,int);
77010   const void * (*column_origin_name16)(sqlite3_stmt*,int);
77011   const char * (*column_table_name)(sqlite3_stmt*,int);
77012   const void * (*column_table_name16)(sqlite3_stmt*,int);
77013   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
77014   const void * (*column_text16)(sqlite3_stmt*,int iCol);
77015   int  (*column_type)(sqlite3_stmt*,int iCol);
77016   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
77017   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
77018   int  (*complete)(const char*sql);
77019   int  (*complete16)(const void*sql);
77020   int  (*create_collation)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*));
77021   int  (*create_collation16)(sqlite3*,const void*,int,void*,int(*)(void*,int,const void*,int,const void*));
77022   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*));
77023   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*));
77024   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
77025   int  (*data_count)(sqlite3_stmt*pStmt);
77026   sqlite3 * (*db_handle)(sqlite3_stmt*);
77027   int (*declare_vtab)(sqlite3*,const char*);
77028   int  (*enable_shared_cache)(int);
77029   int  (*errcode)(sqlite3*db);
77030   const char * (*errmsg)(sqlite3*);
77031   const void * (*errmsg16)(sqlite3*);
77032   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
77033   int  (*expired)(sqlite3_stmt*);
77034   int  (*finalize)(sqlite3_stmt*pStmt);
77035   void  (*free)(void*);
77036   void  (*free_table)(char**result);
77037   int  (*get_autocommit)(sqlite3*);
77038   void * (*get_auxdata)(sqlite3_context*,int);
77039   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
77040   int  (*global_recover)(void);
77041   void  (*interruptx)(sqlite3*);
77042   sqlite_int64  (*last_insert_rowid)(sqlite3*);
77043   const char * (*libversion)(void);
77044   int  (*libversion_number)(void);
77045   void *(*malloc)(int);
77046   char * (*mprintf)(const char*,...);
77047   int  (*open)(const char*,sqlite3**);
77048   int  (*open16)(const void*,sqlite3**);
77049   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
77050   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
77051   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
77052   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
77053   void *(*realloc)(void*,int);
77054   int  (*reset)(sqlite3_stmt*pStmt);
77055   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
77056   void  (*result_double)(sqlite3_context*,double);
77057   void  (*result_error)(sqlite3_context*,const char*,int);
77058   void  (*result_error16)(sqlite3_context*,const void*,int);
77059   void  (*result_int)(sqlite3_context*,int);
77060   void  (*result_int64)(sqlite3_context*,sqlite_int64);
77061   void  (*result_null)(sqlite3_context*);
77062   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
77063   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
77064   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
77065   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
77066   void  (*result_value)(sqlite3_context*,sqlite3_value*);
77067   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
77068   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,const char*,const char*),void*);
77069   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
77070   char * (*snprintf)(int,char*,const char*,...);
77071   int  (*step)(sqlite3_stmt*);
77072   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,char const**,char const**,int*,int*,int*);
77073   void  (*thread_cleanup)(void);
77074   int  (*total_changes)(sqlite3*);
77075   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
77076   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
77077   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,sqlite_int64),void*);
77078   void * (*user_data)(sqlite3_context*);
77079   const void * (*value_blob)(sqlite3_value*);
77080   int  (*value_bytes)(sqlite3_value*);
77081   int  (*value_bytes16)(sqlite3_value*);
77082   double  (*value_double)(sqlite3_value*);
77083   int  (*value_int)(sqlite3_value*);
77084   sqlite_int64  (*value_int64)(sqlite3_value*);
77085   int  (*value_numeric_type)(sqlite3_value*);
77086   const unsigned char * (*value_text)(sqlite3_value*);
77087   const void * (*value_text16)(sqlite3_value*);
77088   const void * (*value_text16be)(sqlite3_value*);
77089   const void * (*value_text16le)(sqlite3_value*);
77090   int  (*value_type)(sqlite3_value*);
77091   char *(*vmprintf)(const char*,va_list);
77092   /* Added ??? */
77093   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
77094   /* Added by 3.3.13 */
77095   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
77096   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
77097   int (*clear_bindings)(sqlite3_stmt*);
77098   /* Added by 3.4.1 */
77099   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,void (*xDestroy)(void *));
77100   /* Added by 3.5.0 */
77101   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
77102   int (*blob_bytes)(sqlite3_blob*);
77103   int (*blob_close)(sqlite3_blob*);
77104   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,int,sqlite3_blob**);
77105   int (*blob_read)(sqlite3_blob*,void*,int,int);
77106   int (*blob_write)(sqlite3_blob*,const void*,int,int);
77107   int (*create_collation_v2)(sqlite3*,const char*,int,void*,int(*)(void*,int,const void*,int,const void*),void(*)(void*));
77108   int (*file_control)(sqlite3*,const char*,int,void*);
77109   sqlite3_int64 (*memory_highwater)(int);
77110   sqlite3_int64 (*memory_used)(void);
77111   sqlite3_mutex *(*mutex_alloc)(int);
77112   void (*mutex_enter)(sqlite3_mutex*);
77113   void (*mutex_free)(sqlite3_mutex*);
77114   void (*mutex_leave)(sqlite3_mutex*);
77115   int (*mutex_try)(sqlite3_mutex*);
77116   int (*open_v2)(const char*,sqlite3**,int,const char*);
77117   int (*release_memory)(int);
77118   void (*result_error_nomem)(sqlite3_context*);
77119   void (*result_error_toobig)(sqlite3_context*);
77120   int (*sleep)(int);
77121   void (*soft_heap_limit)(int);
77122   sqlite3_vfs *(*vfs_find)(const char*);
77123   int (*vfs_register)(sqlite3_vfs*,int);
77124   int (*vfs_unregister)(sqlite3_vfs*);
77125   int (*xthreadsafe)(void);
77126   void (*result_zeroblob)(sqlite3_context*,int);
77127   void (*result_error_code)(sqlite3_context*,int);
77128   int (*test_control)(int, ...);
77129   void (*randomness)(int,void*);
77130   sqlite3 *(*context_db_handle)(sqlite3_context*);
77131   int (*extended_result_codes)(sqlite3*,int);
77132   int (*limit)(sqlite3*,int,int);
77133   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
77134   const char *(*sql)(sqlite3_stmt*);
77135   int (*status)(int,int*,int*,int);
77136 };
77137
77138 /*
77139 ** The following macros redefine the API routines so that they are
77140 ** redirected throught the global sqlite3_api structure.
77141 **
77142 ** This header file is also used by the loadext.c source file
77143 ** (part of the main SQLite library - not an extension) so that
77144 ** it can get access to the sqlite3_api_routines structure
77145 ** definition.  But the main library does not want to redefine
77146 ** the API.  So the redefinition macros are only valid if the
77147 ** SQLITE_CORE macros is undefined.
77148 */
77149 #ifndef SQLITE_CORE
77150 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
77151 #ifndef SQLITE_OMIT_DEPRECATED
77152 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
77153 #endif
77154 #define sqlite3_bind_blob              sqlite3_api->bind_blob
77155 #define sqlite3_bind_double            sqlite3_api->bind_double
77156 #define sqlite3_bind_int               sqlite3_api->bind_int
77157 #define sqlite3_bind_int64             sqlite3_api->bind_int64
77158 #define sqlite3_bind_null              sqlite3_api->bind_null
77159 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
77160 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
77161 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
77162 #define sqlite3_bind_text              sqlite3_api->bind_text
77163 #define sqlite3_bind_text16            sqlite3_api->bind_text16
77164 #define sqlite3_bind_value             sqlite3_api->bind_value
77165 #define sqlite3_busy_handler           sqlite3_api->busy_handler
77166 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
77167 #define sqlite3_changes                sqlite3_api->changes
77168 #define sqlite3_close                  sqlite3_api->close
77169 #define sqlite3_collation_needed       sqlite3_api->collation_needed
77170 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
77171 #define sqlite3_column_blob            sqlite3_api->column_blob
77172 #define sqlite3_column_bytes           sqlite3_api->column_bytes
77173 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
77174 #define sqlite3_column_count           sqlite3_api->column_count
77175 #define sqlite3_column_database_name   sqlite3_api->column_database_name
77176 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
77177 #define sqlite3_column_decltype        sqlite3_api->column_decltype
77178 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
77179 #define sqlite3_column_double          sqlite3_api->column_double
77180 #define sqlite3_column_int             sqlite3_api->column_int
77181 #define sqlite3_column_int64           sqlite3_api->column_int64
77182 #define sqlite3_column_name            sqlite3_api->column_name
77183 #define sqlite3_column_name16          sqlite3_api->column_name16
77184 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
77185 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
77186 #define sqlite3_column_table_name      sqlite3_api->column_table_name
77187 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
77188 #define sqlite3_column_text            sqlite3_api->column_text
77189 #define sqlite3_column_text16          sqlite3_api->column_text16
77190 #define sqlite3_column_type            sqlite3_api->column_type
77191 #define sqlite3_column_value           sqlite3_api->column_value
77192 #define sqlite3_commit_hook            sqlite3_api->commit_hook
77193 #define sqlite3_complete               sqlite3_api->complete
77194 #define sqlite3_complete16             sqlite3_api->complete16
77195 #define sqlite3_create_collation       sqlite3_api->create_collation
77196 #define sqlite3_create_collation16     sqlite3_api->create_collation16
77197 #define sqlite3_create_function        sqlite3_api->create_function
77198 #define sqlite3_create_function16      sqlite3_api->create_function16
77199 #define sqlite3_create_module          sqlite3_api->create_module
77200 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
77201 #define sqlite3_data_count             sqlite3_api->data_count
77202 #define sqlite3_db_handle              sqlite3_api->db_handle
77203 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
77204 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
77205 #define sqlite3_errcode                sqlite3_api->errcode
77206 #define sqlite3_errmsg                 sqlite3_api->errmsg
77207 #define sqlite3_errmsg16               sqlite3_api->errmsg16
77208 #define sqlite3_exec                   sqlite3_api->exec
77209 #ifndef SQLITE_OMIT_DEPRECATED
77210 #define sqlite3_expired                sqlite3_api->expired
77211 #endif
77212 #define sqlite3_finalize               sqlite3_api->finalize
77213 #define sqlite3_free                   sqlite3_api->free
77214 #define sqlite3_free_table             sqlite3_api->free_table
77215 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
77216 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
77217 #define sqlite3_get_table              sqlite3_api->get_table
77218 #ifndef SQLITE_OMIT_DEPRECATED
77219 #define sqlite3_global_recover         sqlite3_api->global_recover
77220 #endif
77221 #define sqlite3_interrupt              sqlite3_api->interruptx
77222 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
77223 #define sqlite3_libversion             sqlite3_api->libversion
77224 #define sqlite3_libversion_number      sqlite3_api->libversion_number
77225 #define sqlite3_malloc                 sqlite3_api->malloc
77226 #define sqlite3_mprintf                sqlite3_api->mprintf
77227 #define sqlite3_open                   sqlite3_api->open
77228 #define sqlite3_open16                 sqlite3_api->open16
77229 #define sqlite3_prepare                sqlite3_api->prepare
77230 #define sqlite3_prepare16              sqlite3_api->prepare16
77231 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
77232 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
77233 #define sqlite3_profile                sqlite3_api->profile
77234 #define sqlite3_progress_handler       sqlite3_api->progress_handler
77235 #define sqlite3_realloc                sqlite3_api->realloc
77236 #define sqlite3_reset                  sqlite3_api->reset
77237 #define sqlite3_result_blob            sqlite3_api->result_blob
77238 #define sqlite3_result_double          sqlite3_api->result_double
77239 #define sqlite3_result_error           sqlite3_api->result_error
77240 #define sqlite3_result_error16         sqlite3_api->result_error16
77241 #define sqlite3_result_int             sqlite3_api->result_int
77242 #define sqlite3_result_int64           sqlite3_api->result_int64
77243 #define sqlite3_result_null            sqlite3_api->result_null
77244 #define sqlite3_result_text            sqlite3_api->result_text
77245 #define sqlite3_result_text16          sqlite3_api->result_text16
77246 #define sqlite3_result_text16be        sqlite3_api->result_text16be
77247 #define sqlite3_result_text16le        sqlite3_api->result_text16le
77248 #define sqlite3_result_value           sqlite3_api->result_value
77249 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
77250 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
77251 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
77252 #define sqlite3_snprintf               sqlite3_api->snprintf
77253 #define sqlite3_step                   sqlite3_api->step
77254 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
77255 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
77256 #define sqlite3_total_changes          sqlite3_api->total_changes
77257 #define sqlite3_trace                  sqlite3_api->trace
77258 #ifndef SQLITE_OMIT_DEPRECATED
77259 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
77260 #endif
77261 #define sqlite3_update_hook            sqlite3_api->update_hook
77262 #define sqlite3_user_data              sqlite3_api->user_data
77263 #define sqlite3_value_blob             sqlite3_api->value_blob
77264 #define sqlite3_value_bytes            sqlite3_api->value_bytes
77265 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
77266 #define sqlite3_value_double           sqlite3_api->value_double
77267 #define sqlite3_value_int              sqlite3_api->value_int
77268 #define sqlite3_value_int64            sqlite3_api->value_int64
77269 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
77270 #define sqlite3_value_text             sqlite3_api->value_text
77271 #define sqlite3_value_text16           sqlite3_api->value_text16
77272 #define sqlite3_value_text16be         sqlite3_api->value_text16be
77273 #define sqlite3_value_text16le         sqlite3_api->value_text16le
77274 #define sqlite3_value_type             sqlite3_api->value_type
77275 #define sqlite3_vmprintf               sqlite3_api->vmprintf
77276 #define sqlite3_overload_function      sqlite3_api->overload_function
77277 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
77278 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
77279 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
77280 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
77281 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
77282 #define sqlite3_blob_close             sqlite3_api->blob_close
77283 #define sqlite3_blob_open              sqlite3_api->blob_open
77284 #define sqlite3_blob_read              sqlite3_api->blob_read
77285 #define sqlite3_blob_write             sqlite3_api->blob_write
77286 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
77287 #define sqlite3_file_control           sqlite3_api->file_control
77288 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
77289 #define sqlite3_memory_used            sqlite3_api->memory_used
77290 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
77291 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
77292 #define sqlite3_mutex_free             sqlite3_api->mutex_free
77293 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
77294 #define sqlite3_mutex_try              sqlite3_api->mutex_try
77295 #define sqlite3_open_v2                sqlite3_api->open_v2
77296 #define sqlite3_release_memory         sqlite3_api->release_memory
77297 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
77298 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
77299 #define sqlite3_sleep                  sqlite3_api->sleep
77300 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
77301 #define sqlite3_vfs_find               sqlite3_api->vfs_find
77302 #define sqlite3_vfs_register           sqlite3_api->vfs_register
77303 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
77304 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
77305 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
77306 #define sqlite3_result_error_code      sqlite3_api->result_error_code
77307 #define sqlite3_test_control           sqlite3_api->test_control
77308 #define sqlite3_randomness             sqlite3_api->randomness
77309 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
77310 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
77311 #define sqlite3_limit                  sqlite3_api->limit
77312 #define sqlite3_next_stmt              sqlite3_api->next_stmt
77313 #define sqlite3_sql                    sqlite3_api->sql
77314 #define sqlite3_status                 sqlite3_api->status
77315 #endif /* SQLITE_CORE */
77316
77317 #define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api = 0;
77318 #define SQLITE_EXTENSION_INIT2(v)  sqlite3_api = v;
77319
77320 #endif /* _SQLITE3EXT_H_ */
77321
77322 /************** End of sqlite3ext.h ******************************************/
77323 /************** Continuing where we left off in loadext.c ********************/
77324
77325 #ifndef SQLITE_OMIT_LOAD_EXTENSION
77326
77327 /*
77328 ** Some API routines are omitted when various features are
77329 ** excluded from a build of SQLite.  Substitute a NULL pointer
77330 ** for any missing APIs.
77331 */
77332 #ifndef SQLITE_ENABLE_COLUMN_METADATA
77333 # define sqlite3_column_database_name   0
77334 # define sqlite3_column_database_name16 0
77335 # define sqlite3_column_table_name      0
77336 # define sqlite3_column_table_name16    0
77337 # define sqlite3_column_origin_name     0
77338 # define sqlite3_column_origin_name16   0
77339 # define sqlite3_table_column_metadata  0
77340 #endif
77341
77342 #ifdef SQLITE_OMIT_AUTHORIZATION
77343 # define sqlite3_set_authorizer         0
77344 #endif
77345
77346 #ifdef SQLITE_OMIT_UTF16
77347 # define sqlite3_bind_text16            0
77348 # define sqlite3_collation_needed16     0
77349 # define sqlite3_column_decltype16      0
77350 # define sqlite3_column_name16          0
77351 # define sqlite3_column_text16          0
77352 # define sqlite3_complete16             0
77353 # define sqlite3_create_collation16     0
77354 # define sqlite3_create_function16      0
77355 # define sqlite3_errmsg16               0
77356 # define sqlite3_open16                 0
77357 # define sqlite3_prepare16              0
77358 # define sqlite3_prepare16_v2           0
77359 # define sqlite3_result_error16         0
77360 # define sqlite3_result_text16          0
77361 # define sqlite3_result_text16be        0
77362 # define sqlite3_result_text16le        0
77363 # define sqlite3_value_text16           0
77364 # define sqlite3_value_text16be         0
77365 # define sqlite3_value_text16le         0
77366 # define sqlite3_column_database_name16 0
77367 # define sqlite3_column_table_name16    0
77368 # define sqlite3_column_origin_name16   0
77369 #endif
77370
77371 #ifdef SQLITE_OMIT_COMPLETE
77372 # define sqlite3_complete 0
77373 # define sqlite3_complete16 0
77374 #endif
77375
77376 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
77377 # define sqlite3_progress_handler 0
77378 #endif
77379
77380 #ifdef SQLITE_OMIT_VIRTUALTABLE
77381 # define sqlite3_create_module 0
77382 # define sqlite3_create_module_v2 0
77383 # define sqlite3_declare_vtab 0
77384 #endif
77385
77386 #ifdef SQLITE_OMIT_SHARED_CACHE
77387 # define sqlite3_enable_shared_cache 0
77388 #endif
77389
77390 #ifdef SQLITE_OMIT_TRACE
77391 # define sqlite3_profile       0
77392 # define sqlite3_trace         0
77393 #endif
77394
77395 #ifdef SQLITE_OMIT_GET_TABLE
77396 # define sqlite3_free_table    0
77397 # define sqlite3_get_table     0
77398 #endif
77399
77400 #ifdef SQLITE_OMIT_INCRBLOB
77401 #define sqlite3_bind_zeroblob  0
77402 #define sqlite3_blob_bytes     0
77403 #define sqlite3_blob_close     0
77404 #define sqlite3_blob_open      0
77405 #define sqlite3_blob_read      0
77406 #define sqlite3_blob_write     0
77407 #endif
77408
77409 /*
77410 ** The following structure contains pointers to all SQLite API routines.
77411 ** A pointer to this structure is passed into extensions when they are
77412 ** loaded so that the extension can make calls back into the SQLite
77413 ** library.
77414 **
77415 ** When adding new APIs, add them to the bottom of this structure
77416 ** in order to preserve backwards compatibility.
77417 **
77418 ** Extensions that use newer APIs should first call the
77419 ** sqlite3_libversion_number() to make sure that the API they
77420 ** intend to use is supported by the library.  Extensions should
77421 ** also check to make sure that the pointer to the function is
77422 ** not NULL before calling it.
77423 */
77424 static const sqlite3_api_routines sqlite3Apis = {
77425   sqlite3_aggregate_context,
77426 #ifndef SQLITE_OMIT_DEPRECATED
77427   sqlite3_aggregate_count,
77428 #else
77429   0,
77430 #endif
77431   sqlite3_bind_blob,
77432   sqlite3_bind_double,
77433   sqlite3_bind_int,
77434   sqlite3_bind_int64,
77435   sqlite3_bind_null,
77436   sqlite3_bind_parameter_count,
77437   sqlite3_bind_parameter_index,
77438   sqlite3_bind_parameter_name,
77439   sqlite3_bind_text,
77440   sqlite3_bind_text16,
77441   sqlite3_bind_value,
77442   sqlite3_busy_handler,
77443   sqlite3_busy_timeout,
77444   sqlite3_changes,
77445   sqlite3_close,
77446   sqlite3_collation_needed,
77447   sqlite3_collation_needed16,
77448   sqlite3_column_blob,
77449   sqlite3_column_bytes,
77450   sqlite3_column_bytes16,
77451   sqlite3_column_count,
77452   sqlite3_column_database_name,
77453   sqlite3_column_database_name16,
77454   sqlite3_column_decltype,
77455   sqlite3_column_decltype16,
77456   sqlite3_column_double,
77457   sqlite3_column_int,
77458   sqlite3_column_int64,
77459   sqlite3_column_name,
77460   sqlite3_column_name16,
77461   sqlite3_column_origin_name,
77462   sqlite3_column_origin_name16,
77463   sqlite3_column_table_name,
77464   sqlite3_column_table_name16,
77465   sqlite3_column_text,
77466   sqlite3_column_text16,
77467   sqlite3_column_type,
77468   sqlite3_column_value,
77469   sqlite3_commit_hook,
77470   sqlite3_complete,
77471   sqlite3_complete16,
77472   sqlite3_create_collation,
77473   sqlite3_create_collation16,
77474   sqlite3_create_function,
77475   sqlite3_create_function16,
77476   sqlite3_create_module,
77477   sqlite3_data_count,
77478   sqlite3_db_handle,
77479   sqlite3_declare_vtab,
77480   sqlite3_enable_shared_cache,
77481   sqlite3_errcode,
77482   sqlite3_errmsg,
77483   sqlite3_errmsg16,
77484   sqlite3_exec,
77485 #ifndef SQLITE_OMIT_DEPRECATED
77486   sqlite3_expired,
77487 #else
77488   0,
77489 #endif
77490   sqlite3_finalize,
77491   sqlite3_free,
77492   sqlite3_free_table,
77493   sqlite3_get_autocommit,
77494   sqlite3_get_auxdata,
77495   sqlite3_get_table,
77496   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
77497   sqlite3_interrupt,
77498   sqlite3_last_insert_rowid,
77499   sqlite3_libversion,
77500   sqlite3_libversion_number,
77501   sqlite3_malloc,
77502   sqlite3_mprintf,
77503   sqlite3_open,
77504   sqlite3_open16,
77505   sqlite3_prepare,
77506   sqlite3_prepare16,
77507   sqlite3_profile,
77508   sqlite3_progress_handler,
77509   sqlite3_realloc,
77510   sqlite3_reset,
77511   sqlite3_result_blob,
77512   sqlite3_result_double,
77513   sqlite3_result_error,
77514   sqlite3_result_error16,
77515   sqlite3_result_int,
77516   sqlite3_result_int64,
77517   sqlite3_result_null,
77518   sqlite3_result_text,
77519   sqlite3_result_text16,
77520   sqlite3_result_text16be,
77521   sqlite3_result_text16le,
77522   sqlite3_result_value,
77523   sqlite3_rollback_hook,
77524   sqlite3_set_authorizer,
77525   sqlite3_set_auxdata,
77526   sqlite3_snprintf,
77527   sqlite3_step,
77528   sqlite3_table_column_metadata,
77529 #ifndef SQLITE_OMIT_DEPRECATED
77530   sqlite3_thread_cleanup,
77531 #else
77532   0,
77533 #endif
77534   sqlite3_total_changes,
77535   sqlite3_trace,
77536 #ifndef SQLITE_OMIT_DEPRECATED
77537   sqlite3_transfer_bindings,
77538 #else
77539   0,
77540 #endif
77541   sqlite3_update_hook,
77542   sqlite3_user_data,
77543   sqlite3_value_blob,
77544   sqlite3_value_bytes,
77545   sqlite3_value_bytes16,
77546   sqlite3_value_double,
77547   sqlite3_value_int,
77548   sqlite3_value_int64,
77549   sqlite3_value_numeric_type,
77550   sqlite3_value_text,
77551   sqlite3_value_text16,
77552   sqlite3_value_text16be,
77553   sqlite3_value_text16le,
77554   sqlite3_value_type,
77555   sqlite3_vmprintf,
77556   /*
77557   ** The original API set ends here.  All extensions can call any
77558   ** of the APIs above provided that the pointer is not NULL.  But
77559   ** before calling APIs that follow, extension should check the
77560   ** sqlite3_libversion_number() to make sure they are dealing with
77561   ** a library that is new enough to support that API.
77562   *************************************************************************
77563   */
77564   sqlite3_overload_function,
77565
77566   /*
77567   ** Added after 3.3.13
77568   */
77569   sqlite3_prepare_v2,
77570   sqlite3_prepare16_v2,
77571   sqlite3_clear_bindings,
77572
77573   /*
77574   ** Added for 3.4.1
77575   */
77576   sqlite3_create_module_v2,
77577
77578   /*
77579   ** Added for 3.5.0
77580   */
77581   sqlite3_bind_zeroblob,
77582   sqlite3_blob_bytes,
77583   sqlite3_blob_close,
77584   sqlite3_blob_open,
77585   sqlite3_blob_read,
77586   sqlite3_blob_write,
77587   sqlite3_create_collation_v2,
77588   sqlite3_file_control,
77589   sqlite3_memory_highwater,
77590   sqlite3_memory_used,
77591 #ifdef SQLITE_MUTEX_OMIT
77592   0, 
77593   0, 
77594   0,
77595   0,
77596   0,
77597 #else
77598   sqlite3_mutex_alloc,
77599   sqlite3_mutex_enter,
77600   sqlite3_mutex_free,
77601   sqlite3_mutex_leave,
77602   sqlite3_mutex_try,
77603 #endif
77604   sqlite3_open_v2,
77605   sqlite3_release_memory,
77606   sqlite3_result_error_nomem,
77607   sqlite3_result_error_toobig,
77608   sqlite3_sleep,
77609   sqlite3_soft_heap_limit,
77610   sqlite3_vfs_find,
77611   sqlite3_vfs_register,
77612   sqlite3_vfs_unregister,
77613
77614   /*
77615   ** Added for 3.5.8
77616   */
77617   sqlite3_threadsafe,
77618   sqlite3_result_zeroblob,
77619   sqlite3_result_error_code,
77620   sqlite3_test_control,
77621   sqlite3_randomness,
77622   sqlite3_context_db_handle,
77623
77624   /*
77625   ** Added for 3.6.0
77626   */
77627   sqlite3_extended_result_codes,
77628   sqlite3_limit,
77629   sqlite3_next_stmt,
77630   sqlite3_sql,
77631   sqlite3_status,
77632 };
77633
77634 /*
77635 ** Attempt to load an SQLite extension library contained in the file
77636 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
77637 ** default entry point name (sqlite3_extension_init) is used.  Use
77638 ** of the default name is recommended.
77639 **
77640 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
77641 **
77642 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
77643 ** error message text.  The calling function should free this memory
77644 ** by calling sqlite3DbFree(db, ).
77645 */
77646 static int sqlite3LoadExtension(
77647   sqlite3 *db,          /* Load the extension into this database connection */
77648   const char *zFile,    /* Name of the shared library containing extension */
77649   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
77650   char **pzErrMsg       /* Put error message here if not 0 */
77651 ){
77652   sqlite3_vfs *pVfs = db->pVfs;
77653   void *handle;
77654   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
77655   char *zErrmsg = 0;
77656   void **aHandle;
77657   const int nMsg = 300;
77658
77659   if( pzErrMsg ) *pzErrMsg = 0;
77660
77661   /* Ticket #1863.  To avoid a creating security problems for older
77662   ** applications that relink against newer versions of SQLite, the
77663   ** ability to run load_extension is turned off by default.  One
77664   ** must call sqlite3_enable_load_extension() to turn on extension
77665   ** loading.  Otherwise you get the following error.
77666   */
77667   if( (db->flags & SQLITE_LoadExtension)==0 ){
77668     if( pzErrMsg ){
77669       *pzErrMsg = sqlite3_mprintf("not authorized");
77670     }
77671     return SQLITE_ERROR;
77672   }
77673
77674   if( zProc==0 ){
77675     zProc = "sqlite3_extension_init";
77676   }
77677
77678   handle = sqlite3OsDlOpen(pVfs, zFile);
77679   if( handle==0 ){
77680     if( pzErrMsg ){
77681       zErrmsg = sqlite3StackAllocZero(db, nMsg);
77682       if( zErrmsg ){
77683         sqlite3_snprintf(nMsg, zErrmsg, 
77684             "unable to open shared library [%s]", zFile);
77685         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
77686         *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
77687         sqlite3StackFree(db, zErrmsg);
77688       }
77689     }
77690     return SQLITE_ERROR;
77691   }
77692   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
77693                    sqlite3OsDlSym(pVfs, handle, zProc);
77694   if( xInit==0 ){
77695     if( pzErrMsg ){
77696       zErrmsg = sqlite3StackAllocZero(db, nMsg);
77697       if( zErrmsg ){
77698         sqlite3_snprintf(nMsg, zErrmsg,
77699             "no entry point [%s] in shared library [%s]", zProc,zFile);
77700         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
77701         *pzErrMsg = sqlite3DbStrDup(0, zErrmsg);
77702         sqlite3StackFree(db, zErrmsg);
77703       }
77704       sqlite3OsDlClose(pVfs, handle);
77705     }
77706     return SQLITE_ERROR;
77707   }else if( xInit(db, &zErrmsg, &sqlite3Apis) ){
77708     if( pzErrMsg ){
77709       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
77710     }
77711     sqlite3_free(zErrmsg);
77712     sqlite3OsDlClose(pVfs, handle);
77713     return SQLITE_ERROR;
77714   }
77715
77716   /* Append the new shared library handle to the db->aExtension array. */
77717   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
77718   if( aHandle==0 ){
77719     return SQLITE_NOMEM;
77720   }
77721   if( db->nExtension>0 ){
77722     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
77723   }
77724   sqlite3DbFree(db, db->aExtension);
77725   db->aExtension = aHandle;
77726
77727   db->aExtension[db->nExtension++] = handle;
77728   return SQLITE_OK;
77729 }
77730 SQLITE_API int sqlite3_load_extension(
77731   sqlite3 *db,          /* Load the extension into this database connection */
77732   const char *zFile,    /* Name of the shared library containing extension */
77733   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
77734   char **pzErrMsg       /* Put error message here if not 0 */
77735 ){
77736   int rc;
77737   sqlite3_mutex_enter(db->mutex);
77738   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
77739   rc = sqlite3ApiExit(db, rc);
77740   sqlite3_mutex_leave(db->mutex);
77741   return rc;
77742 }
77743
77744 /*
77745 ** Call this routine when the database connection is closing in order
77746 ** to clean up loaded extensions
77747 */
77748 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
77749   int i;
77750   assert( sqlite3_mutex_held(db->mutex) );
77751   for(i=0; i<db->nExtension; i++){
77752     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
77753   }
77754   sqlite3DbFree(db, db->aExtension);
77755 }
77756
77757 /*
77758 ** Enable or disable extension loading.  Extension loading is disabled by
77759 ** default so as not to open security holes in older applications.
77760 */
77761 SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
77762   sqlite3_mutex_enter(db->mutex);
77763   if( onoff ){
77764     db->flags |= SQLITE_LoadExtension;
77765   }else{
77766     db->flags &= ~SQLITE_LoadExtension;
77767   }
77768   sqlite3_mutex_leave(db->mutex);
77769   return SQLITE_OK;
77770 }
77771
77772 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
77773
77774 /*
77775 ** The auto-extension code added regardless of whether or not extension
77776 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
77777 ** code if regular extension loading is not available.  This is that
77778 ** dummy pointer.
77779 */
77780 #ifdef SQLITE_OMIT_LOAD_EXTENSION
77781 static const sqlite3_api_routines sqlite3Apis = { 0 };
77782 #endif
77783
77784
77785 /*
77786 ** The following object holds the list of automatically loaded
77787 ** extensions.
77788 **
77789 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
77790 ** mutex must be held while accessing this list.
77791 */
77792 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
77793 static SQLITE_WSD struct sqlite3AutoExtList {
77794   int nExt;              /* Number of entries in aExt[] */          
77795   void (**aExt)(void);   /* Pointers to the extension init functions */
77796 } sqlite3Autoext = { 0, 0 };
77797
77798 /* The "wsdAutoext" macro will resolve to the autoextension
77799 ** state vector.  If writable static data is unsupported on the target,
77800 ** we have to locate the state vector at run-time.  In the more common
77801 ** case where writable static data is supported, wsdStat can refer directly
77802 ** to the "sqlite3Autoext" state vector declared above.
77803 */
77804 #ifdef SQLITE_OMIT_WSD
77805 # define wsdAutoextInit \
77806   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
77807 # define wsdAutoext x[0]
77808 #else
77809 # define wsdAutoextInit
77810 # define wsdAutoext sqlite3Autoext
77811 #endif
77812
77813
77814 /*
77815 ** Register a statically linked extension that is automatically
77816 ** loaded by every new database connection.
77817 */
77818 SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
77819   int rc = SQLITE_OK;
77820 #ifndef SQLITE_OMIT_AUTOINIT
77821   rc = sqlite3_initialize();
77822   if( rc ){
77823     return rc;
77824   }else
77825 #endif
77826   {
77827     int i;
77828 #if SQLITE_THREADSAFE
77829     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
77830 #endif
77831     wsdAutoextInit;
77832     sqlite3_mutex_enter(mutex);
77833     for(i=0; i<wsdAutoext.nExt; i++){
77834       if( wsdAutoext.aExt[i]==xInit ) break;
77835     }
77836     if( i==wsdAutoext.nExt ){
77837       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
77838       void (**aNew)(void);
77839       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
77840       if( aNew==0 ){
77841         rc = SQLITE_NOMEM;
77842       }else{
77843         wsdAutoext.aExt = aNew;
77844         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
77845         wsdAutoext.nExt++;
77846       }
77847     }
77848     sqlite3_mutex_leave(mutex);
77849     assert( (rc&0xff)==rc );
77850     return rc;
77851   }
77852 }
77853
77854 /*
77855 ** Reset the automatic extension loading mechanism.
77856 */
77857 SQLITE_API void sqlite3_reset_auto_extension(void){
77858 #ifndef SQLITE_OMIT_AUTOINIT
77859   if( sqlite3_initialize()==SQLITE_OK )
77860 #endif
77861   {
77862 #if SQLITE_THREADSAFE
77863     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
77864 #endif
77865     wsdAutoextInit;
77866     sqlite3_mutex_enter(mutex);
77867     sqlite3_free(wsdAutoext.aExt);
77868     wsdAutoext.aExt = 0;
77869     wsdAutoext.nExt = 0;
77870     sqlite3_mutex_leave(mutex);
77871   }
77872 }
77873
77874 /*
77875 ** Load all automatic extensions.
77876 **
77877 ** If anything goes wrong, set an error in the database connection.
77878 */
77879 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
77880   int i;
77881   int go = 1;
77882   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
77883
77884   wsdAutoextInit;
77885   if( wsdAutoext.nExt==0 ){
77886     /* Common case: early out without every having to acquire a mutex */
77887     return;
77888   }
77889   for(i=0; go; i++){
77890     char *zErrmsg;
77891 #if SQLITE_THREADSAFE
77892     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
77893 #endif
77894     sqlite3_mutex_enter(mutex);
77895     if( i>=wsdAutoext.nExt ){
77896       xInit = 0;
77897       go = 0;
77898     }else{
77899       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
77900               wsdAutoext.aExt[i];
77901     }
77902     sqlite3_mutex_leave(mutex);
77903     zErrmsg = 0;
77904     if( xInit && xInit(db, &zErrmsg, &sqlite3Apis) ){
77905       sqlite3Error(db, SQLITE_ERROR,
77906             "automatic extension loading failed: %s", zErrmsg);
77907       go = 0;
77908     }
77909     sqlite3_free(zErrmsg);
77910   }
77911 }
77912
77913 /************** End of loadext.c *********************************************/
77914 /************** Begin file pragma.c ******************************************/
77915 /*
77916 ** 2003 April 6
77917 **
77918 ** The author disclaims copyright to this source code.  In place of
77919 ** a legal notice, here is a blessing:
77920 **
77921 **    May you do good and not evil.
77922 **    May you find forgiveness for yourself and forgive others.
77923 **    May you share freely, never taking more than you give.
77924 **
77925 *************************************************************************
77926 ** This file contains code used to implement the PRAGMA command.
77927 */
77928
77929 /* Ignore this whole file if pragmas are disabled
77930 */
77931 #if !defined(SQLITE_OMIT_PRAGMA)
77932
77933 /*
77934 ** Interpret the given string as a safety level.  Return 0 for OFF,
77935 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
77936 ** unrecognized string argument.
77937 **
77938 ** Note that the values returned are one less that the values that
77939 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
77940 ** to support legacy SQL code.  The safety level used to be boolean
77941 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
77942 */
77943 static u8 getSafetyLevel(const char *z){
77944                              /* 123456789 123456789 */
77945   static const char zText[] = "onoffalseyestruefull";
77946   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
77947   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
77948   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
77949   int i, n;
77950   if( sqlite3Isdigit(*z) ){
77951     return (u8)atoi(z);
77952   }
77953   n = sqlite3Strlen30(z);
77954   for(i=0; i<ArraySize(iLength); i++){
77955     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
77956       return iValue[i];
77957     }
77958   }
77959   return 1;
77960 }
77961
77962 /*
77963 ** Interpret the given string as a boolean value.
77964 */
77965 static u8 getBoolean(const char *z){
77966   return getSafetyLevel(z)&1;
77967 }
77968
77969 /*
77970 ** Interpret the given string as a locking mode value.
77971 */
77972 static int getLockingMode(const char *z){
77973   if( z ){
77974     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
77975     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
77976   }
77977   return PAGER_LOCKINGMODE_QUERY;
77978 }
77979
77980 #ifndef SQLITE_OMIT_AUTOVACUUM
77981 /*
77982 ** Interpret the given string as an auto-vacuum mode value.
77983 **
77984 ** The following strings, "none", "full" and "incremental" are 
77985 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
77986 */
77987 static int getAutoVacuum(const char *z){
77988   int i;
77989   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
77990   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
77991   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
77992   i = atoi(z);
77993   return (u8)((i>=0&&i<=2)?i:0);
77994 }
77995 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
77996
77997 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
77998 /*
77999 ** Interpret the given string as a temp db location. Return 1 for file
78000 ** backed temporary databases, 2 for the Red-Black tree in memory database
78001 ** and 0 to use the compile-time default.
78002 */
78003 static int getTempStore(const char *z){
78004   if( z[0]>='0' && z[0]<='2' ){
78005     return z[0] - '0';
78006   }else if( sqlite3StrICmp(z, "file")==0 ){
78007     return 1;
78008   }else if( sqlite3StrICmp(z, "memory")==0 ){
78009     return 2;
78010   }else{
78011     return 0;
78012   }
78013 }
78014 #endif /* SQLITE_PAGER_PRAGMAS */
78015
78016 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
78017 /*
78018 ** Invalidate temp storage, either when the temp storage is changed
78019 ** from default, or when 'file' and the temp_store_directory has changed
78020 */
78021 static int invalidateTempStorage(Parse *pParse){
78022   sqlite3 *db = pParse->db;
78023   if( db->aDb[1].pBt!=0 ){
78024     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
78025       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
78026         "from within a transaction");
78027       return SQLITE_ERROR;
78028     }
78029     sqlite3BtreeClose(db->aDb[1].pBt);
78030     db->aDb[1].pBt = 0;
78031     sqlite3ResetInternalSchema(db, 0);
78032   }
78033   return SQLITE_OK;
78034 }
78035 #endif /* SQLITE_PAGER_PRAGMAS */
78036
78037 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
78038 /*
78039 ** If the TEMP database is open, close it and mark the database schema
78040 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
78041 ** or DEFAULT_TEMP_STORE pragmas.
78042 */
78043 static int changeTempStorage(Parse *pParse, const char *zStorageType){
78044   int ts = getTempStore(zStorageType);
78045   sqlite3 *db = pParse->db;
78046   if( db->temp_store==ts ) return SQLITE_OK;
78047   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
78048     return SQLITE_ERROR;
78049   }
78050   db->temp_store = (u8)ts;
78051   return SQLITE_OK;
78052 }
78053 #endif /* SQLITE_PAGER_PRAGMAS */
78054
78055 /*
78056 ** Generate code to return a single integer value.
78057 */
78058 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
78059   Vdbe *v = sqlite3GetVdbe(pParse);
78060   int mem = ++pParse->nMem;
78061   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
78062   if( pI64 ){
78063     memcpy(pI64, &value, sizeof(value));
78064   }
78065   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
78066   sqlite3VdbeSetNumCols(v, 1);
78067   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
78068   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
78069 }
78070
78071 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
78072 /*
78073 ** Check to see if zRight and zLeft refer to a pragma that queries
78074 ** or changes one of the flags in db->flags.  Return 1 if so and 0 if not.
78075 ** Also, implement the pragma.
78076 */
78077 static int flagPragma(Parse *pParse, const char *zLeft, const char *zRight){
78078   static const struct sPragmaType {
78079     const char *zName;  /* Name of the pragma */
78080     int mask;           /* Mask for the db->flags value */
78081   } aPragma[] = {
78082     { "full_column_names",        SQLITE_FullColNames  },
78083     { "short_column_names",       SQLITE_ShortColNames },
78084     { "count_changes",            SQLITE_CountRows     },
78085     { "empty_result_callbacks",   SQLITE_NullCallback  },
78086     { "legacy_file_format",       SQLITE_LegacyFileFmt },
78087     { "fullfsync",                SQLITE_FullFSync     },
78088     { "reverse_unordered_selects", SQLITE_ReverseOrder  },
78089 #ifdef SQLITE_DEBUG
78090     { "sql_trace",                SQLITE_SqlTrace      },
78091     { "vdbe_listing",             SQLITE_VdbeListing   },
78092     { "vdbe_trace",               SQLITE_VdbeTrace     },
78093 #endif
78094 #ifndef SQLITE_OMIT_CHECK
78095     { "ignore_check_constraints", SQLITE_IgnoreChecks  },
78096 #endif
78097     /* The following is VERY experimental */
78098     { "writable_schema",          SQLITE_WriteSchema|SQLITE_RecoveryMode },
78099     { "omit_readlock",            SQLITE_NoReadlock    },
78100
78101     /* TODO: Maybe it shouldn't be possible to change the ReadUncommitted
78102     ** flag if there are any active statements. */
78103     { "read_uncommitted",         SQLITE_ReadUncommitted },
78104     { "recursive_triggers",       SQLITE_RecTriggers },
78105
78106     /* This flag may only be set if both foreign-key and trigger support
78107     ** are present in the build.  */
78108 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
78109     { "foreign_keys",             SQLITE_ForeignKeys },
78110 #endif
78111   };
78112   int i;
78113   const struct sPragmaType *p;
78114   for(i=0, p=aPragma; i<ArraySize(aPragma); i++, p++){
78115     if( sqlite3StrICmp(zLeft, p->zName)==0 ){
78116       sqlite3 *db = pParse->db;
78117       Vdbe *v;
78118       v = sqlite3GetVdbe(pParse);
78119       assert( v!=0 );  /* Already allocated by sqlite3Pragma() */
78120       if( ALWAYS(v) ){
78121         if( zRight==0 ){
78122           returnSingleInt(pParse, p->zName, (db->flags & p->mask)!=0 );
78123         }else{
78124           int mask = p->mask;          /* Mask of bits to set or clear. */
78125           if( db->autoCommit==0 ){
78126             /* Foreign key support may not be enabled or disabled while not
78127             ** in auto-commit mode.  */
78128             mask &= ~(SQLITE_ForeignKeys);
78129           }
78130
78131           if( getBoolean(zRight) ){
78132             db->flags |= mask;
78133           }else{
78134             db->flags &= ~mask;
78135           }
78136
78137           /* Many of the flag-pragmas modify the code generated by the SQL 
78138           ** compiler (eg. count_changes). So add an opcode to expire all
78139           ** compiled SQL statements after modifying a pragma value.
78140           */
78141           sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
78142         }
78143       }
78144
78145       return 1;
78146     }
78147   }
78148   return 0;
78149 }
78150 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
78151
78152 /*
78153 ** Return a human-readable name for a constraint resolution action.
78154 */
78155 #ifndef SQLITE_OMIT_FOREIGN_KEY
78156 static const char *actionName(u8 action){
78157   const char *zName;
78158   switch( action ){
78159     case OE_SetNull:  zName = "SET NULL";        break;
78160     case OE_SetDflt:  zName = "SET DEFAULT";     break;
78161     case OE_Cascade:  zName = "CASCADE";         break;
78162     case OE_Restrict: zName = "RESTRICT";        break;
78163     default:          zName = "NO ACTION";  
78164                       assert( action==OE_None ); break;
78165   }
78166   return zName;
78167 }
78168 #endif
78169
78170 /*
78171 ** Process a pragma statement.  
78172 **
78173 ** Pragmas are of this form:
78174 **
78175 **      PRAGMA [database.]id [= value]
78176 **
78177 ** The identifier might also be a string.  The value is a string, and
78178 ** identifier, or a number.  If minusFlag is true, then the value is
78179 ** a number that was preceded by a minus sign.
78180 **
78181 ** If the left side is "database.id" then pId1 is the database name
78182 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
78183 ** id and pId2 is any empty string.
78184 */
78185 SQLITE_PRIVATE void sqlite3Pragma(
78186   Parse *pParse, 
78187   Token *pId1,        /* First part of [database.]id field */
78188   Token *pId2,        /* Second part of [database.]id field, or NULL */
78189   Token *pValue,      /* Token for <value>, or NULL */
78190   int minusFlag       /* True if a '-' sign preceded <value> */
78191 ){
78192   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
78193   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
78194   const char *zDb = 0;   /* The database name */
78195   Token *pId;            /* Pointer to <id> token */
78196   int iDb;               /* Database index for <database> */
78197   sqlite3 *db = pParse->db;
78198   Db *pDb;
78199   Vdbe *v = pParse->pVdbe = sqlite3VdbeCreate(db);
78200   if( v==0 ) return;
78201   sqlite3VdbeRunOnlyOnce(v);
78202   pParse->nMem = 2;
78203
78204   /* Interpret the [database.] part of the pragma statement. iDb is the
78205   ** index of the database this pragma is being applied to in db.aDb[]. */
78206   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
78207   if( iDb<0 ) return;
78208   pDb = &db->aDb[iDb];
78209
78210   /* If the temp database has been explicitly named as part of the 
78211   ** pragma, make sure it is open. 
78212   */
78213   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
78214     return;
78215   }
78216
78217   zLeft = sqlite3NameFromToken(db, pId);
78218   if( !zLeft ) return;
78219   if( minusFlag ){
78220     zRight = sqlite3MPrintf(db, "-%T", pValue);
78221   }else{
78222     zRight = sqlite3NameFromToken(db, pValue);
78223   }
78224
78225   assert( pId2 );
78226   zDb = pId2->n>0 ? pDb->zName : 0;
78227   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
78228     goto pragma_out;
78229   }
78230  
78231 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
78232   /*
78233   **  PRAGMA [database.]default_cache_size
78234   **  PRAGMA [database.]default_cache_size=N
78235   **
78236   ** The first form reports the current persistent setting for the
78237   ** page cache size.  The value returned is the maximum number of
78238   ** pages in the page cache.  The second form sets both the current
78239   ** page cache size value and the persistent page cache size value
78240   ** stored in the database file.
78241   **
78242   ** The default cache size is stored in meta-value 2 of page 1 of the
78243   ** database file.  The cache size is actually the absolute value of
78244   ** this memory location.  The sign of meta-value 2 determines the
78245   ** synchronous setting.  A negative value means synchronous is off
78246   ** and a positive value means synchronous is on.
78247   */
78248   if( sqlite3StrICmp(zLeft,"default_cache_size")==0 ){
78249     static const VdbeOpList getCacheSize[] = {
78250       { OP_Transaction, 0, 0,        0},                         /* 0 */
78251       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
78252       { OP_IfPos,       1, 7,        0},
78253       { OP_Integer,     0, 2,        0},
78254       { OP_Subtract,    1, 2,        1},
78255       { OP_IfPos,       1, 7,        0},
78256       { OP_Integer,     0, 1,        0},                         /* 6 */
78257       { OP_ResultRow,   1, 1,        0},
78258     };
78259     int addr;
78260     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
78261     sqlite3VdbeUsesBtree(v, iDb);
78262     if( !zRight ){
78263       sqlite3VdbeSetNumCols(v, 1);
78264       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
78265       pParse->nMem += 2;
78266       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize);
78267       sqlite3VdbeChangeP1(v, addr, iDb);
78268       sqlite3VdbeChangeP1(v, addr+1, iDb);
78269       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
78270     }else{
78271       int size = atoi(zRight);
78272       if( size<0 ) size = -size;
78273       sqlite3BeginWriteOperation(pParse, 0, iDb);
78274       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
78275       sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, 2, BTREE_DEFAULT_CACHE_SIZE);
78276       addr = sqlite3VdbeAddOp2(v, OP_IfPos, 2, 0);
78277       sqlite3VdbeAddOp2(v, OP_Integer, -size, 1);
78278       sqlite3VdbeJumpHere(v, addr);
78279       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
78280       pDb->pSchema->cache_size = size;
78281       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
78282     }
78283   }else
78284
78285   /*
78286   **  PRAGMA [database.]page_size
78287   **  PRAGMA [database.]page_size=N
78288   **
78289   ** The first form reports the current setting for the
78290   ** database page size in bytes.  The second form sets the
78291   ** database page size value.  The value can only be set if
78292   ** the database has not yet been created.
78293   */
78294   if( sqlite3StrICmp(zLeft,"page_size")==0 ){
78295     Btree *pBt = pDb->pBt;
78296     assert( pBt!=0 );
78297     if( !zRight ){
78298       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
78299       returnSingleInt(pParse, "page_size", size);
78300     }else{
78301       /* Malloc may fail when setting the page-size, as there is an internal
78302       ** buffer that the pager module resizes using sqlite3_realloc().
78303       */
78304       db->nextPagesize = atoi(zRight);
78305       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
78306         db->mallocFailed = 1;
78307       }
78308     }
78309   }else
78310
78311   /*
78312   **  PRAGMA [database.]max_page_count
78313   **  PRAGMA [database.]max_page_count=N
78314   **
78315   ** The first form reports the current setting for the
78316   ** maximum number of pages in the database file.  The 
78317   ** second form attempts to change this setting.  Both
78318   ** forms return the current setting.
78319   */
78320   if( sqlite3StrICmp(zLeft,"max_page_count")==0 ){
78321     Btree *pBt = pDb->pBt;
78322     int newMax = 0;
78323     assert( pBt!=0 );
78324     if( zRight ){
78325       newMax = atoi(zRight);
78326     }
78327     if( ALWAYS(pBt) ){
78328       newMax = sqlite3BtreeMaxPageCount(pBt, newMax);
78329     }
78330     returnSingleInt(pParse, "max_page_count", newMax);
78331   }else
78332
78333   /*
78334   **  PRAGMA [database.]secure_delete
78335   **  PRAGMA [database.]secure_delete=ON/OFF
78336   **
78337   ** The first form reports the current setting for the
78338   ** secure_delete flag.  The second form changes the secure_delete
78339   ** flag setting and reports thenew value.
78340   */
78341   if( sqlite3StrICmp(zLeft,"secure_delete")==0 ){
78342     Btree *pBt = pDb->pBt;
78343     int b = -1;
78344     assert( pBt!=0 );
78345     if( zRight ){
78346       b = getBoolean(zRight);
78347     }
78348     if( pId2->n==0 && b>=0 ){
78349       int ii;
78350       for(ii=0; ii<db->nDb; ii++){
78351         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
78352       }
78353     }
78354     b = sqlite3BtreeSecureDelete(pBt, b);
78355     returnSingleInt(pParse, "secure_delete", b);
78356   }else
78357
78358   /*
78359   **  PRAGMA [database.]page_count
78360   **
78361   ** Return the number of pages in the specified database.
78362   */
78363   if( sqlite3StrICmp(zLeft,"page_count")==0 ){
78364     int iReg;
78365     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
78366     sqlite3CodeVerifySchema(pParse, iDb);
78367     iReg = ++pParse->nMem;
78368     sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
78369     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
78370     sqlite3VdbeSetNumCols(v, 1);
78371     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "page_count", SQLITE_STATIC);
78372   }else
78373
78374   /*
78375   **  PRAGMA [database.]locking_mode
78376   **  PRAGMA [database.]locking_mode = (normal|exclusive)
78377   */
78378   if( sqlite3StrICmp(zLeft,"locking_mode")==0 ){
78379     const char *zRet = "normal";
78380     int eMode = getLockingMode(zRight);
78381
78382     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
78383       /* Simple "PRAGMA locking_mode;" statement. This is a query for
78384       ** the current default locking mode (which may be different to
78385       ** the locking-mode of the main database).
78386       */
78387       eMode = db->dfltLockMode;
78388     }else{
78389       Pager *pPager;
78390       if( pId2->n==0 ){
78391         /* This indicates that no database name was specified as part
78392         ** of the PRAGMA command. In this case the locking-mode must be
78393         ** set on all attached databases, as well as the main db file.
78394         **
78395         ** Also, the sqlite3.dfltLockMode variable is set so that
78396         ** any subsequently attached databases also use the specified
78397         ** locking mode.
78398         */
78399         int ii;
78400         assert(pDb==&db->aDb[0]);
78401         for(ii=2; ii<db->nDb; ii++){
78402           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
78403           sqlite3PagerLockingMode(pPager, eMode);
78404         }
78405         db->dfltLockMode = (u8)eMode;
78406       }
78407       pPager = sqlite3BtreePager(pDb->pBt);
78408       eMode = sqlite3PagerLockingMode(pPager, eMode);
78409     }
78410
78411     assert(eMode==PAGER_LOCKINGMODE_NORMAL||eMode==PAGER_LOCKINGMODE_EXCLUSIVE);
78412     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
78413       zRet = "exclusive";
78414     }
78415     sqlite3VdbeSetNumCols(v, 1);
78416     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
78417     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
78418     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
78419   }else
78420
78421   /*
78422   **  PRAGMA [database.]journal_mode
78423   **  PRAGMA [database.]journal_mode = (delete|persist|off|truncate|memory)
78424   */
78425   if( sqlite3StrICmp(zLeft,"journal_mode")==0 ){
78426     int eMode;
78427     static char * const azModeName[] = {
78428       "delete", "persist", "off", "truncate", "memory"
78429     };
78430
78431     if( zRight==0 ){
78432       eMode = PAGER_JOURNALMODE_QUERY;
78433     }else{
78434       int n = sqlite3Strlen30(zRight);
78435       eMode = sizeof(azModeName)/sizeof(azModeName[0]) - 1;
78436       while( eMode>=0 && sqlite3StrNICmp(zRight, azModeName[eMode], n)!=0 ){
78437         eMode--;
78438       }
78439     }
78440     if( pId2->n==0 && eMode==PAGER_JOURNALMODE_QUERY ){
78441       /* Simple "PRAGMA journal_mode;" statement. This is a query for
78442       ** the current default journal mode (which may be different to
78443       ** the journal-mode of the main database).
78444       */
78445       eMode = db->dfltJournalMode;
78446     }else{
78447       Pager *pPager;
78448       if( pId2->n==0 ){
78449         /* This indicates that no database name was specified as part
78450         ** of the PRAGMA command. In this case the journal-mode must be
78451         ** set on all attached databases, as well as the main db file.
78452         **
78453         ** Also, the sqlite3.dfltJournalMode variable is set so that
78454         ** any subsequently attached databases also use the specified
78455         ** journal mode.
78456         */
78457         int ii;
78458         assert(pDb==&db->aDb[0]);
78459         for(ii=1; ii<db->nDb; ii++){
78460           if( db->aDb[ii].pBt ){
78461             pPager = sqlite3BtreePager(db->aDb[ii].pBt);
78462             sqlite3PagerJournalMode(pPager, eMode);
78463           }
78464         }
78465         db->dfltJournalMode = (u8)eMode;
78466       }
78467       pPager = sqlite3BtreePager(pDb->pBt);
78468       eMode = sqlite3PagerJournalMode(pPager, eMode);
78469     }
78470     assert( eMode==PAGER_JOURNALMODE_DELETE
78471               || eMode==PAGER_JOURNALMODE_TRUNCATE
78472               || eMode==PAGER_JOURNALMODE_PERSIST
78473               || eMode==PAGER_JOURNALMODE_OFF
78474               || eMode==PAGER_JOURNALMODE_MEMORY );
78475     sqlite3VdbeSetNumCols(v, 1);
78476     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
78477     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, 
78478            azModeName[eMode], P4_STATIC);
78479     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
78480   }else
78481
78482   /*
78483   **  PRAGMA [database.]journal_size_limit
78484   **  PRAGMA [database.]journal_size_limit=N
78485   **
78486   ** Get or set the size limit on rollback journal files.
78487   */
78488   if( sqlite3StrICmp(zLeft,"journal_size_limit")==0 ){
78489     Pager *pPager = sqlite3BtreePager(pDb->pBt);
78490     i64 iLimit = -2;
78491     if( zRight ){
78492       sqlite3Atoi64(zRight, &iLimit);
78493       if( iLimit<-1 ) iLimit = -1;
78494     }
78495     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
78496     returnSingleInt(pParse, "journal_size_limit", iLimit);
78497   }else
78498
78499 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
78500
78501   /*
78502   **  PRAGMA [database.]auto_vacuum
78503   **  PRAGMA [database.]auto_vacuum=N
78504   **
78505   ** Get or set the value of the database 'auto-vacuum' parameter.
78506   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
78507   */
78508 #ifndef SQLITE_OMIT_AUTOVACUUM
78509   if( sqlite3StrICmp(zLeft,"auto_vacuum")==0 ){
78510     Btree *pBt = pDb->pBt;
78511     assert( pBt!=0 );
78512     if( sqlite3ReadSchema(pParse) ){
78513       goto pragma_out;
78514     }
78515     if( !zRight ){
78516       int auto_vacuum;
78517       if( ALWAYS(pBt) ){
78518          auto_vacuum = sqlite3BtreeGetAutoVacuum(pBt);
78519       }else{
78520          auto_vacuum = SQLITE_DEFAULT_AUTOVACUUM;
78521       }
78522       returnSingleInt(pParse, "auto_vacuum", auto_vacuum);
78523     }else{
78524       int eAuto = getAutoVacuum(zRight);
78525       assert( eAuto>=0 && eAuto<=2 );
78526       db->nextAutovac = (u8)eAuto;
78527       if( ALWAYS(eAuto>=0) ){
78528         /* Call SetAutoVacuum() to set initialize the internal auto and
78529         ** incr-vacuum flags. This is required in case this connection
78530         ** creates the database file. It is important that it is created
78531         ** as an auto-vacuum capable db.
78532         */
78533         int rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
78534         if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
78535           /* When setting the auto_vacuum mode to either "full" or 
78536           ** "incremental", write the value of meta[6] in the database
78537           ** file. Before writing to meta[6], check that meta[3] indicates
78538           ** that this really is an auto-vacuum capable database.
78539           */
78540           static const VdbeOpList setMeta6[] = {
78541             { OP_Transaction,    0,         1,                 0},    /* 0 */
78542             { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
78543             { OP_If,             1,         0,                 0},    /* 2 */
78544             { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
78545             { OP_Integer,        0,         1,                 0},    /* 4 */
78546             { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
78547           };
78548           int iAddr;
78549           iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6);
78550           sqlite3VdbeChangeP1(v, iAddr, iDb);
78551           sqlite3VdbeChangeP1(v, iAddr+1, iDb);
78552           sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
78553           sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
78554           sqlite3VdbeChangeP1(v, iAddr+5, iDb);
78555           sqlite3VdbeUsesBtree(v, iDb);
78556         }
78557       }
78558     }
78559   }else
78560 #endif
78561
78562   /*
78563   **  PRAGMA [database.]incremental_vacuum(N)
78564   **
78565   ** Do N steps of incremental vacuuming on a database.
78566   */
78567 #ifndef SQLITE_OMIT_AUTOVACUUM
78568   if( sqlite3StrICmp(zLeft,"incremental_vacuum")==0 ){
78569     int iLimit, addr;
78570     if( sqlite3ReadSchema(pParse) ){
78571       goto pragma_out;
78572     }
78573     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
78574       iLimit = 0x7fffffff;
78575     }
78576     sqlite3BeginWriteOperation(pParse, 0, iDb);
78577     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
78578     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb);
78579     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
78580     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
78581     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr);
78582     sqlite3VdbeJumpHere(v, addr);
78583   }else
78584 #endif
78585
78586 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
78587   /*
78588   **  PRAGMA [database.]cache_size
78589   **  PRAGMA [database.]cache_size=N
78590   **
78591   ** The first form reports the current local setting for the
78592   ** page cache size.  The local setting can be different from
78593   ** the persistent cache size value that is stored in the database
78594   ** file itself.  The value returned is the maximum number of
78595   ** pages in the page cache.  The second form sets the local
78596   ** page cache size value.  It does not change the persistent
78597   ** cache size stored on the disk so the cache size will revert
78598   ** to its default value when the database is closed and reopened.
78599   ** N should be a positive integer.
78600   */
78601   if( sqlite3StrICmp(zLeft,"cache_size")==0 ){
78602     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
78603     if( !zRight ){
78604       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
78605     }else{
78606       int size = atoi(zRight);
78607       if( size<0 ) size = -size;
78608       pDb->pSchema->cache_size = size;
78609       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
78610     }
78611   }else
78612
78613   /*
78614   **   PRAGMA temp_store
78615   **   PRAGMA temp_store = "default"|"memory"|"file"
78616   **
78617   ** Return or set the local value of the temp_store flag.  Changing
78618   ** the local value does not make changes to the disk file and the default
78619   ** value will be restored the next time the database is opened.
78620   **
78621   ** Note that it is possible for the library compile-time options to
78622   ** override this setting
78623   */
78624   if( sqlite3StrICmp(zLeft, "temp_store")==0 ){
78625     if( !zRight ){
78626       returnSingleInt(pParse, "temp_store", db->temp_store);
78627     }else{
78628       changeTempStorage(pParse, zRight);
78629     }
78630   }else
78631
78632   /*
78633   **   PRAGMA temp_store_directory
78634   **   PRAGMA temp_store_directory = ""|"directory_name"
78635   **
78636   ** Return or set the local value of the temp_store_directory flag.  Changing
78637   ** the value sets a specific directory to be used for temporary files.
78638   ** Setting to a null string reverts to the default temporary directory search.
78639   ** If temporary directory is changed, then invalidateTempStorage.
78640   **
78641   */
78642   if( sqlite3StrICmp(zLeft, "temp_store_directory")==0 ){
78643     if( !zRight ){
78644       if( sqlite3_temp_directory ){
78645         sqlite3VdbeSetNumCols(v, 1);
78646         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
78647             "temp_store_directory", SQLITE_STATIC);
78648         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
78649         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
78650       }
78651     }else{
78652 #ifndef SQLITE_OMIT_WSD
78653       if( zRight[0] ){
78654         int rc;
78655         int res;
78656         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
78657         if( rc!=SQLITE_OK || res==0 ){
78658           sqlite3ErrorMsg(pParse, "not a writable directory");
78659           goto pragma_out;
78660         }
78661       }
78662       if( SQLITE_TEMP_STORE==0
78663        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
78664        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
78665       ){
78666         invalidateTempStorage(pParse);
78667       }
78668       sqlite3_free(sqlite3_temp_directory);
78669       if( zRight[0] ){
78670         sqlite3_temp_directory = sqlite3DbStrDup(0, zRight);
78671       }else{
78672         sqlite3_temp_directory = 0;
78673       }
78674 #endif /* SQLITE_OMIT_WSD */
78675     }
78676   }else
78677
78678 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
78679 #  if defined(__APPLE__)
78680 #    define SQLITE_ENABLE_LOCKING_STYLE 1
78681 #  else
78682 #    define SQLITE_ENABLE_LOCKING_STYLE 0
78683 #  endif
78684 #endif
78685 #if SQLITE_ENABLE_LOCKING_STYLE
78686   /*
78687    **   PRAGMA [database.]lock_proxy_file
78688    **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
78689    **
78690    ** Return or set the value of the lock_proxy_file flag.  Changing
78691    ** the value sets a specific file to be used for database access locks.
78692    **
78693    */
78694   if( sqlite3StrICmp(zLeft, "lock_proxy_file")==0 ){
78695     if( !zRight ){
78696       Pager *pPager = sqlite3BtreePager(pDb->pBt);
78697       char *proxy_file_path = NULL;
78698       sqlite3_file *pFile = sqlite3PagerFile(pPager);
78699       sqlite3OsFileControl(pFile, SQLITE_GET_LOCKPROXYFILE, 
78700                            &proxy_file_path);
78701       
78702       if( proxy_file_path ){
78703         sqlite3VdbeSetNumCols(v, 1);
78704         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
78705                               "lock_proxy_file", SQLITE_STATIC);
78706         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
78707         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
78708       }
78709     }else{
78710       Pager *pPager = sqlite3BtreePager(pDb->pBt);
78711       sqlite3_file *pFile = sqlite3PagerFile(pPager);
78712       int res;
78713       if( zRight[0] ){
78714         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
78715                                      zRight);
78716       } else {
78717         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
78718                                      NULL);
78719       }
78720       if( res!=SQLITE_OK ){
78721         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
78722         goto pragma_out;
78723       }
78724     }
78725   }else
78726 #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
78727     
78728   /*
78729   **   PRAGMA [database.]synchronous
78730   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
78731   **
78732   ** Return or set the local value of the synchronous flag.  Changing
78733   ** the local value does not make changes to the disk file and the
78734   ** default value will be restored the next time the database is
78735   ** opened.
78736   */
78737   if( sqlite3StrICmp(zLeft,"synchronous")==0 ){
78738     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
78739     if( !zRight ){
78740       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
78741     }else{
78742       if( !db->autoCommit ){
78743         sqlite3ErrorMsg(pParse, 
78744             "Safety level may not be changed inside a transaction");
78745       }else{
78746         pDb->safety_level = getSafetyLevel(zRight)+1;
78747       }
78748     }
78749   }else
78750 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
78751
78752 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
78753   if( flagPragma(pParse, zLeft, zRight) ){
78754     /* The flagPragma() subroutine also generates any necessary code
78755     ** there is nothing more to do here */
78756   }else
78757 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
78758
78759 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
78760   /*
78761   **   PRAGMA table_info(<table>)
78762   **
78763   ** Return a single row for each column of the named table. The columns of
78764   ** the returned data set are:
78765   **
78766   ** cid:        Column id (numbered from left to right, starting at 0)
78767   ** name:       Column name
78768   ** type:       Column declaration type.
78769   ** notnull:    True if 'NOT NULL' is part of column declaration
78770   ** dflt_value: The default value for the column, if any.
78771   */
78772   if( sqlite3StrICmp(zLeft, "table_info")==0 && zRight ){
78773     Table *pTab;
78774     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
78775     pTab = sqlite3FindTable(db, zRight, zDb);
78776     if( pTab ){
78777       int i;
78778       int nHidden = 0;
78779       Column *pCol;
78780       sqlite3VdbeSetNumCols(v, 6);
78781       pParse->nMem = 6;
78782       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
78783       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
78784       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
78785       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
78786       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
78787       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
78788       sqlite3ViewGetColumnNames(pParse, pTab);
78789       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
78790         if( IsHiddenColumn(pCol) ){
78791           nHidden++;
78792           continue;
78793         }
78794         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
78795         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
78796         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
78797            pCol->zType ? pCol->zType : "", 0);
78798         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
78799         if( pCol->zDflt ){
78800           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
78801         }else{
78802           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
78803         }
78804         sqlite3VdbeAddOp2(v, OP_Integer, pCol->isPrimKey, 6);
78805         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
78806       }
78807     }
78808   }else
78809
78810   if( sqlite3StrICmp(zLeft, "index_info")==0 && zRight ){
78811     Index *pIdx;
78812     Table *pTab;
78813     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
78814     pIdx = sqlite3FindIndex(db, zRight, zDb);
78815     if( pIdx ){
78816       int i;
78817       pTab = pIdx->pTable;
78818       sqlite3VdbeSetNumCols(v, 3);
78819       pParse->nMem = 3;
78820       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
78821       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
78822       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
78823       for(i=0; i<pIdx->nColumn; i++){
78824         int cnum = pIdx->aiColumn[i];
78825         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
78826         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
78827         assert( pTab->nCol>cnum );
78828         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
78829         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
78830       }
78831     }
78832   }else
78833
78834   if( sqlite3StrICmp(zLeft, "index_list")==0 && zRight ){
78835     Index *pIdx;
78836     Table *pTab;
78837     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
78838     pTab = sqlite3FindTable(db, zRight, zDb);
78839     if( pTab ){
78840       v = sqlite3GetVdbe(pParse);
78841       pIdx = pTab->pIndex;
78842       if( pIdx ){
78843         int i = 0; 
78844         sqlite3VdbeSetNumCols(v, 3);
78845         pParse->nMem = 3;
78846         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
78847         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
78848         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
78849         while(pIdx){
78850           sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
78851           sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
78852           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->onError!=OE_None, 3);
78853           sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
78854           ++i;
78855           pIdx = pIdx->pNext;
78856         }
78857       }
78858     }
78859   }else
78860
78861   if( sqlite3StrICmp(zLeft, "database_list")==0 ){
78862     int i;
78863     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
78864     sqlite3VdbeSetNumCols(v, 3);
78865     pParse->nMem = 3;
78866     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
78867     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
78868     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
78869     for(i=0; i<db->nDb; i++){
78870       if( db->aDb[i].pBt==0 ) continue;
78871       assert( db->aDb[i].zName!=0 );
78872       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
78873       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
78874       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
78875            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
78876       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
78877     }
78878   }else
78879
78880   if( sqlite3StrICmp(zLeft, "collation_list")==0 ){
78881     int i = 0;
78882     HashElem *p;
78883     sqlite3VdbeSetNumCols(v, 2);
78884     pParse->nMem = 2;
78885     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
78886     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
78887     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
78888       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
78889       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
78890       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
78891       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
78892     }
78893   }else
78894 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
78895
78896 #ifndef SQLITE_OMIT_FOREIGN_KEY
78897   if( sqlite3StrICmp(zLeft, "foreign_key_list")==0 && zRight ){
78898     FKey *pFK;
78899     Table *pTab;
78900     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
78901     pTab = sqlite3FindTable(db, zRight, zDb);
78902     if( pTab ){
78903       v = sqlite3GetVdbe(pParse);
78904       pFK = pTab->pFKey;
78905       if( pFK ){
78906         int i = 0; 
78907         sqlite3VdbeSetNumCols(v, 8);
78908         pParse->nMem = 8;
78909         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
78910         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
78911         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
78912         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
78913         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
78914         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
78915         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
78916         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
78917         while(pFK){
78918           int j;
78919           for(j=0; j<pFK->nCol; j++){
78920             char *zCol = pFK->aCol[j].zCol;
78921             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
78922             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
78923             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
78924             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
78925             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
78926             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
78927                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
78928             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
78929             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
78930             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
78931             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
78932             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
78933           }
78934           ++i;
78935           pFK = pFK->pNextFrom;
78936         }
78937       }
78938     }
78939   }else
78940 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
78941
78942 #ifndef NDEBUG
78943   if( sqlite3StrICmp(zLeft, "parser_trace")==0 ){
78944     if( zRight ){
78945       if( getBoolean(zRight) ){
78946         sqlite3ParserTrace(stderr, "parser: ");
78947       }else{
78948         sqlite3ParserTrace(0, 0);
78949       }
78950     }
78951   }else
78952 #endif
78953
78954   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
78955   ** used will be case sensitive or not depending on the RHS.
78956   */
78957   if( sqlite3StrICmp(zLeft, "case_sensitive_like")==0 ){
78958     if( zRight ){
78959       sqlite3RegisterLikeFunctions(db, getBoolean(zRight));
78960     }
78961   }else
78962
78963 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
78964 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
78965 #endif
78966
78967 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
78968   /* Pragma "quick_check" is an experimental reduced version of 
78969   ** integrity_check designed to detect most database corruption
78970   ** without most of the overhead of a full integrity-check.
78971   */
78972   if( sqlite3StrICmp(zLeft, "integrity_check")==0
78973    || sqlite3StrICmp(zLeft, "quick_check")==0 
78974   ){
78975     int i, j, addr, mxErr;
78976
78977     /* Code that appears at the end of the integrity check.  If no error
78978     ** messages have been generated, output OK.  Otherwise output the
78979     ** error message
78980     */
78981     static const VdbeOpList endCode[] = {
78982       { OP_AddImm,      1, 0,        0},    /* 0 */
78983       { OP_IfNeg,       1, 0,        0},    /* 1 */
78984       { OP_String8,     0, 3,        0},    /* 2 */
78985       { OP_ResultRow,   3, 1,        0},
78986     };
78987
78988     int isQuick = (zLeft[0]=='q');
78989
78990     /* Initialize the VDBE program */
78991     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
78992     pParse->nMem = 6;
78993     sqlite3VdbeSetNumCols(v, 1);
78994     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
78995
78996     /* Set the maximum error count */
78997     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
78998     if( zRight ){
78999       mxErr = atoi(zRight);
79000       if( mxErr<=0 ){
79001         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
79002       }
79003     }
79004     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
79005
79006     /* Do an integrity check on each database file */
79007     for(i=0; i<db->nDb; i++){
79008       HashElem *x;
79009       Hash *pTbls;
79010       int cnt = 0;
79011
79012       if( OMIT_TEMPDB && i==1 ) continue;
79013
79014       sqlite3CodeVerifySchema(pParse, i);
79015       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
79016       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
79017       sqlite3VdbeJumpHere(v, addr);
79018
79019       /* Do an integrity check of the B-Tree
79020       **
79021       ** Begin by filling registers 2, 3, ... with the root pages numbers
79022       ** for all tables and indices in the database.
79023       */
79024       pTbls = &db->aDb[i].pSchema->tblHash;
79025       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
79026         Table *pTab = sqliteHashData(x);
79027         Index *pIdx;
79028         sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
79029         cnt++;
79030         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
79031           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
79032           cnt++;
79033         }
79034       }
79035
79036       /* Make sure sufficient number of registers have been allocated */
79037       if( pParse->nMem < cnt+4 ){
79038         pParse->nMem = cnt+4;
79039       }
79040
79041       /* Do the b-tree integrity checks */
79042       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
79043       sqlite3VdbeChangeP5(v, (u8)i);
79044       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2);
79045       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
79046          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
79047          P4_DYNAMIC);
79048       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
79049       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
79050       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
79051       sqlite3VdbeJumpHere(v, addr);
79052
79053       /* Make sure all the indices are constructed correctly.
79054       */
79055       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
79056         Table *pTab = sqliteHashData(x);
79057         Index *pIdx;
79058         int loopTop;
79059
79060         if( pTab->pIndex==0 ) continue;
79061         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
79062         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
79063         sqlite3VdbeJumpHere(v, addr);
79064         sqlite3OpenTableAndIndices(pParse, pTab, 1, OP_OpenRead);
79065         sqlite3VdbeAddOp2(v, OP_Integer, 0, 2);  /* reg(2) will count entries */
79066         loopTop = sqlite3VdbeAddOp2(v, OP_Rewind, 1, 0);
79067         sqlite3VdbeAddOp2(v, OP_AddImm, 2, 1);   /* increment entry count */
79068         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
79069           int jmp2;
79070           int r1;
79071           static const VdbeOpList idxErr[] = {
79072             { OP_AddImm,      1, -1,  0},
79073             { OP_String8,     0,  3,  0},    /* 1 */
79074             { OP_Rowid,       1,  4,  0},
79075             { OP_String8,     0,  5,  0},    /* 3 */
79076             { OP_String8,     0,  6,  0},    /* 4 */
79077             { OP_Concat,      4,  3,  3},
79078             { OP_Concat,      5,  3,  3},
79079             { OP_Concat,      6,  3,  3},
79080             { OP_ResultRow,   3,  1,  0},
79081             { OP_IfPos,       1,  0,  0},    /* 9 */
79082             { OP_Halt,        0,  0,  0},
79083           };
79084           r1 = sqlite3GenerateIndexKey(pParse, pIdx, 1, 3, 0);
79085           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, j+2, 0, r1, pIdx->nColumn+1);
79086           addr = sqlite3VdbeAddOpList(v, ArraySize(idxErr), idxErr);
79087           sqlite3VdbeChangeP4(v, addr+1, "rowid ", P4_STATIC);
79088           sqlite3VdbeChangeP4(v, addr+3, " missing from index ", P4_STATIC);
79089           sqlite3VdbeChangeP4(v, addr+4, pIdx->zName, P4_STATIC);
79090           sqlite3VdbeJumpHere(v, addr+9);
79091           sqlite3VdbeJumpHere(v, jmp2);
79092         }
79093         sqlite3VdbeAddOp2(v, OP_Next, 1, loopTop+1);
79094         sqlite3VdbeJumpHere(v, loopTop);
79095         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
79096           static const VdbeOpList cntIdx[] = {
79097              { OP_Integer,      0,  3,  0},
79098              { OP_Rewind,       0,  0,  0},  /* 1 */
79099              { OP_AddImm,       3,  1,  0},
79100              { OP_Next,         0,  0,  0},  /* 3 */
79101              { OP_Eq,           2,  0,  3},  /* 4 */
79102              { OP_AddImm,       1, -1,  0},
79103              { OP_String8,      0,  2,  0},  /* 6 */
79104              { OP_String8,      0,  3,  0},  /* 7 */
79105              { OP_Concat,       3,  2,  2},
79106              { OP_ResultRow,    2,  1,  0},
79107           };
79108           addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);
79109           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
79110           sqlite3VdbeJumpHere(v, addr);
79111           addr = sqlite3VdbeAddOpList(v, ArraySize(cntIdx), cntIdx);
79112           sqlite3VdbeChangeP1(v, addr+1, j+2);
79113           sqlite3VdbeChangeP2(v, addr+1, addr+4);
79114           sqlite3VdbeChangeP1(v, addr+3, j+2);
79115           sqlite3VdbeChangeP2(v, addr+3, addr+2);
79116           sqlite3VdbeJumpHere(v, addr+4);
79117           sqlite3VdbeChangeP4(v, addr+6, 
79118                      "wrong # of entries in index ", P4_STATIC);
79119           sqlite3VdbeChangeP4(v, addr+7, pIdx->zName, P4_STATIC);
79120         }
79121       } 
79122     }
79123     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode);
79124     sqlite3VdbeChangeP2(v, addr, -mxErr);
79125     sqlite3VdbeJumpHere(v, addr+1);
79126     sqlite3VdbeChangeP4(v, addr+2, "ok", P4_STATIC);
79127   }else
79128 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
79129
79130 #ifndef SQLITE_OMIT_UTF16
79131   /*
79132   **   PRAGMA encoding
79133   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
79134   **
79135   ** In its first form, this pragma returns the encoding of the main
79136   ** database. If the database is not initialized, it is initialized now.
79137   **
79138   ** The second form of this pragma is a no-op if the main database file
79139   ** has not already been initialized. In this case it sets the default
79140   ** encoding that will be used for the main database file if a new file
79141   ** is created. If an existing main database file is opened, then the
79142   ** default text encoding for the existing database is used.
79143   ** 
79144   ** In all cases new databases created using the ATTACH command are
79145   ** created to use the same default text encoding as the main database. If
79146   ** the main database has not been initialized and/or created when ATTACH
79147   ** is executed, this is done before the ATTACH operation.
79148   **
79149   ** In the second form this pragma sets the text encoding to be used in
79150   ** new database files created using this database handle. It is only
79151   ** useful if invoked immediately after the main database i
79152   */
79153   if( sqlite3StrICmp(zLeft, "encoding")==0 ){
79154     static const struct EncName {
79155       char *zName;
79156       u8 enc;
79157     } encnames[] = {
79158       { "UTF8",     SQLITE_UTF8        },
79159       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
79160       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
79161       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
79162       { "UTF16le",  SQLITE_UTF16LE     },
79163       { "UTF16be",  SQLITE_UTF16BE     },
79164       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
79165       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
79166       { 0, 0 }
79167     };
79168     const struct EncName *pEnc;
79169     if( !zRight ){    /* "PRAGMA encoding" */
79170       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
79171       sqlite3VdbeSetNumCols(v, 1);
79172       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
79173       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
79174       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
79175       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
79176       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
79177       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
79178       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
79179     }else{                        /* "PRAGMA encoding = XXX" */
79180       /* Only change the value of sqlite.enc if the database handle is not
79181       ** initialized. If the main database exists, the new sqlite.enc value
79182       ** will be overwritten when the schema is next loaded. If it does not
79183       ** already exists, it will be created to use the new encoding value.
79184       */
79185       if( 
79186         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
79187         DbHasProperty(db, 0, DB_Empty) 
79188       ){
79189         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
79190           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
79191             ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
79192             break;
79193           }
79194         }
79195         if( !pEnc->zName ){
79196           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
79197         }
79198       }
79199     }
79200   }else
79201 #endif /* SQLITE_OMIT_UTF16 */
79202
79203 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
79204   /*
79205   **   PRAGMA [database.]schema_version
79206   **   PRAGMA [database.]schema_version = <integer>
79207   **
79208   **   PRAGMA [database.]user_version
79209   **   PRAGMA [database.]user_version = <integer>
79210   **
79211   ** The pragma's schema_version and user_version are used to set or get
79212   ** the value of the schema-version and user-version, respectively. Both
79213   ** the schema-version and the user-version are 32-bit signed integers
79214   ** stored in the database header.
79215   **
79216   ** The schema-cookie is usually only manipulated internally by SQLite. It
79217   ** is incremented by SQLite whenever the database schema is modified (by
79218   ** creating or dropping a table or index). The schema version is used by
79219   ** SQLite each time a query is executed to ensure that the internal cache
79220   ** of the schema used when compiling the SQL query matches the schema of
79221   ** the database against which the compiled query is actually executed.
79222   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
79223   ** the schema-version is potentially dangerous and may lead to program
79224   ** crashes or database corruption. Use with caution!
79225   **
79226   ** The user-version is not used internally by SQLite. It may be used by
79227   ** applications for any purpose.
79228   */
79229   if( sqlite3StrICmp(zLeft, "schema_version")==0 
79230    || sqlite3StrICmp(zLeft, "user_version")==0 
79231    || sqlite3StrICmp(zLeft, "freelist_count")==0 
79232   ){
79233     int iCookie;   /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
79234     sqlite3VdbeUsesBtree(v, iDb);
79235     switch( zLeft[0] ){
79236       case 'f': case 'F':
79237         iCookie = BTREE_FREE_PAGE_COUNT;
79238         break;
79239       case 's': case 'S':
79240         iCookie = BTREE_SCHEMA_VERSION;
79241         break;
79242       default:
79243         iCookie = BTREE_USER_VERSION;
79244         break;
79245     }
79246
79247     if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
79248       /* Write the specified cookie value */
79249       static const VdbeOpList setCookie[] = {
79250         { OP_Transaction,    0,  1,  0},    /* 0 */
79251         { OP_Integer,        0,  1,  0},    /* 1 */
79252         { OP_SetCookie,      0,  0,  1},    /* 2 */
79253       };
79254       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie);
79255       sqlite3VdbeChangeP1(v, addr, iDb);
79256       sqlite3VdbeChangeP1(v, addr+1, atoi(zRight));
79257       sqlite3VdbeChangeP1(v, addr+2, iDb);
79258       sqlite3VdbeChangeP2(v, addr+2, iCookie);
79259     }else{
79260       /* Read the specified cookie value */
79261       static const VdbeOpList readCookie[] = {
79262         { OP_Transaction,     0,  0,  0},    /* 0 */
79263         { OP_ReadCookie,      0,  1,  0},    /* 1 */
79264         { OP_ResultRow,       1,  1,  0}
79265       };
79266       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie);
79267       sqlite3VdbeChangeP1(v, addr, iDb);
79268       sqlite3VdbeChangeP1(v, addr+1, iDb);
79269       sqlite3VdbeChangeP3(v, addr+1, iCookie);
79270       sqlite3VdbeSetNumCols(v, 1);
79271       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
79272     }
79273   }else
79274 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
79275
79276 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
79277   /*
79278   **   PRAGMA compile_options
79279   **
79280   ** Return the names of all compile-time options used in this build,
79281   ** one option per row.
79282   */
79283   if( sqlite3StrICmp(zLeft, "compile_options")==0 ){
79284     int i = 0;
79285     const char *zOpt;
79286     sqlite3VdbeSetNumCols(v, 1);
79287     pParse->nMem = 1;
79288     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
79289     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
79290       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
79291       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
79292     }
79293   }else
79294 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
79295
79296 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
79297   /*
79298   ** Report the current state of file logs for all databases
79299   */
79300   if( sqlite3StrICmp(zLeft, "lock_status")==0 ){
79301     static const char *const azLockName[] = {
79302       "unlocked", "shared", "reserved", "pending", "exclusive"
79303     };
79304     int i;
79305     sqlite3VdbeSetNumCols(v, 2);
79306     pParse->nMem = 2;
79307     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
79308     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
79309     for(i=0; i<db->nDb; i++){
79310       Btree *pBt;
79311       Pager *pPager;
79312       const char *zState = "unknown";
79313       int j;
79314       if( db->aDb[i].zName==0 ) continue;
79315       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
79316       pBt = db->aDb[i].pBt;
79317       if( pBt==0 || (pPager = sqlite3BtreePager(pBt))==0 ){
79318         zState = "closed";
79319       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
79320                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
79321          zState = azLockName[j];
79322       }
79323       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
79324       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
79325     }
79326
79327   }else
79328 #endif
79329
79330 #ifdef SQLITE_HAS_CODEC
79331   if( sqlite3StrICmp(zLeft, "key")==0 && zRight ){
79332     sqlite3_key(db, zRight, sqlite3Strlen30(zRight));
79333   }else
79334   if( sqlite3StrICmp(zLeft, "rekey")==0 && zRight ){
79335     sqlite3_rekey(db, zRight, sqlite3Strlen30(zRight));
79336   }else
79337   if( zRight && (sqlite3StrICmp(zLeft, "hexkey")==0 ||
79338                  sqlite3StrICmp(zLeft, "hexrekey")==0) ){
79339     int i, h1, h2;
79340     char zKey[40];
79341     for(i=0; (h1 = zRight[i])!=0 && (h2 = zRight[i+1])!=0; i+=2){
79342       h1 += 9*(1&(h1>>6));
79343       h2 += 9*(1&(h2>>6));
79344       zKey[i/2] = (h2 & 0x0f) | ((h1 & 0xf)<<4);
79345     }
79346     if( (zLeft[3] & 0xf)==0xb ){
79347       sqlite3_key(db, zKey, i/2);
79348     }else{
79349       sqlite3_rekey(db, zKey, i/2);
79350     }
79351   }else
79352 #endif
79353 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
79354   if( sqlite3StrICmp(zLeft, "activate_extensions")==0 ){
79355 #ifdef SQLITE_HAS_CODEC
79356     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
79357       sqlite3_activate_see(&zRight[4]);
79358     }
79359 #endif
79360 #ifdef SQLITE_ENABLE_CEROD
79361     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
79362       sqlite3_activate_cerod(&zRight[6]);
79363     }
79364 #endif
79365   }else
79366 #endif
79367
79368  
79369   {/* Empty ELSE clause */}
79370
79371   /*
79372   ** Reset the safety level, in case the fullfsync flag or synchronous
79373   ** setting changed.
79374   */
79375 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
79376   if( db->autoCommit ){
79377     sqlite3BtreeSetSafetyLevel(pDb->pBt, pDb->safety_level,
79378                (db->flags&SQLITE_FullFSync)!=0);
79379   }
79380 #endif
79381 pragma_out:
79382   sqlite3DbFree(db, zLeft);
79383   sqlite3DbFree(db, zRight);
79384 }
79385
79386 #endif /* SQLITE_OMIT_PRAGMA */
79387
79388 /************** End of pragma.c **********************************************/
79389 /************** Begin file prepare.c *****************************************/
79390 /*
79391 ** 2005 May 25
79392 **
79393 ** The author disclaims copyright to this source code.  In place of
79394 ** a legal notice, here is a blessing:
79395 **
79396 **    May you do good and not evil.
79397 **    May you find forgiveness for yourself and forgive others.
79398 **    May you share freely, never taking more than you give.
79399 **
79400 *************************************************************************
79401 ** This file contains the implementation of the sqlite3_prepare()
79402 ** interface, and routines that contribute to loading the database schema
79403 ** from disk.
79404 */
79405
79406 /*
79407 ** Fill the InitData structure with an error message that indicates
79408 ** that the database is corrupt.
79409 */
79410 static void corruptSchema(
79411   InitData *pData,     /* Initialization context */
79412   const char *zObj,    /* Object being parsed at the point of error */
79413   const char *zExtra   /* Error information */
79414 ){
79415   sqlite3 *db = pData->db;
79416   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
79417     if( zObj==0 ) zObj = "?";
79418     sqlite3SetString(pData->pzErrMsg, db,
79419       "malformed database schema (%s)", zObj);
79420     if( zExtra ){
79421       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg, 
79422                                  "%s - %s", *pData->pzErrMsg, zExtra);
79423     }
79424   }
79425   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT;
79426 }
79427
79428 /*
79429 ** This is the callback routine for the code that initializes the
79430 ** database.  See sqlite3Init() below for additional information.
79431 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
79432 **
79433 ** Each callback contains the following information:
79434 **
79435 **     argv[0] = name of thing being created
79436 **     argv[1] = root page number for table or index. 0 for trigger or view.
79437 **     argv[2] = SQL text for the CREATE statement.
79438 **
79439 */
79440 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
79441   InitData *pData = (InitData*)pInit;
79442   sqlite3 *db = pData->db;
79443   int iDb = pData->iDb;
79444
79445   assert( argc==3 );
79446   UNUSED_PARAMETER2(NotUsed, argc);
79447   assert( sqlite3_mutex_held(db->mutex) );
79448   DbClearProperty(db, iDb, DB_Empty);
79449   if( db->mallocFailed ){
79450     corruptSchema(pData, argv[0], 0);
79451     return 1;
79452   }
79453
79454   assert( iDb>=0 && iDb<db->nDb );
79455   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
79456   if( argv[1]==0 ){
79457     corruptSchema(pData, argv[0], 0);
79458   }else if( argv[2] && argv[2][0] ){
79459     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
79460     ** But because db->init.busy is set to 1, no VDBE code is generated
79461     ** or executed.  All the parser does is build the internal data
79462     ** structures that describe the table, index, or view.
79463     */
79464     char *zErr;
79465     int rc;
79466     assert( db->init.busy );
79467     db->init.iDb = iDb;
79468     db->init.newTnum = atoi(argv[1]);
79469     db->init.orphanTrigger = 0;
79470     rc = sqlite3_exec(db, argv[2], 0, 0, &zErr);
79471     db->init.iDb = 0;
79472     assert( rc!=SQLITE_OK || zErr==0 );
79473     if( SQLITE_OK!=rc ){
79474       if( db->init.orphanTrigger ){
79475         assert( iDb==1 );
79476       }else{
79477         pData->rc = rc;
79478         if( rc==SQLITE_NOMEM ){
79479           db->mallocFailed = 1;
79480         }else if( rc!=SQLITE_INTERRUPT && rc!=SQLITE_LOCKED ){
79481           corruptSchema(pData, argv[0], zErr);
79482         }
79483       }
79484       sqlite3DbFree(db, zErr);
79485     }
79486   }else if( argv[0]==0 ){
79487     corruptSchema(pData, 0, 0);
79488   }else{
79489     /* If the SQL column is blank it means this is an index that
79490     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
79491     ** constraint for a CREATE TABLE.  The index should have already
79492     ** been created when we processed the CREATE TABLE.  All we have
79493     ** to do here is record the root page number for that index.
79494     */
79495     Index *pIndex;
79496     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
79497     if( pIndex==0 ){
79498       /* This can occur if there exists an index on a TEMP table which
79499       ** has the same name as another index on a permanent index.  Since
79500       ** the permanent table is hidden by the TEMP table, we can also
79501       ** safely ignore the index on the permanent table.
79502       */
79503       /* Do Nothing */;
79504     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
79505       corruptSchema(pData, argv[0], "invalid rootpage");
79506     }
79507   }
79508   return 0;
79509 }
79510
79511 /*
79512 ** Attempt to read the database schema and initialize internal
79513 ** data structures for a single database file.  The index of the
79514 ** database file is given by iDb.  iDb==0 is used for the main
79515 ** database.  iDb==1 should never be used.  iDb>=2 is used for
79516 ** auxiliary databases.  Return one of the SQLITE_ error codes to
79517 ** indicate success or failure.
79518 */
79519 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
79520   int rc;
79521   int i;
79522   int size;
79523   Table *pTab;
79524   Db *pDb;
79525   char const *azArg[4];
79526   int meta[5];
79527   InitData initData;
79528   char const *zMasterSchema;
79529   char const *zMasterName = SCHEMA_TABLE(iDb);
79530   int openedTransaction = 0;
79531
79532   /*
79533   ** The master database table has a structure like this
79534   */
79535   static const char master_schema[] = 
79536      "CREATE TABLE sqlite_master(\n"
79537      "  type text,\n"
79538      "  name text,\n"
79539      "  tbl_name text,\n"
79540      "  rootpage integer,\n"
79541      "  sql text\n"
79542      ")"
79543   ;
79544 #ifndef SQLITE_OMIT_TEMPDB
79545   static const char temp_master_schema[] = 
79546      "CREATE TEMP TABLE sqlite_temp_master(\n"
79547      "  type text,\n"
79548      "  name text,\n"
79549      "  tbl_name text,\n"
79550      "  rootpage integer,\n"
79551      "  sql text\n"
79552      ")"
79553   ;
79554 #else
79555   #define temp_master_schema 0
79556 #endif
79557
79558   assert( iDb>=0 && iDb<db->nDb );
79559   assert( db->aDb[iDb].pSchema );
79560   assert( sqlite3_mutex_held(db->mutex) );
79561   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
79562
79563   /* zMasterSchema and zInitScript are set to point at the master schema
79564   ** and initialisation script appropriate for the database being
79565   ** initialised. zMasterName is the name of the master table.
79566   */
79567   if( !OMIT_TEMPDB && iDb==1 ){
79568     zMasterSchema = temp_master_schema;
79569   }else{
79570     zMasterSchema = master_schema;
79571   }
79572   zMasterName = SCHEMA_TABLE(iDb);
79573
79574   /* Construct the schema tables.  */
79575   azArg[0] = zMasterName;
79576   azArg[1] = "1";
79577   azArg[2] = zMasterSchema;
79578   azArg[3] = 0;
79579   initData.db = db;
79580   initData.iDb = iDb;
79581   initData.rc = SQLITE_OK;
79582   initData.pzErrMsg = pzErrMsg;
79583   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
79584   if( initData.rc ){
79585     rc = initData.rc;
79586     goto error_out;
79587   }
79588   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
79589   if( ALWAYS(pTab) ){
79590     pTab->tabFlags |= TF_Readonly;
79591   }
79592
79593   /* Create a cursor to hold the database open
79594   */
79595   pDb = &db->aDb[iDb];
79596   if( pDb->pBt==0 ){
79597     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
79598       DbSetProperty(db, 1, DB_SchemaLoaded);
79599     }
79600     return SQLITE_OK;
79601   }
79602
79603   /* If there is not already a read-only (or read-write) transaction opened
79604   ** on the b-tree database, open one now. If a transaction is opened, it 
79605   ** will be closed before this function returns.  */
79606   sqlite3BtreeEnter(pDb->pBt);
79607   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
79608     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
79609     if( rc!=SQLITE_OK ){
79610       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
79611       goto initone_error_out;
79612     }
79613     openedTransaction = 1;
79614   }
79615
79616   /* Get the database meta information.
79617   **
79618   ** Meta values are as follows:
79619   **    meta[0]   Schema cookie.  Changes with each schema change.
79620   **    meta[1]   File format of schema layer.
79621   **    meta[2]   Size of the page cache.
79622   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
79623   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
79624   **    meta[5]   User version
79625   **    meta[6]   Incremental vacuum mode
79626   **    meta[7]   unused
79627   **    meta[8]   unused
79628   **    meta[9]   unused
79629   **
79630   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
79631   ** the possible values of meta[4].
79632   */
79633   for(i=0; i<ArraySize(meta); i++){
79634     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
79635   }
79636   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
79637
79638   /* If opening a non-empty database, check the text encoding. For the
79639   ** main database, set sqlite3.enc to the encoding of the main database.
79640   ** For an attached db, it is an error if the encoding is not the same
79641   ** as sqlite3.enc.
79642   */
79643   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
79644     if( iDb==0 ){
79645       u8 encoding;
79646       /* If opening the main database, set ENC(db). */
79647       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
79648       if( encoding==0 ) encoding = SQLITE_UTF8;
79649       ENC(db) = encoding;
79650       db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
79651     }else{
79652       /* If opening an attached database, the encoding much match ENC(db) */
79653       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
79654         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
79655             " text encoding as main database");
79656         rc = SQLITE_ERROR;
79657         goto initone_error_out;
79658       }
79659     }
79660   }else{
79661     DbSetProperty(db, iDb, DB_Empty);
79662   }
79663   pDb->pSchema->enc = ENC(db);
79664
79665   if( pDb->pSchema->cache_size==0 ){
79666     size = meta[BTREE_DEFAULT_CACHE_SIZE-1];
79667     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
79668     if( size<0 ) size = -size;
79669     pDb->pSchema->cache_size = size;
79670     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
79671   }
79672
79673   /*
79674   ** file_format==1    Version 3.0.0.
79675   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
79676   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
79677   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
79678   */
79679   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
79680   if( pDb->pSchema->file_format==0 ){
79681     pDb->pSchema->file_format = 1;
79682   }
79683   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
79684     sqlite3SetString(pzErrMsg, db, "unsupported file format");
79685     rc = SQLITE_ERROR;
79686     goto initone_error_out;
79687   }
79688
79689   /* Ticket #2804:  When we open a database in the newer file format,
79690   ** clear the legacy_file_format pragma flag so that a VACUUM will
79691   ** not downgrade the database and thus invalidate any descending
79692   ** indices that the user might have created.
79693   */
79694   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
79695     db->flags &= ~SQLITE_LegacyFileFmt;
79696   }
79697
79698   /* Read the schema information out of the schema tables
79699   */
79700   assert( db->init.busy );
79701   {
79702     char *zSql;
79703     zSql = sqlite3MPrintf(db, 
79704         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
79705         db->aDb[iDb].zName, zMasterName);
79706 #ifndef SQLITE_OMIT_AUTHORIZATION
79707     {
79708       int (*xAuth)(void*,int,const char*,const char*,const char*,const char*);
79709       xAuth = db->xAuth;
79710       db->xAuth = 0;
79711 #endif
79712       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
79713 #ifndef SQLITE_OMIT_AUTHORIZATION
79714       db->xAuth = xAuth;
79715     }
79716 #endif
79717     if( rc==SQLITE_OK ) rc = initData.rc;
79718     sqlite3DbFree(db, zSql);
79719 #ifndef SQLITE_OMIT_ANALYZE
79720     if( rc==SQLITE_OK ){
79721       sqlite3AnalysisLoad(db, iDb);
79722     }
79723 #endif
79724   }
79725   if( db->mallocFailed ){
79726     rc = SQLITE_NOMEM;
79727     sqlite3ResetInternalSchema(db, 0);
79728   }
79729   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
79730     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
79731     ** the schema loaded, even if errors occurred. In this situation the 
79732     ** current sqlite3_prepare() operation will fail, but the following one
79733     ** will attempt to compile the supplied statement against whatever subset
79734     ** of the schema was loaded before the error occurred. The primary
79735     ** purpose of this is to allow access to the sqlite_master table
79736     ** even when its contents have been corrupted.
79737     */
79738     DbSetProperty(db, iDb, DB_SchemaLoaded);
79739     rc = SQLITE_OK;
79740   }
79741
79742   /* Jump here for an error that occurs after successfully allocating
79743   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
79744   ** before that point, jump to error_out.
79745   */
79746 initone_error_out:
79747   if( openedTransaction ){
79748     sqlite3BtreeCommit(pDb->pBt);
79749   }
79750   sqlite3BtreeLeave(pDb->pBt);
79751
79752 error_out:
79753   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
79754     db->mallocFailed = 1;
79755   }
79756   return rc;
79757 }
79758
79759 /*
79760 ** Initialize all database files - the main database file, the file
79761 ** used to store temporary tables, and any additional database files
79762 ** created using ATTACH statements.  Return a success code.  If an
79763 ** error occurs, write an error message into *pzErrMsg.
79764 **
79765 ** After a database is initialized, the DB_SchemaLoaded bit is set
79766 ** bit is set in the flags field of the Db structure. If the database
79767 ** file was of zero-length, then the DB_Empty flag is also set.
79768 */
79769 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
79770   int i, rc;
79771   int commit_internal = !(db->flags&SQLITE_InternChanges);
79772   
79773   assert( sqlite3_mutex_held(db->mutex) );
79774   rc = SQLITE_OK;
79775   db->init.busy = 1;
79776   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
79777     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
79778     rc = sqlite3InitOne(db, i, pzErrMsg);
79779     if( rc ){
79780       sqlite3ResetInternalSchema(db, i);
79781     }
79782   }
79783
79784   /* Once all the other databases have been initialised, load the schema
79785   ** for the TEMP database. This is loaded last, as the TEMP database
79786   ** schema may contain references to objects in other databases.
79787   */
79788 #ifndef SQLITE_OMIT_TEMPDB
79789   if( rc==SQLITE_OK && ALWAYS(db->nDb>1)
79790                     && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
79791     rc = sqlite3InitOne(db, 1, pzErrMsg);
79792     if( rc ){
79793       sqlite3ResetInternalSchema(db, 1);
79794     }
79795   }
79796 #endif
79797
79798   db->init.busy = 0;
79799   if( rc==SQLITE_OK && commit_internal ){
79800     sqlite3CommitInternalChanges(db);
79801   }
79802
79803   return rc; 
79804 }
79805
79806 /*
79807 ** This routine is a no-op if the database schema is already initialised.
79808 ** Otherwise, the schema is loaded. An error code is returned.
79809 */
79810 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
79811   int rc = SQLITE_OK;
79812   sqlite3 *db = pParse->db;
79813   assert( sqlite3_mutex_held(db->mutex) );
79814   if( !db->init.busy ){
79815     rc = sqlite3Init(db, &pParse->zErrMsg);
79816   }
79817   if( rc!=SQLITE_OK ){
79818     pParse->rc = rc;
79819     pParse->nErr++;
79820   }
79821   return rc;
79822 }
79823
79824
79825 /*
79826 ** Check schema cookies in all databases.  If any cookie is out
79827 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
79828 ** make no changes to pParse->rc.
79829 */
79830 static void schemaIsValid(Parse *pParse){
79831   sqlite3 *db = pParse->db;
79832   int iDb;
79833   int rc;
79834   int cookie;
79835
79836   assert( pParse->checkSchema );
79837   assert( sqlite3_mutex_held(db->mutex) );
79838   for(iDb=0; iDb<db->nDb; iDb++){
79839     int openedTransaction = 0;         /* True if a transaction is opened */
79840     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
79841     if( pBt==0 ) continue;
79842
79843     /* If there is not already a read-only (or read-write) transaction opened
79844     ** on the b-tree database, open one now. If a transaction is opened, it 
79845     ** will be closed immediately after reading the meta-value. */
79846     if( !sqlite3BtreeIsInReadTrans(pBt) ){
79847       rc = sqlite3BtreeBeginTrans(pBt, 0);
79848       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
79849         db->mallocFailed = 1;
79850       }
79851       if( rc!=SQLITE_OK ) return;
79852       openedTransaction = 1;
79853     }
79854
79855     /* Read the schema cookie from the database. If it does not match the 
79856     ** value stored as part of the in-memory schema representation,
79857     ** set Parse.rc to SQLITE_SCHEMA. */
79858     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
79859     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
79860       pParse->rc = SQLITE_SCHEMA;
79861     }
79862
79863     /* Close the transaction, if one was opened. */
79864     if( openedTransaction ){
79865       sqlite3BtreeCommit(pBt);
79866     }
79867   }
79868 }
79869
79870 /*
79871 ** Convert a schema pointer into the iDb index that indicates
79872 ** which database file in db->aDb[] the schema refers to.
79873 **
79874 ** If the same database is attached more than once, the first
79875 ** attached database is returned.
79876 */
79877 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
79878   int i = -1000000;
79879
79880   /* If pSchema is NULL, then return -1000000. This happens when code in 
79881   ** expr.c is trying to resolve a reference to a transient table (i.e. one
79882   ** created by a sub-select). In this case the return value of this 
79883   ** function should never be used.
79884   **
79885   ** We return -1000000 instead of the more usual -1 simply because using
79886   ** -1000000 as the incorrect index into db->aDb[] is much 
79887   ** more likely to cause a segfault than -1 (of course there are assert()
79888   ** statements too, but it never hurts to play the odds).
79889   */
79890   assert( sqlite3_mutex_held(db->mutex) );
79891   if( pSchema ){
79892     for(i=0; ALWAYS(i<db->nDb); i++){
79893       if( db->aDb[i].pSchema==pSchema ){
79894         break;
79895       }
79896     }
79897     assert( i>=0 && i<db->nDb );
79898   }
79899   return i;
79900 }
79901
79902 /*
79903 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
79904 */
79905 static int sqlite3Prepare(
79906   sqlite3 *db,              /* Database handle. */
79907   const char *zSql,         /* UTF-8 encoded SQL statement. */
79908   int nBytes,               /* Length of zSql in bytes. */
79909   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
79910   Vdbe *pReprepare,         /* VM being reprepared */
79911   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
79912   const char **pzTail       /* OUT: End of parsed string */
79913 ){
79914   Parse *pParse;            /* Parsing context */
79915   char *zErrMsg = 0;        /* Error message */
79916   int rc = SQLITE_OK;       /* Result code */
79917   int i;                    /* Loop counter */
79918
79919   /* Allocate the parsing context */
79920   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
79921   if( pParse==0 ){
79922     rc = SQLITE_NOMEM;
79923     goto end_prepare;
79924   }
79925   pParse->pReprepare = pReprepare;
79926   assert( ppStmt && *ppStmt==0 );
79927   assert( !db->mallocFailed );
79928   assert( sqlite3_mutex_held(db->mutex) );
79929
79930   /* Check to verify that it is possible to get a read lock on all
79931   ** database schemas.  The inability to get a read lock indicates that
79932   ** some other database connection is holding a write-lock, which in
79933   ** turn means that the other connection has made uncommitted changes
79934   ** to the schema.
79935   **
79936   ** Were we to proceed and prepare the statement against the uncommitted
79937   ** schema changes and if those schema changes are subsequently rolled
79938   ** back and different changes are made in their place, then when this
79939   ** prepared statement goes to run the schema cookie would fail to detect
79940   ** the schema change.  Disaster would follow.
79941   **
79942   ** This thread is currently holding mutexes on all Btrees (because
79943   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
79944   ** is not possible for another thread to start a new schema change
79945   ** while this routine is running.  Hence, we do not need to hold 
79946   ** locks on the schema, we just need to make sure nobody else is 
79947   ** holding them.
79948   **
79949   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
79950   ** but it does *not* override schema lock detection, so this all still
79951   ** works even if READ_UNCOMMITTED is set.
79952   */
79953   for(i=0; i<db->nDb; i++) {
79954     Btree *pBt = db->aDb[i].pBt;
79955     if( pBt ){
79956       assert( sqlite3BtreeHoldsMutex(pBt) );
79957       rc = sqlite3BtreeSchemaLocked(pBt);
79958       if( rc ){
79959         const char *zDb = db->aDb[i].zName;
79960         sqlite3Error(db, rc, "database schema is locked: %s", zDb);
79961         testcase( db->flags & SQLITE_ReadUncommitted );
79962         goto end_prepare;
79963       }
79964     }
79965   }
79966
79967   sqlite3VtabUnlockList(db);
79968
79969   pParse->db = db;
79970   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
79971     char *zSqlCopy;
79972     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
79973     testcase( nBytes==mxLen );
79974     testcase( nBytes==mxLen+1 );
79975     if( nBytes>mxLen ){
79976       sqlite3Error(db, SQLITE_TOOBIG, "statement too long");
79977       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
79978       goto end_prepare;
79979     }
79980     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
79981     if( zSqlCopy ){
79982       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
79983       sqlite3DbFree(db, zSqlCopy);
79984       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
79985     }else{
79986       pParse->zTail = &zSql[nBytes];
79987     }
79988   }else{
79989     sqlite3RunParser(pParse, zSql, &zErrMsg);
79990   }
79991
79992   if( db->mallocFailed ){
79993     pParse->rc = SQLITE_NOMEM;
79994   }
79995   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
79996   if( pParse->checkSchema ){
79997     schemaIsValid(pParse);
79998   }
79999   if( pParse->rc==SQLITE_SCHEMA ){
80000     sqlite3ResetInternalSchema(db, 0);
80001   }
80002   if( db->mallocFailed ){
80003     pParse->rc = SQLITE_NOMEM;
80004   }
80005   if( pzTail ){
80006     *pzTail = pParse->zTail;
80007   }
80008   rc = pParse->rc;
80009
80010 #ifndef SQLITE_OMIT_EXPLAIN
80011   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
80012     static const char * const azColName[] = {
80013        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
80014        "order", "from", "detail"
80015     };
80016     int iFirst, mx;
80017     if( pParse->explain==2 ){
80018       sqlite3VdbeSetNumCols(pParse->pVdbe, 3);
80019       iFirst = 8;
80020       mx = 11;
80021     }else{
80022       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
80023       iFirst = 0;
80024       mx = 8;
80025     }
80026     for(i=iFirst; i<mx; i++){
80027       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
80028                             azColName[i], SQLITE_STATIC);
80029     }
80030   }
80031 #endif
80032
80033   assert( db->init.busy==0 || saveSqlFlag==0 );
80034   if( db->init.busy==0 ){
80035     Vdbe *pVdbe = pParse->pVdbe;
80036     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
80037   }
80038   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
80039     sqlite3VdbeFinalize(pParse->pVdbe);
80040     assert(!(*ppStmt));
80041   }else{
80042     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
80043   }
80044
80045   if( zErrMsg ){
80046     sqlite3Error(db, rc, "%s", zErrMsg);
80047     sqlite3DbFree(db, zErrMsg);
80048   }else{
80049     sqlite3Error(db, rc, 0);
80050   }
80051
80052   /* Delete any TriggerPrg structures allocated while parsing this statement. */
80053   while( pParse->pTriggerPrg ){
80054     TriggerPrg *pT = pParse->pTriggerPrg;
80055     pParse->pTriggerPrg = pT->pNext;
80056     sqlite3VdbeProgramDelete(db, pT->pProgram, 0);
80057     sqlite3DbFree(db, pT);
80058   }
80059
80060 end_prepare:
80061
80062   sqlite3StackFree(db, pParse);
80063   rc = sqlite3ApiExit(db, rc);
80064   assert( (rc&db->errMask)==rc );
80065   return rc;
80066 }
80067 static int sqlite3LockAndPrepare(
80068   sqlite3 *db,              /* Database handle. */
80069   const char *zSql,         /* UTF-8 encoded SQL statement. */
80070   int nBytes,               /* Length of zSql in bytes. */
80071   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
80072   Vdbe *pOld,               /* VM being reprepared */
80073   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
80074   const char **pzTail       /* OUT: End of parsed string */
80075 ){
80076   int rc;
80077   assert( ppStmt!=0 );
80078   *ppStmt = 0;
80079   if( !sqlite3SafetyCheckOk(db) ){
80080     return SQLITE_MISUSE_BKPT;
80081   }
80082   sqlite3_mutex_enter(db->mutex);
80083   sqlite3BtreeEnterAll(db);
80084   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
80085   if( rc==SQLITE_SCHEMA ){
80086     sqlite3_finalize(*ppStmt);
80087     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
80088   }
80089   sqlite3BtreeLeaveAll(db);
80090   sqlite3_mutex_leave(db->mutex);
80091   return rc;
80092 }
80093
80094 /*
80095 ** Rerun the compilation of a statement after a schema change.
80096 **
80097 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
80098 ** if the statement cannot be recompiled because another connection has
80099 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
80100 ** occurs, return SQLITE_SCHEMA.
80101 */
80102 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
80103   int rc;
80104   sqlite3_stmt *pNew;
80105   const char *zSql;
80106   sqlite3 *db;
80107
80108   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
80109   zSql = sqlite3_sql((sqlite3_stmt *)p);
80110   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
80111   db = sqlite3VdbeDb(p);
80112   assert( sqlite3_mutex_held(db->mutex) );
80113   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
80114   if( rc ){
80115     if( rc==SQLITE_NOMEM ){
80116       db->mallocFailed = 1;
80117     }
80118     assert( pNew==0 );
80119     return rc;
80120   }else{
80121     assert( pNew!=0 );
80122   }
80123   sqlite3VdbeSwap((Vdbe*)pNew, p);
80124   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
80125   sqlite3VdbeResetStepResult((Vdbe*)pNew);
80126   sqlite3VdbeFinalize((Vdbe*)pNew);
80127   return SQLITE_OK;
80128 }
80129
80130
80131 /*
80132 ** Two versions of the official API.  Legacy and new use.  In the legacy
80133 ** version, the original SQL text is not saved in the prepared statement
80134 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
80135 ** sqlite3_step().  In the new version, the original SQL text is retained
80136 ** and the statement is automatically recompiled if an schema change
80137 ** occurs.
80138 */
80139 SQLITE_API int sqlite3_prepare(
80140   sqlite3 *db,              /* Database handle. */
80141   const char *zSql,         /* UTF-8 encoded SQL statement. */
80142   int nBytes,               /* Length of zSql in bytes. */
80143   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
80144   const char **pzTail       /* OUT: End of parsed string */
80145 ){
80146   int rc;
80147   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
80148   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
80149   return rc;
80150 }
80151 SQLITE_API int sqlite3_prepare_v2(
80152   sqlite3 *db,              /* Database handle. */
80153   const char *zSql,         /* UTF-8 encoded SQL statement. */
80154   int nBytes,               /* Length of zSql in bytes. */
80155   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
80156   const char **pzTail       /* OUT: End of parsed string */
80157 ){
80158   int rc;
80159   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
80160   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
80161   return rc;
80162 }
80163
80164
80165 #ifndef SQLITE_OMIT_UTF16
80166 /*
80167 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
80168 */
80169 static int sqlite3Prepare16(
80170   sqlite3 *db,              /* Database handle. */ 
80171   const void *zSql,         /* UTF-8 encoded SQL statement. */
80172   int nBytes,               /* Length of zSql in bytes. */
80173   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
80174   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
80175   const void **pzTail       /* OUT: End of parsed string */
80176 ){
80177   /* This function currently works by first transforming the UTF-16
80178   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
80179   ** tricky bit is figuring out the pointer to return in *pzTail.
80180   */
80181   char *zSql8;
80182   const char *zTail8 = 0;
80183   int rc = SQLITE_OK;
80184
80185   assert( ppStmt );
80186   *ppStmt = 0;
80187   if( !sqlite3SafetyCheckOk(db) ){
80188     return SQLITE_MISUSE_BKPT;
80189   }
80190   sqlite3_mutex_enter(db->mutex);
80191   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
80192   if( zSql8 ){
80193     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
80194   }
80195
80196   if( zTail8 && pzTail ){
80197     /* If sqlite3_prepare returns a tail pointer, we calculate the
80198     ** equivalent pointer into the UTF-16 string by counting the unicode
80199     ** characters between zSql8 and zTail8, and then returning a pointer
80200     ** the same number of characters into the UTF-16 string.
80201     */
80202     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
80203     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
80204   }
80205   sqlite3DbFree(db, zSql8); 
80206   rc = sqlite3ApiExit(db, rc);
80207   sqlite3_mutex_leave(db->mutex);
80208   return rc;
80209 }
80210
80211 /*
80212 ** Two versions of the official API.  Legacy and new use.  In the legacy
80213 ** version, the original SQL text is not saved in the prepared statement
80214 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
80215 ** sqlite3_step().  In the new version, the original SQL text is retained
80216 ** and the statement is automatically recompiled if an schema change
80217 ** occurs.
80218 */
80219 SQLITE_API int sqlite3_prepare16(
80220   sqlite3 *db,              /* Database handle. */ 
80221   const void *zSql,         /* UTF-8 encoded SQL statement. */
80222   int nBytes,               /* Length of zSql in bytes. */
80223   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
80224   const void **pzTail       /* OUT: End of parsed string */
80225 ){
80226   int rc;
80227   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
80228   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
80229   return rc;
80230 }
80231 SQLITE_API int sqlite3_prepare16_v2(
80232   sqlite3 *db,              /* Database handle. */ 
80233   const void *zSql,         /* UTF-8 encoded SQL statement. */
80234   int nBytes,               /* Length of zSql in bytes. */
80235   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
80236   const void **pzTail       /* OUT: End of parsed string */
80237 ){
80238   int rc;
80239   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
80240   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
80241   return rc;
80242 }
80243
80244 #endif /* SQLITE_OMIT_UTF16 */
80245
80246 /************** End of prepare.c *********************************************/
80247 /************** Begin file select.c ******************************************/
80248 /*
80249 ** 2001 September 15
80250 **
80251 ** The author disclaims copyright to this source code.  In place of
80252 ** a legal notice, here is a blessing:
80253 **
80254 **    May you do good and not evil.
80255 **    May you find forgiveness for yourself and forgive others.
80256 **    May you share freely, never taking more than you give.
80257 **
80258 *************************************************************************
80259 ** This file contains C code routines that are called by the parser
80260 ** to handle SELECT statements in SQLite.
80261 */
80262
80263
80264 /*
80265 ** Delete all the content of a Select structure but do not deallocate
80266 ** the select structure itself.
80267 */
80268 static void clearSelect(sqlite3 *db, Select *p){
80269   sqlite3ExprListDelete(db, p->pEList);
80270   sqlite3SrcListDelete(db, p->pSrc);
80271   sqlite3ExprDelete(db, p->pWhere);
80272   sqlite3ExprListDelete(db, p->pGroupBy);
80273   sqlite3ExprDelete(db, p->pHaving);
80274   sqlite3ExprListDelete(db, p->pOrderBy);
80275   sqlite3SelectDelete(db, p->pPrior);
80276   sqlite3ExprDelete(db, p->pLimit);
80277   sqlite3ExprDelete(db, p->pOffset);
80278 }
80279
80280 /*
80281 ** Initialize a SelectDest structure.
80282 */
80283 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
80284   pDest->eDest = (u8)eDest;
80285   pDest->iParm = iParm;
80286   pDest->affinity = 0;
80287   pDest->iMem = 0;
80288   pDest->nMem = 0;
80289 }
80290
80291
80292 /*
80293 ** Allocate a new Select structure and return a pointer to that
80294 ** structure.
80295 */
80296 SQLITE_PRIVATE Select *sqlite3SelectNew(
80297   Parse *pParse,        /* Parsing context */
80298   ExprList *pEList,     /* which columns to include in the result */
80299   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
80300   Expr *pWhere,         /* the WHERE clause */
80301   ExprList *pGroupBy,   /* the GROUP BY clause */
80302   Expr *pHaving,        /* the HAVING clause */
80303   ExprList *pOrderBy,   /* the ORDER BY clause */
80304   int isDistinct,       /* true if the DISTINCT keyword is present */
80305   Expr *pLimit,         /* LIMIT value.  NULL means not used */
80306   Expr *pOffset         /* OFFSET value.  NULL means no offset */
80307 ){
80308   Select *pNew;
80309   Select standin;
80310   sqlite3 *db = pParse->db;
80311   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
80312   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
80313   if( pNew==0 ){
80314     pNew = &standin;
80315     memset(pNew, 0, sizeof(*pNew));
80316   }
80317   if( pEList==0 ){
80318     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
80319   }
80320   pNew->pEList = pEList;
80321   pNew->pSrc = pSrc;
80322   pNew->pWhere = pWhere;
80323   pNew->pGroupBy = pGroupBy;
80324   pNew->pHaving = pHaving;
80325   pNew->pOrderBy = pOrderBy;
80326   pNew->selFlags = isDistinct ? SF_Distinct : 0;
80327   pNew->op = TK_SELECT;
80328   pNew->pLimit = pLimit;
80329   pNew->pOffset = pOffset;
80330   assert( pOffset==0 || pLimit!=0 );
80331   pNew->addrOpenEphm[0] = -1;
80332   pNew->addrOpenEphm[1] = -1;
80333   pNew->addrOpenEphm[2] = -1;
80334   if( db->mallocFailed ) {
80335     clearSelect(db, pNew);
80336     if( pNew!=&standin ) sqlite3DbFree(db, pNew);
80337     pNew = 0;
80338   }
80339   return pNew;
80340 }
80341
80342 /*
80343 ** Delete the given Select structure and all of its substructures.
80344 */
80345 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
80346   if( p ){
80347     clearSelect(db, p);
80348     sqlite3DbFree(db, p);
80349   }
80350 }
80351
80352 /*
80353 ** Given 1 to 3 identifiers preceeding the JOIN keyword, determine the
80354 ** type of join.  Return an integer constant that expresses that type
80355 ** in terms of the following bit values:
80356 **
80357 **     JT_INNER
80358 **     JT_CROSS
80359 **     JT_OUTER
80360 **     JT_NATURAL
80361 **     JT_LEFT
80362 **     JT_RIGHT
80363 **
80364 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
80365 **
80366 ** If an illegal or unsupported join type is seen, then still return
80367 ** a join type, but put an error in the pParse structure.
80368 */
80369 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
80370   int jointype = 0;
80371   Token *apAll[3];
80372   Token *p;
80373                              /*   0123456789 123456789 123456789 123 */
80374   static const char zKeyText[] = "naturaleftouterightfullinnercross";
80375   static const struct {
80376     u8 i;        /* Beginning of keyword text in zKeyText[] */
80377     u8 nChar;    /* Length of the keyword in characters */
80378     u8 code;     /* Join type mask */
80379   } aKeyword[] = {
80380     /* natural */ { 0,  7, JT_NATURAL                },
80381     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
80382     /* outer   */ { 10, 5, JT_OUTER                  },
80383     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
80384     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
80385     /* inner   */ { 23, 5, JT_INNER                  },
80386     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
80387   };
80388   int i, j;
80389   apAll[0] = pA;
80390   apAll[1] = pB;
80391   apAll[2] = pC;
80392   for(i=0; i<3 && apAll[i]; i++){
80393     p = apAll[i];
80394     for(j=0; j<ArraySize(aKeyword); j++){
80395       if( p->n==aKeyword[j].nChar 
80396           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
80397         jointype |= aKeyword[j].code;
80398         break;
80399       }
80400     }
80401     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
80402     if( j>=ArraySize(aKeyword) ){
80403       jointype |= JT_ERROR;
80404       break;
80405     }
80406   }
80407   if(
80408      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
80409      (jointype & JT_ERROR)!=0
80410   ){
80411     const char *zSp = " ";
80412     assert( pB!=0 );
80413     if( pC==0 ){ zSp++; }
80414     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
80415        "%T %T%s%T", pA, pB, zSp, pC);
80416     jointype = JT_INNER;
80417   }else if( (jointype & JT_OUTER)!=0 
80418          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
80419     sqlite3ErrorMsg(pParse, 
80420       "RIGHT and FULL OUTER JOINs are not currently supported");
80421     jointype = JT_INNER;
80422   }
80423   return jointype;
80424 }
80425
80426 /*
80427 ** Return the index of a column in a table.  Return -1 if the column
80428 ** is not contained in the table.
80429 */
80430 static int columnIndex(Table *pTab, const char *zCol){
80431   int i;
80432   for(i=0; i<pTab->nCol; i++){
80433     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
80434   }
80435   return -1;
80436 }
80437
80438 /*
80439 ** Search the first N tables in pSrc, from left to right, looking for a
80440 ** table that has a column named zCol.  
80441 **
80442 ** When found, set *piTab and *piCol to the table index and column index
80443 ** of the matching column and return TRUE.
80444 **
80445 ** If not found, return FALSE.
80446 */
80447 static int tableAndColumnIndex(
80448   SrcList *pSrc,       /* Array of tables to search */
80449   int N,               /* Number of tables in pSrc->a[] to search */
80450   const char *zCol,    /* Name of the column we are looking for */
80451   int *piTab,          /* Write index of pSrc->a[] here */
80452   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
80453 ){
80454   int i;               /* For looping over tables in pSrc */
80455   int iCol;            /* Index of column matching zCol */
80456
80457   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
80458   for(i=0; i<N; i++){
80459     iCol = columnIndex(pSrc->a[i].pTab, zCol);
80460     if( iCol>=0 ){
80461       if( piTab ){
80462         *piTab = i;
80463         *piCol = iCol;
80464       }
80465       return 1;
80466     }
80467   }
80468   return 0;
80469 }
80470
80471 /*
80472 ** This function is used to add terms implied by JOIN syntax to the
80473 ** WHERE clause expression of a SELECT statement. The new term, which
80474 ** is ANDed with the existing WHERE clause, is of the form:
80475 **
80476 **    (tab1.col1 = tab2.col2)
80477 **
80478 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
80479 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
80480 ** column iColRight of tab2.
80481 */
80482 static void addWhereTerm(
80483   Parse *pParse,                  /* Parsing context */
80484   SrcList *pSrc,                  /* List of tables in FROM clause */
80485   int iLeft,                      /* Index of first table to join in pSrc */
80486   int iColLeft,                   /* Index of column in first table */
80487   int iRight,                     /* Index of second table in pSrc */
80488   int iColRight,                  /* Index of column in second table */
80489   int isOuterJoin,                /* True if this is an OUTER join */
80490   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
80491 ){
80492   sqlite3 *db = pParse->db;
80493   Expr *pE1;
80494   Expr *pE2;
80495   Expr *pEq;
80496
80497   assert( iLeft<iRight );
80498   assert( pSrc->nSrc>iRight );
80499   assert( pSrc->a[iLeft].pTab );
80500   assert( pSrc->a[iRight].pTab );
80501
80502   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
80503   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
80504
80505   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
80506   if( pEq && isOuterJoin ){
80507     ExprSetProperty(pEq, EP_FromJoin);
80508     assert( !ExprHasAnyProperty(pEq, EP_TokenOnly|EP_Reduced) );
80509     ExprSetIrreducible(pEq);
80510     pEq->iRightJoinTable = (i16)pE2->iTable;
80511   }
80512   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
80513 }
80514
80515 /*
80516 ** Set the EP_FromJoin property on all terms of the given expression.
80517 ** And set the Expr.iRightJoinTable to iTable for every term in the
80518 ** expression.
80519 **
80520 ** The EP_FromJoin property is used on terms of an expression to tell
80521 ** the LEFT OUTER JOIN processing logic that this term is part of the
80522 ** join restriction specified in the ON or USING clause and not a part
80523 ** of the more general WHERE clause.  These terms are moved over to the
80524 ** WHERE clause during join processing but we need to remember that they
80525 ** originated in the ON or USING clause.
80526 **
80527 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
80528 ** expression depends on table iRightJoinTable even if that table is not
80529 ** explicitly mentioned in the expression.  That information is needed
80530 ** for cases like this:
80531 **
80532 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
80533 **
80534 ** The where clause needs to defer the handling of the t1.x=5
80535 ** term until after the t2 loop of the join.  In that way, a
80536 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
80537 ** defer the handling of t1.x=5, it will be processed immediately
80538 ** after the t1 loop and rows with t1.x!=5 will never appear in
80539 ** the output, which is incorrect.
80540 */
80541 static void setJoinExpr(Expr *p, int iTable){
80542   while( p ){
80543     ExprSetProperty(p, EP_FromJoin);
80544     assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
80545     ExprSetIrreducible(p);
80546     p->iRightJoinTable = (i16)iTable;
80547     setJoinExpr(p->pLeft, iTable);
80548     p = p->pRight;
80549   } 
80550 }
80551
80552 /*
80553 ** This routine processes the join information for a SELECT statement.
80554 ** ON and USING clauses are converted into extra terms of the WHERE clause.
80555 ** NATURAL joins also create extra WHERE clause terms.
80556 **
80557 ** The terms of a FROM clause are contained in the Select.pSrc structure.
80558 ** The left most table is the first entry in Select.pSrc.  The right-most
80559 ** table is the last entry.  The join operator is held in the entry to
80560 ** the left.  Thus entry 0 contains the join operator for the join between
80561 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
80562 ** also attached to the left entry.
80563 **
80564 ** This routine returns the number of errors encountered.
80565 */
80566 static int sqliteProcessJoin(Parse *pParse, Select *p){
80567   SrcList *pSrc;                  /* All tables in the FROM clause */
80568   int i, j;                       /* Loop counters */
80569   struct SrcList_item *pLeft;     /* Left table being joined */
80570   struct SrcList_item *pRight;    /* Right table being joined */
80571
80572   pSrc = p->pSrc;
80573   pLeft = &pSrc->a[0];
80574   pRight = &pLeft[1];
80575   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
80576     Table *pLeftTab = pLeft->pTab;
80577     Table *pRightTab = pRight->pTab;
80578     int isOuter;
80579
80580     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
80581     isOuter = (pRight->jointype & JT_OUTER)!=0;
80582
80583     /* When the NATURAL keyword is present, add WHERE clause terms for
80584     ** every column that the two tables have in common.
80585     */
80586     if( pRight->jointype & JT_NATURAL ){
80587       if( pRight->pOn || pRight->pUsing ){
80588         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
80589            "an ON or USING clause", 0);
80590         return 1;
80591       }
80592       for(j=0; j<pRightTab->nCol; j++){
80593         char *zName;   /* Name of column in the right table */
80594         int iLeft;     /* Matching left table */
80595         int iLeftCol;  /* Matching column in the left table */
80596
80597         zName = pRightTab->aCol[j].zName;
80598         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
80599           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
80600                        isOuter, &p->pWhere);
80601         }
80602       }
80603     }
80604
80605     /* Disallow both ON and USING clauses in the same join
80606     */
80607     if( pRight->pOn && pRight->pUsing ){
80608       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
80609         "clauses in the same join");
80610       return 1;
80611     }
80612
80613     /* Add the ON clause to the end of the WHERE clause, connected by
80614     ** an AND operator.
80615     */
80616     if( pRight->pOn ){
80617       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
80618       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
80619       pRight->pOn = 0;
80620     }
80621
80622     /* Create extra terms on the WHERE clause for each column named
80623     ** in the USING clause.  Example: If the two tables to be joined are 
80624     ** A and B and the USING clause names X, Y, and Z, then add this
80625     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
80626     ** Report an error if any column mentioned in the USING clause is
80627     ** not contained in both tables to be joined.
80628     */
80629     if( pRight->pUsing ){
80630       IdList *pList = pRight->pUsing;
80631       for(j=0; j<pList->nId; j++){
80632         char *zName;     /* Name of the term in the USING clause */
80633         int iLeft;       /* Table on the left with matching column name */
80634         int iLeftCol;    /* Column number of matching column on the left */
80635         int iRightCol;   /* Column number of matching column on the right */
80636
80637         zName = pList->a[j].zName;
80638         iRightCol = columnIndex(pRightTab, zName);
80639         if( iRightCol<0
80640          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
80641         ){
80642           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
80643             "not present in both tables", zName);
80644           return 1;
80645         }
80646         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
80647                      isOuter, &p->pWhere);
80648       }
80649     }
80650   }
80651   return 0;
80652 }
80653
80654 /*
80655 ** Insert code into "v" that will push the record on the top of the
80656 ** stack into the sorter.
80657 */
80658 static void pushOntoSorter(
80659   Parse *pParse,         /* Parser context */
80660   ExprList *pOrderBy,    /* The ORDER BY clause */
80661   Select *pSelect,       /* The whole SELECT statement */
80662   int regData            /* Register holding data to be sorted */
80663 ){
80664   Vdbe *v = pParse->pVdbe;
80665   int nExpr = pOrderBy->nExpr;
80666   int regBase = sqlite3GetTempRange(pParse, nExpr+2);
80667   int regRecord = sqlite3GetTempReg(pParse);
80668   sqlite3ExprCacheClear(pParse);
80669   sqlite3ExprCodeExprList(pParse, pOrderBy, regBase, 0);
80670   sqlite3VdbeAddOp2(v, OP_Sequence, pOrderBy->iECursor, regBase+nExpr);
80671   sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+1, 1);
80672   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nExpr + 2, regRecord);
80673   sqlite3VdbeAddOp2(v, OP_IdxInsert, pOrderBy->iECursor, regRecord);
80674   sqlite3ReleaseTempReg(pParse, regRecord);
80675   sqlite3ReleaseTempRange(pParse, regBase, nExpr+2);
80676   if( pSelect->iLimit ){
80677     int addr1, addr2;
80678     int iLimit;
80679     if( pSelect->iOffset ){
80680       iLimit = pSelect->iOffset+1;
80681     }else{
80682       iLimit = pSelect->iLimit;
80683     }
80684     addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit);
80685     sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
80686     addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
80687     sqlite3VdbeJumpHere(v, addr1);
80688     sqlite3VdbeAddOp1(v, OP_Last, pOrderBy->iECursor);
80689     sqlite3VdbeAddOp1(v, OP_Delete, pOrderBy->iECursor);
80690     sqlite3VdbeJumpHere(v, addr2);
80691     pSelect->iLimit = 0;
80692   }
80693 }
80694
80695 /*
80696 ** Add code to implement the OFFSET
80697 */
80698 static void codeOffset(
80699   Vdbe *v,          /* Generate code into this VM */
80700   Select *p,        /* The SELECT statement being coded */
80701   int iContinue     /* Jump here to skip the current record */
80702 ){
80703   if( p->iOffset && iContinue!=0 ){
80704     int addr;
80705     sqlite3VdbeAddOp2(v, OP_AddImm, p->iOffset, -1);
80706     addr = sqlite3VdbeAddOp1(v, OP_IfNeg, p->iOffset);
80707     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
80708     VdbeComment((v, "skip OFFSET records"));
80709     sqlite3VdbeJumpHere(v, addr);
80710   }
80711 }
80712
80713 /*
80714 ** Add code that will check to make sure the N registers starting at iMem
80715 ** form a distinct entry.  iTab is a sorting index that holds previously
80716 ** seen combinations of the N values.  A new entry is made in iTab
80717 ** if the current N values are new.
80718 **
80719 ** A jump to addrRepeat is made and the N+1 values are popped from the
80720 ** stack if the top N elements are not distinct.
80721 */
80722 static void codeDistinct(
80723   Parse *pParse,     /* Parsing and code generating context */
80724   int iTab,          /* A sorting index used to test for distinctness */
80725   int addrRepeat,    /* Jump to here if not distinct */
80726   int N,             /* Number of elements */
80727   int iMem           /* First element */
80728 ){
80729   Vdbe *v;
80730   int r1;
80731
80732   v = pParse->pVdbe;
80733   r1 = sqlite3GetTempReg(pParse);
80734   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N);
80735   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
80736   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
80737   sqlite3ReleaseTempReg(pParse, r1);
80738 }
80739
80740 /*
80741 ** Generate an error message when a SELECT is used within a subexpression
80742 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
80743 ** column.  We do this in a subroutine because the error occurs in multiple
80744 ** places.
80745 */
80746 static int checkForMultiColumnSelectError(
80747   Parse *pParse,       /* Parse context. */
80748   SelectDest *pDest,   /* Destination of SELECT results */
80749   int nExpr            /* Number of result columns returned by SELECT */
80750 ){
80751   int eDest = pDest->eDest;
80752   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
80753     sqlite3ErrorMsg(pParse, "only a single result allowed for "
80754        "a SELECT that is part of an expression");
80755     return 1;
80756   }else{
80757     return 0;
80758   }
80759 }
80760
80761 /*
80762 ** This routine generates the code for the inside of the inner loop
80763 ** of a SELECT.
80764 **
80765 ** If srcTab and nColumn are both zero, then the pEList expressions
80766 ** are evaluated in order to get the data for this row.  If nColumn>0
80767 ** then data is pulled from srcTab and pEList is used only to get the
80768 ** datatypes for each column.
80769 */
80770 static void selectInnerLoop(
80771   Parse *pParse,          /* The parser context */
80772   Select *p,              /* The complete select statement being coded */
80773   ExprList *pEList,       /* List of values being extracted */
80774   int srcTab,             /* Pull data from this table */
80775   int nColumn,            /* Number of columns in the source table */
80776   ExprList *pOrderBy,     /* If not NULL, sort results using this key */
80777   int distinct,           /* If >=0, make sure results are distinct */
80778   SelectDest *pDest,      /* How to dispose of the results */
80779   int iContinue,          /* Jump here to continue with next row */
80780   int iBreak              /* Jump here to break out of the inner loop */
80781 ){
80782   Vdbe *v = pParse->pVdbe;
80783   int i;
80784   int hasDistinct;        /* True if the DISTINCT keyword is present */
80785   int regResult;              /* Start of memory holding result set */
80786   int eDest = pDest->eDest;   /* How to dispose of results */
80787   int iParm = pDest->iParm;   /* First argument to disposal method */
80788   int nResultCol;             /* Number of result columns */
80789
80790   assert( v );
80791   if( NEVER(v==0) ) return;
80792   assert( pEList!=0 );
80793   hasDistinct = distinct>=0;
80794   if( pOrderBy==0 && !hasDistinct ){
80795     codeOffset(v, p, iContinue);
80796   }
80797
80798   /* Pull the requested columns.
80799   */
80800   if( nColumn>0 ){
80801     nResultCol = nColumn;
80802   }else{
80803     nResultCol = pEList->nExpr;
80804   }
80805   if( pDest->iMem==0 ){
80806     pDest->iMem = pParse->nMem+1;
80807     pDest->nMem = nResultCol;
80808     pParse->nMem += nResultCol;
80809   }else{ 
80810     assert( pDest->nMem==nResultCol );
80811   }
80812   regResult = pDest->iMem;
80813   if( nColumn>0 ){
80814     for(i=0; i<nColumn; i++){
80815       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
80816     }
80817   }else if( eDest!=SRT_Exists ){
80818     /* If the destination is an EXISTS(...) expression, the actual
80819     ** values returned by the SELECT are not required.
80820     */
80821     sqlite3ExprCacheClear(pParse);
80822     sqlite3ExprCodeExprList(pParse, pEList, regResult, eDest==SRT_Output);
80823   }
80824   nColumn = nResultCol;
80825
80826   /* If the DISTINCT keyword was present on the SELECT statement
80827   ** and this row has been seen before, then do not make this row
80828   ** part of the result.
80829   */
80830   if( hasDistinct ){
80831     assert( pEList!=0 );
80832     assert( pEList->nExpr==nColumn );
80833     codeDistinct(pParse, distinct, iContinue, nColumn, regResult);
80834     if( pOrderBy==0 ){
80835       codeOffset(v, p, iContinue);
80836     }
80837   }
80838
80839   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
80840     return;
80841   }
80842
80843   switch( eDest ){
80844     /* In this mode, write each query result to the key of the temporary
80845     ** table iParm.
80846     */
80847 #ifndef SQLITE_OMIT_COMPOUND_SELECT
80848     case SRT_Union: {
80849       int r1;
80850       r1 = sqlite3GetTempReg(pParse);
80851       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
80852       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
80853       sqlite3ReleaseTempReg(pParse, r1);
80854       break;
80855     }
80856
80857     /* Construct a record from the query result, but instead of
80858     ** saving that record, use it as a key to delete elements from
80859     ** the temporary table iParm.
80860     */
80861     case SRT_Except: {
80862       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nColumn);
80863       break;
80864     }
80865 #endif
80866
80867     /* Store the result as data using a unique key.
80868     */
80869     case SRT_Table:
80870     case SRT_EphemTab: {
80871       int r1 = sqlite3GetTempReg(pParse);
80872       testcase( eDest==SRT_Table );
80873       testcase( eDest==SRT_EphemTab );
80874       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
80875       if( pOrderBy ){
80876         pushOntoSorter(pParse, pOrderBy, p, r1);
80877       }else{
80878         int r2 = sqlite3GetTempReg(pParse);
80879         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
80880         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
80881         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
80882         sqlite3ReleaseTempReg(pParse, r2);
80883       }
80884       sqlite3ReleaseTempReg(pParse, r1);
80885       break;
80886     }
80887
80888 #ifndef SQLITE_OMIT_SUBQUERY
80889     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
80890     ** then there should be a single item on the stack.  Write this
80891     ** item into the set table with bogus data.
80892     */
80893     case SRT_Set: {
80894       assert( nColumn==1 );
80895       p->affinity = sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affinity);
80896       if( pOrderBy ){
80897         /* At first glance you would think we could optimize out the
80898         ** ORDER BY in this case since the order of entries in the set
80899         ** does not matter.  But there might be a LIMIT clause, in which
80900         ** case the order does matter */
80901         pushOntoSorter(pParse, pOrderBy, p, regResult);
80902       }else{
80903         int r1 = sqlite3GetTempReg(pParse);
80904         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, 1, r1, &p->affinity, 1);
80905         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
80906         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
80907         sqlite3ReleaseTempReg(pParse, r1);
80908       }
80909       break;
80910     }
80911
80912     /* If any row exist in the result set, record that fact and abort.
80913     */
80914     case SRT_Exists: {
80915       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
80916       /* The LIMIT clause will terminate the loop for us */
80917       break;
80918     }
80919
80920     /* If this is a scalar select that is part of an expression, then
80921     ** store the results in the appropriate memory cell and break out
80922     ** of the scan loop.
80923     */
80924     case SRT_Mem: {
80925       assert( nColumn==1 );
80926       if( pOrderBy ){
80927         pushOntoSorter(pParse, pOrderBy, p, regResult);
80928       }else{
80929         sqlite3ExprCodeMove(pParse, regResult, iParm, 1);
80930         /* The LIMIT clause will jump out of the loop for us */
80931       }
80932       break;
80933     }
80934 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
80935
80936     /* Send the data to the callback function or to a subroutine.  In the
80937     ** case of a subroutine, the subroutine itself is responsible for
80938     ** popping the data from the stack.
80939     */
80940     case SRT_Coroutine:
80941     case SRT_Output: {
80942       testcase( eDest==SRT_Coroutine );
80943       testcase( eDest==SRT_Output );
80944       if( pOrderBy ){
80945         int r1 = sqlite3GetTempReg(pParse);
80946         sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nColumn, r1);
80947         pushOntoSorter(pParse, pOrderBy, p, r1);
80948         sqlite3ReleaseTempReg(pParse, r1);
80949       }else if( eDest==SRT_Coroutine ){
80950         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
80951       }else{
80952         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nColumn);
80953         sqlite3ExprCacheAffinityChange(pParse, regResult, nColumn);
80954       }
80955       break;
80956     }
80957
80958 #if !defined(SQLITE_OMIT_TRIGGER)
80959     /* Discard the results.  This is used for SELECT statements inside
80960     ** the body of a TRIGGER.  The purpose of such selects is to call
80961     ** user-defined functions that have side effects.  We do not care
80962     ** about the actual results of the select.
80963     */
80964     default: {
80965       assert( eDest==SRT_Discard );
80966       break;
80967     }
80968 #endif
80969   }
80970
80971   /* Jump to the end of the loop if the LIMIT is reached.
80972   */
80973   if( p->iLimit ){
80974     assert( pOrderBy==0 );  /* If there is an ORDER BY, the call to
80975                             ** pushOntoSorter() would have cleared p->iLimit */
80976     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
80977   }
80978 }
80979
80980 /*
80981 ** Given an expression list, generate a KeyInfo structure that records
80982 ** the collating sequence for each expression in that expression list.
80983 **
80984 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
80985 ** KeyInfo structure is appropriate for initializing a virtual index to
80986 ** implement that clause.  If the ExprList is the result set of a SELECT
80987 ** then the KeyInfo structure is appropriate for initializing a virtual
80988 ** index to implement a DISTINCT test.
80989 **
80990 ** Space to hold the KeyInfo structure is obtain from malloc.  The calling
80991 ** function is responsible for seeing that this structure is eventually
80992 ** freed.  Add the KeyInfo structure to the P4 field of an opcode using
80993 ** P4_KEYINFO_HANDOFF is the usual way of dealing with this.
80994 */
80995 static KeyInfo *keyInfoFromExprList(Parse *pParse, ExprList *pList){
80996   sqlite3 *db = pParse->db;
80997   int nExpr;
80998   KeyInfo *pInfo;
80999   struct ExprList_item *pItem;
81000   int i;
81001
81002   nExpr = pList->nExpr;
81003   pInfo = sqlite3DbMallocZero(db, sizeof(*pInfo) + nExpr*(sizeof(CollSeq*)+1) );
81004   if( pInfo ){
81005     pInfo->aSortOrder = (u8*)&pInfo->aColl[nExpr];
81006     pInfo->nField = (u16)nExpr;
81007     pInfo->enc = ENC(db);
81008     pInfo->db = db;
81009     for(i=0, pItem=pList->a; i<nExpr; i++, pItem++){
81010       CollSeq *pColl;
81011       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
81012       if( !pColl ){
81013         pColl = db->pDfltColl;
81014       }
81015       pInfo->aColl[i] = pColl;
81016       pInfo->aSortOrder[i] = pItem->sortOrder;
81017     }
81018   }
81019   return pInfo;
81020 }
81021
81022
81023 /*
81024 ** If the inner loop was generated using a non-null pOrderBy argument,
81025 ** then the results were placed in a sorter.  After the loop is terminated
81026 ** we need to run the sorter and output the results.  The following
81027 ** routine generates the code needed to do that.
81028 */
81029 static void generateSortTail(
81030   Parse *pParse,    /* Parsing context */
81031   Select *p,        /* The SELECT statement */
81032   Vdbe *v,          /* Generate code into this VDBE */
81033   int nColumn,      /* Number of columns of data */
81034   SelectDest *pDest /* Write the sorted results here */
81035 ){
81036   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
81037   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
81038   int addr;
81039   int iTab;
81040   int pseudoTab = 0;
81041   ExprList *pOrderBy = p->pOrderBy;
81042
81043   int eDest = pDest->eDest;
81044   int iParm = pDest->iParm;
81045
81046   int regRow;
81047   int regRowid;
81048
81049   iTab = pOrderBy->iECursor;
81050   regRow = sqlite3GetTempReg(pParse);
81051   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
81052     pseudoTab = pParse->nTab++;
81053     sqlite3VdbeAddOp3(v, OP_OpenPseudo, pseudoTab, regRow, nColumn);
81054     regRowid = 0;
81055   }else{
81056     regRowid = sqlite3GetTempReg(pParse);
81057   }
81058   addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak);
81059   codeOffset(v, p, addrContinue);
81060   sqlite3VdbeAddOp3(v, OP_Column, iTab, pOrderBy->nExpr + 1, regRow);
81061   switch( eDest ){
81062     case SRT_Table:
81063     case SRT_EphemTab: {
81064       testcase( eDest==SRT_Table );
81065       testcase( eDest==SRT_EphemTab );
81066       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
81067       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
81068       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
81069       break;
81070     }
81071 #ifndef SQLITE_OMIT_SUBQUERY
81072     case SRT_Set: {
81073       assert( nColumn==1 );
81074       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid, &p->affinity, 1);
81075       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
81076       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
81077       break;
81078     }
81079     case SRT_Mem: {
81080       assert( nColumn==1 );
81081       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
81082       /* The LIMIT clause will terminate the loop for us */
81083       break;
81084     }
81085 #endif
81086     default: {
81087       int i;
81088       assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
81089       testcase( eDest==SRT_Output );
81090       testcase( eDest==SRT_Coroutine );
81091       for(i=0; i<nColumn; i++){
81092         assert( regRow!=pDest->iMem+i );
81093         sqlite3VdbeAddOp3(v, OP_Column, pseudoTab, i, pDest->iMem+i);
81094         if( i==0 ){
81095           sqlite3VdbeChangeP5(v, OPFLAG_CLEARCACHE);
81096         }
81097       }
81098       if( eDest==SRT_Output ){
81099         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iMem, nColumn);
81100         sqlite3ExprCacheAffinityChange(pParse, pDest->iMem, nColumn);
81101       }else{
81102         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
81103       }
81104       break;
81105     }
81106   }
81107   sqlite3ReleaseTempReg(pParse, regRow);
81108   sqlite3ReleaseTempReg(pParse, regRowid);
81109
81110   /* LIMIT has been implemented by the pushOntoSorter() routine.
81111   */
81112   assert( p->iLimit==0 );
81113
81114   /* The bottom of the loop
81115   */
81116   sqlite3VdbeResolveLabel(v, addrContinue);
81117   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr);
81118   sqlite3VdbeResolveLabel(v, addrBreak);
81119   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
81120     sqlite3VdbeAddOp2(v, OP_Close, pseudoTab, 0);
81121   }
81122 }
81123
81124 /*
81125 ** Return a pointer to a string containing the 'declaration type' of the
81126 ** expression pExpr. The string may be treated as static by the caller.
81127 **
81128 ** The declaration type is the exact datatype definition extracted from the
81129 ** original CREATE TABLE statement if the expression is a column. The
81130 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
81131 ** is considered a column can be complex in the presence of subqueries. The
81132 ** result-set expression in all of the following SELECT statements is 
81133 ** considered a column by this function.
81134 **
81135 **   SELECT col FROM tbl;
81136 **   SELECT (SELECT col FROM tbl;
81137 **   SELECT (SELECT col FROM tbl);
81138 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
81139 ** 
81140 ** The declaration type for any expression other than a column is NULL.
81141 */
81142 static const char *columnType(
81143   NameContext *pNC, 
81144   Expr *pExpr,
81145   const char **pzOriginDb,
81146   const char **pzOriginTab,
81147   const char **pzOriginCol
81148 ){
81149   char const *zType = 0;
81150   char const *zOriginDb = 0;
81151   char const *zOriginTab = 0;
81152   char const *zOriginCol = 0;
81153   int j;
81154   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
81155
81156   switch( pExpr->op ){
81157     case TK_AGG_COLUMN:
81158     case TK_COLUMN: {
81159       /* The expression is a column. Locate the table the column is being
81160       ** extracted from in NameContext.pSrcList. This table may be real
81161       ** database table or a subquery.
81162       */
81163       Table *pTab = 0;            /* Table structure column is extracted from */
81164       Select *pS = 0;             /* Select the column is extracted from */
81165       int iCol = pExpr->iColumn;  /* Index of column in pTab */
81166       testcase( pExpr->op==TK_AGG_COLUMN );
81167       testcase( pExpr->op==TK_COLUMN );
81168       while( pNC && !pTab ){
81169         SrcList *pTabList = pNC->pSrcList;
81170         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
81171         if( j<pTabList->nSrc ){
81172           pTab = pTabList->a[j].pTab;
81173           pS = pTabList->a[j].pSelect;
81174         }else{
81175           pNC = pNC->pNext;
81176         }
81177       }
81178
81179       if( pTab==0 ){
81180         /* At one time, code such as "SELECT new.x" within a trigger would
81181         ** cause this condition to run.  Since then, we have restructured how
81182         ** trigger code is generated and so this condition is no longer 
81183         ** possible. However, it can still be true for statements like
81184         ** the following:
81185         **
81186         **   CREATE TABLE t1(col INTEGER);
81187         **   SELECT (SELECT t1.col) FROM FROM t1;
81188         **
81189         ** when columnType() is called on the expression "t1.col" in the 
81190         ** sub-select. In this case, set the column type to NULL, even
81191         ** though it should really be "INTEGER".
81192         **
81193         ** This is not a problem, as the column type of "t1.col" is never
81194         ** used. When columnType() is called on the expression 
81195         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
81196         ** branch below.  */
81197         break;
81198       }
81199
81200       assert( pTab && pExpr->pTab==pTab );
81201       if( pS ){
81202         /* The "table" is actually a sub-select or a view in the FROM clause
81203         ** of the SELECT statement. Return the declaration type and origin
81204         ** data for the result-set column of the sub-select.
81205         */
81206         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
81207           /* If iCol is less than zero, then the expression requests the
81208           ** rowid of the sub-select or view. This expression is legal (see 
81209           ** test case misc2.2.2) - it always evaluates to NULL.
81210           */
81211           NameContext sNC;
81212           Expr *p = pS->pEList->a[iCol].pExpr;
81213           sNC.pSrcList = pS->pSrc;
81214           sNC.pNext = pNC;
81215           sNC.pParse = pNC->pParse;
81216           zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
81217         }
81218       }else if( ALWAYS(pTab->pSchema) ){
81219         /* A real table */
81220         assert( !pS );
81221         if( iCol<0 ) iCol = pTab->iPKey;
81222         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
81223         if( iCol<0 ){
81224           zType = "INTEGER";
81225           zOriginCol = "rowid";
81226         }else{
81227           zType = pTab->aCol[iCol].zType;
81228           zOriginCol = pTab->aCol[iCol].zName;
81229         }
81230         zOriginTab = pTab->zName;
81231         if( pNC->pParse ){
81232           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
81233           zOriginDb = pNC->pParse->db->aDb[iDb].zName;
81234         }
81235       }
81236       break;
81237     }
81238 #ifndef SQLITE_OMIT_SUBQUERY
81239     case TK_SELECT: {
81240       /* The expression is a sub-select. Return the declaration type and
81241       ** origin info for the single column in the result set of the SELECT
81242       ** statement.
81243       */
81244       NameContext sNC;
81245       Select *pS = pExpr->x.pSelect;
81246       Expr *p = pS->pEList->a[0].pExpr;
81247       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
81248       sNC.pSrcList = pS->pSrc;
81249       sNC.pNext = pNC;
81250       sNC.pParse = pNC->pParse;
81251       zType = columnType(&sNC, p, &zOriginDb, &zOriginTab, &zOriginCol); 
81252       break;
81253     }
81254 #endif
81255   }
81256   
81257   if( pzOriginDb ){
81258     assert( pzOriginTab && pzOriginCol );
81259     *pzOriginDb = zOriginDb;
81260     *pzOriginTab = zOriginTab;
81261     *pzOriginCol = zOriginCol;
81262   }
81263   return zType;
81264 }
81265
81266 /*
81267 ** Generate code that will tell the VDBE the declaration types of columns
81268 ** in the result set.
81269 */
81270 static void generateColumnTypes(
81271   Parse *pParse,      /* Parser context */
81272   SrcList *pTabList,  /* List of tables */
81273   ExprList *pEList    /* Expressions defining the result set */
81274 ){
81275 #ifndef SQLITE_OMIT_DECLTYPE
81276   Vdbe *v = pParse->pVdbe;
81277   int i;
81278   NameContext sNC;
81279   sNC.pSrcList = pTabList;
81280   sNC.pParse = pParse;
81281   for(i=0; i<pEList->nExpr; i++){
81282     Expr *p = pEList->a[i].pExpr;
81283     const char *zType;
81284 #ifdef SQLITE_ENABLE_COLUMN_METADATA
81285     const char *zOrigDb = 0;
81286     const char *zOrigTab = 0;
81287     const char *zOrigCol = 0;
81288     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
81289
81290     /* The vdbe must make its own copy of the column-type and other 
81291     ** column specific strings, in case the schema is reset before this
81292     ** virtual machine is deleted.
81293     */
81294     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
81295     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
81296     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
81297 #else
81298     zType = columnType(&sNC, p, 0, 0, 0);
81299 #endif
81300     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
81301   }
81302 #endif /* SQLITE_OMIT_DECLTYPE */
81303 }
81304
81305 /*
81306 ** Generate code that will tell the VDBE the names of columns
81307 ** in the result set.  This information is used to provide the
81308 ** azCol[] values in the callback.
81309 */
81310 static void generateColumnNames(
81311   Parse *pParse,      /* Parser context */
81312   SrcList *pTabList,  /* List of tables */
81313   ExprList *pEList    /* Expressions defining the result set */
81314 ){
81315   Vdbe *v = pParse->pVdbe;
81316   int i, j;
81317   sqlite3 *db = pParse->db;
81318   int fullNames, shortNames;
81319
81320 #ifndef SQLITE_OMIT_EXPLAIN
81321   /* If this is an EXPLAIN, skip this step */
81322   if( pParse->explain ){
81323     return;
81324   }
81325 #endif
81326
81327   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
81328   pParse->colNamesSet = 1;
81329   fullNames = (db->flags & SQLITE_FullColNames)!=0;
81330   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
81331   sqlite3VdbeSetNumCols(v, pEList->nExpr);
81332   for(i=0; i<pEList->nExpr; i++){
81333     Expr *p;
81334     p = pEList->a[i].pExpr;
81335     if( NEVER(p==0) ) continue;
81336     if( pEList->a[i].zName ){
81337       char *zName = pEList->a[i].zName;
81338       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
81339     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
81340       Table *pTab;
81341       char *zCol;
81342       int iCol = p->iColumn;
81343       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
81344         if( pTabList->a[j].iCursor==p->iTable ) break;
81345       }
81346       assert( j<pTabList->nSrc );
81347       pTab = pTabList->a[j].pTab;
81348       if( iCol<0 ) iCol = pTab->iPKey;
81349       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
81350       if( iCol<0 ){
81351         zCol = "rowid";
81352       }else{
81353         zCol = pTab->aCol[iCol].zName;
81354       }
81355       if( !shortNames && !fullNames ){
81356         sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
81357             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
81358       }else if( fullNames ){
81359         char *zName = 0;
81360         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
81361         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
81362       }else{
81363         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
81364       }
81365     }else{
81366       sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
81367           sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
81368     }
81369   }
81370   generateColumnTypes(pParse, pTabList, pEList);
81371 }
81372
81373 #ifndef SQLITE_OMIT_COMPOUND_SELECT
81374 /*
81375 ** Name of the connection operator, used for error messages.
81376 */
81377 static const char *selectOpName(int id){
81378   char *z;
81379   switch( id ){
81380     case TK_ALL:       z = "UNION ALL";   break;
81381     case TK_INTERSECT: z = "INTERSECT";   break;
81382     case TK_EXCEPT:    z = "EXCEPT";      break;
81383     default:           z = "UNION";       break;
81384   }
81385   return z;
81386 }
81387 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
81388
81389 /*
81390 ** Given a an expression list (which is really the list of expressions
81391 ** that form the result set of a SELECT statement) compute appropriate
81392 ** column names for a table that would hold the expression list.
81393 **
81394 ** All column names will be unique.
81395 **
81396 ** Only the column names are computed.  Column.zType, Column.zColl,
81397 ** and other fields of Column are zeroed.
81398 **
81399 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
81400 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
81401 */
81402 static int selectColumnsFromExprList(
81403   Parse *pParse,          /* Parsing context */
81404   ExprList *pEList,       /* Expr list from which to derive column names */
81405   int *pnCol,             /* Write the number of columns here */
81406   Column **paCol          /* Write the new column list here */
81407 ){
81408   sqlite3 *db = pParse->db;   /* Database connection */
81409   int i, j;                   /* Loop counters */
81410   int cnt;                    /* Index added to make the name unique */
81411   Column *aCol, *pCol;        /* For looping over result columns */
81412   int nCol;                   /* Number of columns in the result set */
81413   Expr *p;                    /* Expression for a single result column */
81414   char *zName;                /* Column name */
81415   int nName;                  /* Size of name in zName[] */
81416
81417   *pnCol = nCol = pEList->nExpr;
81418   aCol = *paCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
81419   if( aCol==0 ) return SQLITE_NOMEM;
81420   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
81421     /* Get an appropriate name for the column
81422     */
81423     p = pEList->a[i].pExpr;
81424     assert( p->pRight==0 || ExprHasProperty(p->pRight, EP_IntValue)
81425                || p->pRight->u.zToken==0 || p->pRight->u.zToken[0]!=0 );
81426     if( (zName = pEList->a[i].zName)!=0 ){
81427       /* If the column contains an "AS <name>" phrase, use <name> as the name */
81428       zName = sqlite3DbStrDup(db, zName);
81429     }else{
81430       Expr *pColExpr = p;  /* The expression that is the result column name */
81431       Table *pTab;         /* Table associated with this expression */
81432       while( pColExpr->op==TK_DOT ) pColExpr = pColExpr->pRight;
81433       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
81434         /* For columns use the column name name */
81435         int iCol = pColExpr->iColumn;
81436         pTab = pColExpr->pTab;
81437         if( iCol<0 ) iCol = pTab->iPKey;
81438         zName = sqlite3MPrintf(db, "%s",
81439                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
81440       }else if( pColExpr->op==TK_ID ){
81441         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
81442         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
81443       }else{
81444         /* Use the original text of the column expression as its name */
81445         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
81446       }
81447     }
81448     if( db->mallocFailed ){
81449       sqlite3DbFree(db, zName);
81450       break;
81451     }
81452
81453     /* Make sure the column name is unique.  If the name is not unique,
81454     ** append a integer to the name so that it becomes unique.
81455     */
81456     nName = sqlite3Strlen30(zName);
81457     for(j=cnt=0; j<i; j++){
81458       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
81459         char *zNewName;
81460         zName[nName] = 0;
81461         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
81462         sqlite3DbFree(db, zName);
81463         zName = zNewName;
81464         j = -1;
81465         if( zName==0 ) break;
81466       }
81467     }
81468     pCol->zName = zName;
81469   }
81470   if( db->mallocFailed ){
81471     for(j=0; j<i; j++){
81472       sqlite3DbFree(db, aCol[j].zName);
81473     }
81474     sqlite3DbFree(db, aCol);
81475     *paCol = 0;
81476     *pnCol = 0;
81477     return SQLITE_NOMEM;
81478   }
81479   return SQLITE_OK;
81480 }
81481
81482 /*
81483 ** Add type and collation information to a column list based on
81484 ** a SELECT statement.
81485 ** 
81486 ** The column list presumably came from selectColumnNamesFromExprList().
81487 ** The column list has only names, not types or collations.  This
81488 ** routine goes through and adds the types and collations.
81489 **
81490 ** This routine requires that all identifiers in the SELECT
81491 ** statement be resolved.
81492 */
81493 static void selectAddColumnTypeAndCollation(
81494   Parse *pParse,        /* Parsing contexts */
81495   int nCol,             /* Number of columns */
81496   Column *aCol,         /* List of columns */
81497   Select *pSelect       /* SELECT used to determine types and collations */
81498 ){
81499   sqlite3 *db = pParse->db;
81500   NameContext sNC;
81501   Column *pCol;
81502   CollSeq *pColl;
81503   int i;
81504   Expr *p;
81505   struct ExprList_item *a;
81506
81507   assert( pSelect!=0 );
81508   assert( (pSelect->selFlags & SF_Resolved)!=0 );
81509   assert( nCol==pSelect->pEList->nExpr || db->mallocFailed );
81510   if( db->mallocFailed ) return;
81511   memset(&sNC, 0, sizeof(sNC));
81512   sNC.pSrcList = pSelect->pSrc;
81513   a = pSelect->pEList->a;
81514   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
81515     p = a[i].pExpr;
81516     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p, 0, 0, 0));
81517     pCol->affinity = sqlite3ExprAffinity(p);
81518     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
81519     pColl = sqlite3ExprCollSeq(pParse, p);
81520     if( pColl ){
81521       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
81522     }
81523   }
81524 }
81525
81526 /*
81527 ** Given a SELECT statement, generate a Table structure that describes
81528 ** the result set of that SELECT.
81529 */
81530 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
81531   Table *pTab;
81532   sqlite3 *db = pParse->db;
81533   int savedFlags;
81534
81535   savedFlags = db->flags;
81536   db->flags &= ~SQLITE_FullColNames;
81537   db->flags |= SQLITE_ShortColNames;
81538   sqlite3SelectPrep(pParse, pSelect, 0);
81539   if( pParse->nErr ) return 0;
81540   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
81541   db->flags = savedFlags;
81542   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
81543   if( pTab==0 ){
81544     return 0;
81545   }
81546   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
81547   ** is disabled, so we might as well hard-code pTab->dbMem to NULL. */
81548   assert( db->lookaside.bEnabled==0 );
81549   pTab->dbMem = 0;
81550   pTab->nRef = 1;
81551   pTab->zName = 0;
81552   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
81553   selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSelect);
81554   pTab->iPKey = -1;
81555   if( db->mallocFailed ){
81556     sqlite3DeleteTable(pTab);
81557     return 0;
81558   }
81559   return pTab;
81560 }
81561
81562 /*
81563 ** Get a VDBE for the given parser context.  Create a new one if necessary.
81564 ** If an error occurs, return NULL and leave a message in pParse.
81565 */
81566 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
81567   Vdbe *v = pParse->pVdbe;
81568   if( v==0 ){
81569     v = pParse->pVdbe = sqlite3VdbeCreate(pParse->db);
81570 #ifndef SQLITE_OMIT_TRACE
81571     if( v ){
81572       sqlite3VdbeAddOp0(v, OP_Trace);
81573     }
81574 #endif
81575   }
81576   return v;
81577 }
81578
81579
81580 /*
81581 ** Compute the iLimit and iOffset fields of the SELECT based on the
81582 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
81583 ** that appear in the original SQL statement after the LIMIT and OFFSET
81584 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
81585 ** are the integer memory register numbers for counters used to compute 
81586 ** the limit and offset.  If there is no limit and/or offset, then 
81587 ** iLimit and iOffset are negative.
81588 **
81589 ** This routine changes the values of iLimit and iOffset only if
81590 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
81591 ** iOffset should have been preset to appropriate default values
81592 ** (usually but not always -1) prior to calling this routine.
81593 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
81594 ** redefined.  The UNION ALL operator uses this property to force
81595 ** the reuse of the same limit and offset registers across multiple
81596 ** SELECT statements.
81597 */
81598 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
81599   Vdbe *v = 0;
81600   int iLimit = 0;
81601   int iOffset;
81602   int addr1, n;
81603   if( p->iLimit ) return;
81604
81605   /* 
81606   ** "LIMIT -1" always shows all rows.  There is some
81607   ** contraversy about what the correct behavior should be.
81608   ** The current implementation interprets "LIMIT 0" to mean
81609   ** no rows.
81610   */
81611   sqlite3ExprCacheClear(pParse);
81612   assert( p->pOffset==0 || p->pLimit!=0 );
81613   if( p->pLimit ){
81614     p->iLimit = iLimit = ++pParse->nMem;
81615     v = sqlite3GetVdbe(pParse);
81616     if( NEVER(v==0) ) return;  /* VDBE should have already been allocated */
81617     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
81618       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
81619       VdbeComment((v, "LIMIT counter"));
81620       if( n==0 ){
81621         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
81622       }
81623     }else{
81624       sqlite3ExprCode(pParse, p->pLimit, iLimit);
81625       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit);
81626       VdbeComment((v, "LIMIT counter"));
81627       sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak);
81628     }
81629     if( p->pOffset ){
81630       p->iOffset = iOffset = ++pParse->nMem;
81631       pParse->nMem++;   /* Allocate an extra register for limit+offset */
81632       sqlite3ExprCode(pParse, p->pOffset, iOffset);
81633       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset);
81634       VdbeComment((v, "OFFSET counter"));
81635       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset);
81636       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
81637       sqlite3VdbeJumpHere(v, addr1);
81638       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
81639       VdbeComment((v, "LIMIT+OFFSET"));
81640       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit);
81641       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
81642       sqlite3VdbeJumpHere(v, addr1);
81643     }
81644   }
81645 }
81646
81647 #ifndef SQLITE_OMIT_COMPOUND_SELECT
81648 /*
81649 ** Return the appropriate collating sequence for the iCol-th column of
81650 ** the result set for the compound-select statement "p".  Return NULL if
81651 ** the column has no default collating sequence.
81652 **
81653 ** The collating sequence for the compound select is taken from the
81654 ** left-most term of the select that has a collating sequence.
81655 */
81656 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
81657   CollSeq *pRet;
81658   if( p->pPrior ){
81659     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
81660   }else{
81661     pRet = 0;
81662   }
81663   assert( iCol>=0 );
81664   if( pRet==0 && iCol<p->pEList->nExpr ){
81665     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
81666   }
81667   return pRet;
81668 }
81669 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
81670
81671 /* Forward reference */
81672 static int multiSelectOrderBy(
81673   Parse *pParse,        /* Parsing context */
81674   Select *p,            /* The right-most of SELECTs to be coded */
81675   SelectDest *pDest     /* What to do with query results */
81676 );
81677
81678
81679 #ifndef SQLITE_OMIT_COMPOUND_SELECT
81680 /*
81681 ** This routine is called to process a compound query form from
81682 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
81683 ** INTERSECT
81684 **
81685 ** "p" points to the right-most of the two queries.  the query on the
81686 ** left is p->pPrior.  The left query could also be a compound query
81687 ** in which case this routine will be called recursively. 
81688 **
81689 ** The results of the total query are to be written into a destination
81690 ** of type eDest with parameter iParm.
81691 **
81692 ** Example 1:  Consider a three-way compound SQL statement.
81693 **
81694 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
81695 **
81696 ** This statement is parsed up as follows:
81697 **
81698 **     SELECT c FROM t3
81699 **      |
81700 **      `----->  SELECT b FROM t2
81701 **                |
81702 **                `------>  SELECT a FROM t1
81703 **
81704 ** The arrows in the diagram above represent the Select.pPrior pointer.
81705 ** So if this routine is called with p equal to the t3 query, then
81706 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
81707 **
81708 ** Notice that because of the way SQLite parses compound SELECTs, the
81709 ** individual selects always group from left to right.
81710 */
81711 static int multiSelect(
81712   Parse *pParse,        /* Parsing context */
81713   Select *p,            /* The right-most of SELECTs to be coded */
81714   SelectDest *pDest     /* What to do with query results */
81715 ){
81716   int rc = SQLITE_OK;   /* Success code from a subroutine */
81717   Select *pPrior;       /* Another SELECT immediately to our left */
81718   Vdbe *v;              /* Generate code to this VDBE */
81719   SelectDest dest;      /* Alternative data destination */
81720   Select *pDelete = 0;  /* Chain of simple selects to delete */
81721   sqlite3 *db;          /* Database connection */
81722
81723   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
81724   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
81725   */
81726   assert( p && p->pPrior );  /* Calling function guarantees this much */
81727   db = pParse->db;
81728   pPrior = p->pPrior;
81729   assert( pPrior->pRightmost!=pPrior );
81730   assert( pPrior->pRightmost==p->pRightmost );
81731   dest = *pDest;
81732   if( pPrior->pOrderBy ){
81733     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
81734       selectOpName(p->op));
81735     rc = 1;
81736     goto multi_select_end;
81737   }
81738   if( pPrior->pLimit ){
81739     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
81740       selectOpName(p->op));
81741     rc = 1;
81742     goto multi_select_end;
81743   }
81744
81745   v = sqlite3GetVdbe(pParse);
81746   assert( v!=0 );  /* The VDBE already created by calling function */
81747
81748   /* Create the destination temporary table if necessary
81749   */
81750   if( dest.eDest==SRT_EphemTab ){
81751     assert( p->pEList );
81752     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iParm, p->pEList->nExpr);
81753     dest.eDest = SRT_Table;
81754   }
81755
81756   /* Make sure all SELECTs in the statement have the same number of elements
81757   ** in their result sets.
81758   */
81759   assert( p->pEList && pPrior->pEList );
81760   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
81761     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
81762       " do not have the same number of result columns", selectOpName(p->op));
81763     rc = 1;
81764     goto multi_select_end;
81765   }
81766
81767   /* Compound SELECTs that have an ORDER BY clause are handled separately.
81768   */
81769   if( p->pOrderBy ){
81770     return multiSelectOrderBy(pParse, p, pDest);
81771   }
81772
81773   /* Generate code for the left and right SELECT statements.
81774   */
81775   switch( p->op ){
81776     case TK_ALL: {
81777       int addr = 0;
81778       assert( !pPrior->pLimit );
81779       pPrior->pLimit = p->pLimit;
81780       pPrior->pOffset = p->pOffset;
81781       rc = sqlite3Select(pParse, pPrior, &dest);
81782       p->pLimit = 0;
81783       p->pOffset = 0;
81784       if( rc ){
81785         goto multi_select_end;
81786       }
81787       p->pPrior = 0;
81788       p->iLimit = pPrior->iLimit;
81789       p->iOffset = pPrior->iOffset;
81790       if( p->iLimit ){
81791         addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit);
81792         VdbeComment((v, "Jump ahead if LIMIT reached"));
81793       }
81794       rc = sqlite3Select(pParse, p, &dest);
81795       testcase( rc!=SQLITE_OK );
81796       pDelete = p->pPrior;
81797       p->pPrior = pPrior;
81798       if( addr ){
81799         sqlite3VdbeJumpHere(v, addr);
81800       }
81801       break;
81802     }
81803     case TK_EXCEPT:
81804     case TK_UNION: {
81805       int unionTab;    /* Cursor number of the temporary table holding result */
81806       u8 op = 0;       /* One of the SRT_ operations to apply to self */
81807       int priorOp;     /* The SRT_ operation to apply to prior selects */
81808       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
81809       int addr;
81810       SelectDest uniondest;
81811
81812       testcase( p->op==TK_EXCEPT );
81813       testcase( p->op==TK_UNION );
81814       priorOp = SRT_Union;
81815       if( dest.eDest==priorOp && ALWAYS(!p->pLimit &&!p->pOffset) ){
81816         /* We can reuse a temporary table generated by a SELECT to our
81817         ** right.
81818         */
81819         assert( p->pRightmost!=p );  /* Can only happen for leftward elements
81820                                      ** of a 3-way or more compound */
81821         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
81822         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
81823         unionTab = dest.iParm;
81824       }else{
81825         /* We will need to create our own temporary table to hold the
81826         ** intermediate results.
81827         */
81828         unionTab = pParse->nTab++;
81829         assert( p->pOrderBy==0 );
81830         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
81831         assert( p->addrOpenEphm[0] == -1 );
81832         p->addrOpenEphm[0] = addr;
81833         p->pRightmost->selFlags |= SF_UsesEphemeral;
81834         assert( p->pEList );
81835       }
81836
81837       /* Code the SELECT statements to our left
81838       */
81839       assert( !pPrior->pOrderBy );
81840       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
81841       rc = sqlite3Select(pParse, pPrior, &uniondest);
81842       if( rc ){
81843         goto multi_select_end;
81844       }
81845
81846       /* Code the current SELECT statement
81847       */
81848       if( p->op==TK_EXCEPT ){
81849         op = SRT_Except;
81850       }else{
81851         assert( p->op==TK_UNION );
81852         op = SRT_Union;
81853       }
81854       p->pPrior = 0;
81855       pLimit = p->pLimit;
81856       p->pLimit = 0;
81857       pOffset = p->pOffset;
81858       p->pOffset = 0;
81859       uniondest.eDest = op;
81860       rc = sqlite3Select(pParse, p, &uniondest);
81861       testcase( rc!=SQLITE_OK );
81862       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
81863       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
81864       sqlite3ExprListDelete(db, p->pOrderBy);
81865       pDelete = p->pPrior;
81866       p->pPrior = pPrior;
81867       p->pOrderBy = 0;
81868       sqlite3ExprDelete(db, p->pLimit);
81869       p->pLimit = pLimit;
81870       p->pOffset = pOffset;
81871       p->iLimit = 0;
81872       p->iOffset = 0;
81873
81874       /* Convert the data in the temporary table into whatever form
81875       ** it is that we currently need.
81876       */
81877       assert( unionTab==dest.iParm || dest.eDest!=priorOp );
81878       if( dest.eDest!=priorOp ){
81879         int iCont, iBreak, iStart;
81880         assert( p->pEList );
81881         if( dest.eDest==SRT_Output ){
81882           Select *pFirst = p;
81883           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
81884           generateColumnNames(pParse, 0, pFirst->pEList);
81885         }
81886         iBreak = sqlite3VdbeMakeLabel(v);
81887         iCont = sqlite3VdbeMakeLabel(v);
81888         computeLimitRegisters(pParse, p, iBreak);
81889         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak);
81890         iStart = sqlite3VdbeCurrentAddr(v);
81891         selectInnerLoop(pParse, p, p->pEList, unionTab, p->pEList->nExpr,
81892                         0, -1, &dest, iCont, iBreak);
81893         sqlite3VdbeResolveLabel(v, iCont);
81894         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart);
81895         sqlite3VdbeResolveLabel(v, iBreak);
81896         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
81897       }
81898       break;
81899     }
81900     default: assert( p->op==TK_INTERSECT ); {
81901       int tab1, tab2;
81902       int iCont, iBreak, iStart;
81903       Expr *pLimit, *pOffset;
81904       int addr;
81905       SelectDest intersectdest;
81906       int r1;
81907
81908       /* INTERSECT is different from the others since it requires
81909       ** two temporary tables.  Hence it has its own case.  Begin
81910       ** by allocating the tables we will need.
81911       */
81912       tab1 = pParse->nTab++;
81913       tab2 = pParse->nTab++;
81914       assert( p->pOrderBy==0 );
81915
81916       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
81917       assert( p->addrOpenEphm[0] == -1 );
81918       p->addrOpenEphm[0] = addr;
81919       p->pRightmost->selFlags |= SF_UsesEphemeral;
81920       assert( p->pEList );
81921
81922       /* Code the SELECTs to our left into temporary table "tab1".
81923       */
81924       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
81925       rc = sqlite3Select(pParse, pPrior, &intersectdest);
81926       if( rc ){
81927         goto multi_select_end;
81928       }
81929
81930       /* Code the current SELECT into temporary table "tab2"
81931       */
81932       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
81933       assert( p->addrOpenEphm[1] == -1 );
81934       p->addrOpenEphm[1] = addr;
81935       p->pPrior = 0;
81936       pLimit = p->pLimit;
81937       p->pLimit = 0;
81938       pOffset = p->pOffset;
81939       p->pOffset = 0;
81940       intersectdest.iParm = tab2;
81941       rc = sqlite3Select(pParse, p, &intersectdest);
81942       testcase( rc!=SQLITE_OK );
81943       pDelete = p->pPrior;
81944       p->pPrior = pPrior;
81945       sqlite3ExprDelete(db, p->pLimit);
81946       p->pLimit = pLimit;
81947       p->pOffset = pOffset;
81948
81949       /* Generate code to take the intersection of the two temporary
81950       ** tables.
81951       */
81952       assert( p->pEList );
81953       if( dest.eDest==SRT_Output ){
81954         Select *pFirst = p;
81955         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
81956         generateColumnNames(pParse, 0, pFirst->pEList);
81957       }
81958       iBreak = sqlite3VdbeMakeLabel(v);
81959       iCont = sqlite3VdbeMakeLabel(v);
81960       computeLimitRegisters(pParse, p, iBreak);
81961       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak);
81962       r1 = sqlite3GetTempReg(pParse);
81963       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
81964       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
81965       sqlite3ReleaseTempReg(pParse, r1);
81966       selectInnerLoop(pParse, p, p->pEList, tab1, p->pEList->nExpr,
81967                       0, -1, &dest, iCont, iBreak);
81968       sqlite3VdbeResolveLabel(v, iCont);
81969       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart);
81970       sqlite3VdbeResolveLabel(v, iBreak);
81971       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
81972       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
81973       break;
81974     }
81975   }
81976
81977   /* Compute collating sequences used by 
81978   ** temporary tables needed to implement the compound select.
81979   ** Attach the KeyInfo structure to all temporary tables.
81980   **
81981   ** This section is run by the right-most SELECT statement only.
81982   ** SELECT statements to the left always skip this part.  The right-most
81983   ** SELECT might also skip this part if it has no ORDER BY clause and
81984   ** no temp tables are required.
81985   */
81986   if( p->selFlags & SF_UsesEphemeral ){
81987     int i;                        /* Loop counter */
81988     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
81989     Select *pLoop;                /* For looping through SELECT statements */
81990     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
81991     int nCol;                     /* Number of columns in result set */
81992
81993     assert( p->pRightmost==p );
81994     nCol = p->pEList->nExpr;
81995     pKeyInfo = sqlite3DbMallocZero(db,
81996                        sizeof(*pKeyInfo)+nCol*(sizeof(CollSeq*) + 1));
81997     if( !pKeyInfo ){
81998       rc = SQLITE_NOMEM;
81999       goto multi_select_end;
82000     }
82001
82002     pKeyInfo->enc = ENC(db);
82003     pKeyInfo->nField = (u16)nCol;
82004
82005     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
82006       *apColl = multiSelectCollSeq(pParse, p, i);
82007       if( 0==*apColl ){
82008         *apColl = db->pDfltColl;
82009       }
82010     }
82011
82012     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
82013       for(i=0; i<2; i++){
82014         int addr = pLoop->addrOpenEphm[i];
82015         if( addr<0 ){
82016           /* If [0] is unused then [1] is also unused.  So we can
82017           ** always safely abort as soon as the first unused slot is found */
82018           assert( pLoop->addrOpenEphm[1]<0 );
82019           break;
82020         }
82021         sqlite3VdbeChangeP2(v, addr, nCol);
82022         sqlite3VdbeChangeP4(v, addr, (char*)pKeyInfo, P4_KEYINFO);
82023         pLoop->addrOpenEphm[i] = -1;
82024       }
82025     }
82026     sqlite3DbFree(db, pKeyInfo);
82027   }
82028
82029 multi_select_end:
82030   pDest->iMem = dest.iMem;
82031   pDest->nMem = dest.nMem;
82032   sqlite3SelectDelete(db, pDelete);
82033   return rc;
82034 }
82035 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
82036
82037 /*
82038 ** Code an output subroutine for a coroutine implementation of a
82039 ** SELECT statment.
82040 **
82041 ** The data to be output is contained in pIn->iMem.  There are
82042 ** pIn->nMem columns to be output.  pDest is where the output should
82043 ** be sent.
82044 **
82045 ** regReturn is the number of the register holding the subroutine
82046 ** return address.
82047 **
82048 ** If regPrev>0 then it is a the first register in a vector that
82049 ** records the previous output.  mem[regPrev] is a flag that is false
82050 ** if there has been no previous output.  If regPrev>0 then code is
82051 ** generated to suppress duplicates.  pKeyInfo is used for comparing
82052 ** keys.
82053 **
82054 ** If the LIMIT found in p->iLimit is reached, jump immediately to
82055 ** iBreak.
82056 */
82057 static int generateOutputSubroutine(
82058   Parse *pParse,          /* Parsing context */
82059   Select *p,              /* The SELECT statement */
82060   SelectDest *pIn,        /* Coroutine supplying data */
82061   SelectDest *pDest,      /* Where to send the data */
82062   int regReturn,          /* The return address register */
82063   int regPrev,            /* Previous result register.  No uniqueness if 0 */
82064   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
82065   int p4type,             /* The p4 type for pKeyInfo */
82066   int iBreak              /* Jump here if we hit the LIMIT */
82067 ){
82068   Vdbe *v = pParse->pVdbe;
82069   int iContinue;
82070   int addr;
82071
82072   addr = sqlite3VdbeCurrentAddr(v);
82073   iContinue = sqlite3VdbeMakeLabel(v);
82074
82075   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
82076   */
82077   if( regPrev ){
82078     int j1, j2;
82079     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev);
82080     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iMem, regPrev+1, pIn->nMem,
82081                               (char*)pKeyInfo, p4type);
82082     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2);
82083     sqlite3VdbeJumpHere(v, j1);
82084     sqlite3ExprCodeCopy(pParse, pIn->iMem, regPrev+1, pIn->nMem);
82085     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
82086   }
82087   if( pParse->db->mallocFailed ) return 0;
82088
82089   /* Suppress the the first OFFSET entries if there is an OFFSET clause
82090   */
82091   codeOffset(v, p, iContinue);
82092
82093   switch( pDest->eDest ){
82094     /* Store the result as data using a unique key.
82095     */
82096     case SRT_Table:
82097     case SRT_EphemTab: {
82098       int r1 = sqlite3GetTempReg(pParse);
82099       int r2 = sqlite3GetTempReg(pParse);
82100       testcase( pDest->eDest==SRT_Table );
82101       testcase( pDest->eDest==SRT_EphemTab );
82102       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iMem, pIn->nMem, r1);
82103       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iParm, r2);
82104       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iParm, r1, r2);
82105       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
82106       sqlite3ReleaseTempReg(pParse, r2);
82107       sqlite3ReleaseTempReg(pParse, r1);
82108       break;
82109     }
82110
82111 #ifndef SQLITE_OMIT_SUBQUERY
82112     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
82113     ** then there should be a single item on the stack.  Write this
82114     ** item into the set table with bogus data.
82115     */
82116     case SRT_Set: {
82117       int r1;
82118       assert( pIn->nMem==1 );
82119       p->affinity = 
82120          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affinity);
82121       r1 = sqlite3GetTempReg(pParse);
82122       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iMem, 1, r1, &p->affinity, 1);
82123       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, 1);
82124       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iParm, r1);
82125       sqlite3ReleaseTempReg(pParse, r1);
82126       break;
82127     }
82128
82129 #if 0  /* Never occurs on an ORDER BY query */
82130     /* If any row exist in the result set, record that fact and abort.
82131     */
82132     case SRT_Exists: {
82133       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iParm);
82134       /* The LIMIT clause will terminate the loop for us */
82135       break;
82136     }
82137 #endif
82138
82139     /* If this is a scalar select that is part of an expression, then
82140     ** store the results in the appropriate memory cell and break out
82141     ** of the scan loop.
82142     */
82143     case SRT_Mem: {
82144       assert( pIn->nMem==1 );
82145       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iParm, 1);
82146       /* The LIMIT clause will jump out of the loop for us */
82147       break;
82148     }
82149 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
82150
82151     /* The results are stored in a sequence of registers
82152     ** starting at pDest->iMem.  Then the co-routine yields.
82153     */
82154     case SRT_Coroutine: {
82155       if( pDest->iMem==0 ){
82156         pDest->iMem = sqlite3GetTempRange(pParse, pIn->nMem);
82157         pDest->nMem = pIn->nMem;
82158       }
82159       sqlite3ExprCodeMove(pParse, pIn->iMem, pDest->iMem, pDest->nMem);
82160       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iParm);
82161       break;
82162     }
82163
82164     /* If none of the above, then the result destination must be
82165     ** SRT_Output.  This routine is never called with any other
82166     ** destination other than the ones handled above or SRT_Output.
82167     **
82168     ** For SRT_Output, results are stored in a sequence of registers.  
82169     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
82170     ** return the next row of result.
82171     */
82172     default: {
82173       assert( pDest->eDest==SRT_Output );
82174       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iMem, pIn->nMem);
82175       sqlite3ExprCacheAffinityChange(pParse, pIn->iMem, pIn->nMem);
82176       break;
82177     }
82178   }
82179
82180   /* Jump to the end of the loop if the LIMIT is reached.
82181   */
82182   if( p->iLimit ){
82183     sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1);
82184   }
82185
82186   /* Generate the subroutine return
82187   */
82188   sqlite3VdbeResolveLabel(v, iContinue);
82189   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
82190
82191   return addr;
82192 }
82193
82194 /*
82195 ** Alternative compound select code generator for cases when there
82196 ** is an ORDER BY clause.
82197 **
82198 ** We assume a query of the following form:
82199 **
82200 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
82201 **
82202 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
82203 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
82204 ** co-routines.  Then run the co-routines in parallel and merge the results
82205 ** into the output.  In addition to the two coroutines (called selectA and
82206 ** selectB) there are 7 subroutines:
82207 **
82208 **    outA:    Move the output of the selectA coroutine into the output
82209 **             of the compound query.
82210 **
82211 **    outB:    Move the output of the selectB coroutine into the output
82212 **             of the compound query.  (Only generated for UNION and
82213 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
82214 **             appears only in B.)
82215 **
82216 **    AltB:    Called when there is data from both coroutines and A<B.
82217 **
82218 **    AeqB:    Called when there is data from both coroutines and A==B.
82219 **
82220 **    AgtB:    Called when there is data from both coroutines and A>B.
82221 **
82222 **    EofA:    Called when data is exhausted from selectA.
82223 **
82224 **    EofB:    Called when data is exhausted from selectB.
82225 **
82226 ** The implementation of the latter five subroutines depend on which 
82227 ** <operator> is used:
82228 **
82229 **
82230 **             UNION ALL         UNION            EXCEPT          INTERSECT
82231 **          -------------  -----------------  --------------  -----------------
82232 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
82233 **
82234 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
82235 **
82236 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
82237 **
82238 **   EofA:   outB, nextB      outB, nextB          halt             halt
82239 **
82240 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
82241 **
82242 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
82243 ** causes an immediate jump to EofA and an EOF on B following nextB causes
82244 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
82245 ** following nextX causes a jump to the end of the select processing.
82246 **
82247 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
82248 ** within the output subroutine.  The regPrev register set holds the previously
82249 ** output value.  A comparison is made against this value and the output
82250 ** is skipped if the next results would be the same as the previous.
82251 **
82252 ** The implementation plan is to implement the two coroutines and seven
82253 ** subroutines first, then put the control logic at the bottom.  Like this:
82254 **
82255 **          goto Init
82256 **     coA: coroutine for left query (A)
82257 **     coB: coroutine for right query (B)
82258 **    outA: output one row of A
82259 **    outB: output one row of B (UNION and UNION ALL only)
82260 **    EofA: ...
82261 **    EofB: ...
82262 **    AltB: ...
82263 **    AeqB: ...
82264 **    AgtB: ...
82265 **    Init: initialize coroutine registers
82266 **          yield coA
82267 **          if eof(A) goto EofA
82268 **          yield coB
82269 **          if eof(B) goto EofB
82270 **    Cmpr: Compare A, B
82271 **          Jump AltB, AeqB, AgtB
82272 **     End: ...
82273 **
82274 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
82275 ** actually called using Gosub and they do not Return.  EofA and EofB loop
82276 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
82277 ** and AgtB jump to either L2 or to one of EofA or EofB.
82278 */
82279 #ifndef SQLITE_OMIT_COMPOUND_SELECT
82280 static int multiSelectOrderBy(
82281   Parse *pParse,        /* Parsing context */
82282   Select *p,            /* The right-most of SELECTs to be coded */
82283   SelectDest *pDest     /* What to do with query results */
82284 ){
82285   int i, j;             /* Loop counters */
82286   Select *pPrior;       /* Another SELECT immediately to our left */
82287   Vdbe *v;              /* Generate code to this VDBE */
82288   SelectDest destA;     /* Destination for coroutine A */
82289   SelectDest destB;     /* Destination for coroutine B */
82290   int regAddrA;         /* Address register for select-A coroutine */
82291   int regEofA;          /* Flag to indicate when select-A is complete */
82292   int regAddrB;         /* Address register for select-B coroutine */
82293   int regEofB;          /* Flag to indicate when select-B is complete */
82294   int addrSelectA;      /* Address of the select-A coroutine */
82295   int addrSelectB;      /* Address of the select-B coroutine */
82296   int regOutA;          /* Address register for the output-A subroutine */
82297   int regOutB;          /* Address register for the output-B subroutine */
82298   int addrOutA;         /* Address of the output-A subroutine */
82299   int addrOutB = 0;     /* Address of the output-B subroutine */
82300   int addrEofA;         /* Address of the select-A-exhausted subroutine */
82301   int addrEofB;         /* Address of the select-B-exhausted subroutine */
82302   int addrAltB;         /* Address of the A<B subroutine */
82303   int addrAeqB;         /* Address of the A==B subroutine */
82304   int addrAgtB;         /* Address of the A>B subroutine */
82305   int regLimitA;        /* Limit register for select-A */
82306   int regLimitB;        /* Limit register for select-A */
82307   int regPrev;          /* A range of registers to hold previous output */
82308   int savedLimit;       /* Saved value of p->iLimit */
82309   int savedOffset;      /* Saved value of p->iOffset */
82310   int labelCmpr;        /* Label for the start of the merge algorithm */
82311   int labelEnd;         /* Label for the end of the overall SELECT stmt */
82312   int j1;               /* Jump instructions that get retargetted */
82313   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
82314   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
82315   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
82316   sqlite3 *db;          /* Database connection */
82317   ExprList *pOrderBy;   /* The ORDER BY clause */
82318   int nOrderBy;         /* Number of terms in the ORDER BY clause */
82319   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
82320
82321   assert( p->pOrderBy!=0 );
82322   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
82323   db = pParse->db;
82324   v = pParse->pVdbe;
82325   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
82326   labelEnd = sqlite3VdbeMakeLabel(v);
82327   labelCmpr = sqlite3VdbeMakeLabel(v);
82328
82329
82330   /* Patch up the ORDER BY clause
82331   */
82332   op = p->op;  
82333   pPrior = p->pPrior;
82334   assert( pPrior->pOrderBy==0 );
82335   pOrderBy = p->pOrderBy;
82336   assert( pOrderBy );
82337   nOrderBy = pOrderBy->nExpr;
82338
82339   /* For operators other than UNION ALL we have to make sure that
82340   ** the ORDER BY clause covers every term of the result set.  Add
82341   ** terms to the ORDER BY clause as necessary.
82342   */
82343   if( op!=TK_ALL ){
82344     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
82345       struct ExprList_item *pItem;
82346       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
82347         assert( pItem->iCol>0 );
82348         if( pItem->iCol==i ) break;
82349       }
82350       if( j==nOrderBy ){
82351         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
82352         if( pNew==0 ) return SQLITE_NOMEM;
82353         pNew->flags |= EP_IntValue;
82354         pNew->u.iValue = i;
82355         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
82356         pOrderBy->a[nOrderBy++].iCol = (u16)i;
82357       }
82358     }
82359   }
82360
82361   /* Compute the comparison permutation and keyinfo that is used with
82362   ** the permutation used to determine if the next
82363   ** row of results comes from selectA or selectB.  Also add explicit
82364   ** collations to the ORDER BY clause terms so that when the subqueries
82365   ** to the right and the left are evaluated, they use the correct
82366   ** collation.
82367   */
82368   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
82369   if( aPermute ){
82370     struct ExprList_item *pItem;
82371     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
82372       assert( pItem->iCol>0  && pItem->iCol<=p->pEList->nExpr );
82373       aPermute[i] = pItem->iCol - 1;
82374     }
82375     pKeyMerge =
82376       sqlite3DbMallocRaw(db, sizeof(*pKeyMerge)+nOrderBy*(sizeof(CollSeq*)+1));
82377     if( pKeyMerge ){
82378       pKeyMerge->aSortOrder = (u8*)&pKeyMerge->aColl[nOrderBy];
82379       pKeyMerge->nField = (u16)nOrderBy;
82380       pKeyMerge->enc = ENC(db);
82381       for(i=0; i<nOrderBy; i++){
82382         CollSeq *pColl;
82383         Expr *pTerm = pOrderBy->a[i].pExpr;
82384         if( pTerm->flags & EP_ExpCollate ){
82385           pColl = pTerm->pColl;
82386         }else{
82387           pColl = multiSelectCollSeq(pParse, p, aPermute[i]);
82388           pTerm->flags |= EP_ExpCollate;
82389           pTerm->pColl = pColl;
82390         }
82391         pKeyMerge->aColl[i] = pColl;
82392         pKeyMerge->aSortOrder[i] = pOrderBy->a[i].sortOrder;
82393       }
82394     }
82395   }else{
82396     pKeyMerge = 0;
82397   }
82398
82399   /* Reattach the ORDER BY clause to the query.
82400   */
82401   p->pOrderBy = pOrderBy;
82402   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
82403
82404   /* Allocate a range of temporary registers and the KeyInfo needed
82405   ** for the logic that removes duplicate result rows when the
82406   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
82407   */
82408   if( op==TK_ALL ){
82409     regPrev = 0;
82410   }else{
82411     int nExpr = p->pEList->nExpr;
82412     assert( nOrderBy>=nExpr || db->mallocFailed );
82413     regPrev = sqlite3GetTempRange(pParse, nExpr+1);
82414     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
82415     pKeyDup = sqlite3DbMallocZero(db,
82416                   sizeof(*pKeyDup) + nExpr*(sizeof(CollSeq*)+1) );
82417     if( pKeyDup ){
82418       pKeyDup->aSortOrder = (u8*)&pKeyDup->aColl[nExpr];
82419       pKeyDup->nField = (u16)nExpr;
82420       pKeyDup->enc = ENC(db);
82421       for(i=0; i<nExpr; i++){
82422         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
82423         pKeyDup->aSortOrder[i] = 0;
82424       }
82425     }
82426   }
82427  
82428   /* Separate the left and the right query from one another
82429   */
82430   p->pPrior = 0;
82431   pPrior->pRightmost = 0;
82432   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
82433   if( pPrior->pPrior==0 ){
82434     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
82435   }
82436
82437   /* Compute the limit registers */
82438   computeLimitRegisters(pParse, p, labelEnd);
82439   if( p->iLimit && op==TK_ALL ){
82440     regLimitA = ++pParse->nMem;
82441     regLimitB = ++pParse->nMem;
82442     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
82443                                   regLimitA);
82444     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
82445   }else{
82446     regLimitA = regLimitB = 0;
82447   }
82448   sqlite3ExprDelete(db, p->pLimit);
82449   p->pLimit = 0;
82450   sqlite3ExprDelete(db, p->pOffset);
82451   p->pOffset = 0;
82452
82453   regAddrA = ++pParse->nMem;
82454   regEofA = ++pParse->nMem;
82455   regAddrB = ++pParse->nMem;
82456   regEofB = ++pParse->nMem;
82457   regOutA = ++pParse->nMem;
82458   regOutB = ++pParse->nMem;
82459   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
82460   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
82461
82462   /* Jump past the various subroutines and coroutines to the main
82463   ** merge loop
82464   */
82465   j1 = sqlite3VdbeAddOp0(v, OP_Goto);
82466   addrSelectA = sqlite3VdbeCurrentAddr(v);
82467
82468
82469   /* Generate a coroutine to evaluate the SELECT statement to the
82470   ** left of the compound operator - the "A" select.
82471   */
82472   VdbeNoopComment((v, "Begin coroutine for left SELECT"));
82473   pPrior->iLimit = regLimitA;
82474   sqlite3Select(pParse, pPrior, &destA);
82475   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofA);
82476   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
82477   VdbeNoopComment((v, "End coroutine for left SELECT"));
82478
82479   /* Generate a coroutine to evaluate the SELECT statement on 
82480   ** the right - the "B" select
82481   */
82482   addrSelectB = sqlite3VdbeCurrentAddr(v);
82483   VdbeNoopComment((v, "Begin coroutine for right SELECT"));
82484   savedLimit = p->iLimit;
82485   savedOffset = p->iOffset;
82486   p->iLimit = regLimitB;
82487   p->iOffset = 0;  
82488   sqlite3Select(pParse, p, &destB);
82489   p->iLimit = savedLimit;
82490   p->iOffset = savedOffset;
82491   sqlite3VdbeAddOp2(v, OP_Integer, 1, regEofB);
82492   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
82493   VdbeNoopComment((v, "End coroutine for right SELECT"));
82494
82495   /* Generate a subroutine that outputs the current row of the A
82496   ** select as the next output row of the compound select.
82497   */
82498   VdbeNoopComment((v, "Output routine for A"));
82499   addrOutA = generateOutputSubroutine(pParse,
82500                  p, &destA, pDest, regOutA,
82501                  regPrev, pKeyDup, P4_KEYINFO_HANDOFF, labelEnd);
82502   
82503   /* Generate a subroutine that outputs the current row of the B
82504   ** select as the next output row of the compound select.
82505   */
82506   if( op==TK_ALL || op==TK_UNION ){
82507     VdbeNoopComment((v, "Output routine for B"));
82508     addrOutB = generateOutputSubroutine(pParse,
82509                  p, &destB, pDest, regOutB,
82510                  regPrev, pKeyDup, P4_KEYINFO_STATIC, labelEnd);
82511   }
82512
82513   /* Generate a subroutine to run when the results from select A
82514   ** are exhausted and only data in select B remains.
82515   */
82516   VdbeNoopComment((v, "eof-A subroutine"));
82517   if( op==TK_EXCEPT || op==TK_INTERSECT ){
82518     addrEofA = sqlite3VdbeAddOp2(v, OP_Goto, 0, labelEnd);
82519   }else{  
82520     addrEofA = sqlite3VdbeAddOp2(v, OP_If, regEofB, labelEnd);
82521     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
82522     sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
82523     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
82524   }
82525
82526   /* Generate a subroutine to run when the results from select B
82527   ** are exhausted and only data in select A remains.
82528   */
82529   if( op==TK_INTERSECT ){
82530     addrEofB = addrEofA;
82531   }else{  
82532     VdbeNoopComment((v, "eof-B subroutine"));
82533     addrEofB = sqlite3VdbeAddOp2(v, OP_If, regEofA, labelEnd);
82534     sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
82535     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
82536     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
82537   }
82538
82539   /* Generate code to handle the case of A<B
82540   */
82541   VdbeNoopComment((v, "A-lt-B subroutine"));
82542   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
82543   sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
82544   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
82545   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
82546
82547   /* Generate code to handle the case of A==B
82548   */
82549   if( op==TK_ALL ){
82550     addrAeqB = addrAltB;
82551   }else if( op==TK_INTERSECT ){
82552     addrAeqB = addrAltB;
82553     addrAltB++;
82554   }else{
82555     VdbeNoopComment((v, "A-eq-B subroutine"));
82556     addrAeqB =
82557     sqlite3VdbeAddOp1(v, OP_Yield, regAddrA);
82558     sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
82559     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
82560   }
82561
82562   /* Generate code to handle the case of A>B
82563   */
82564   VdbeNoopComment((v, "A-gt-B subroutine"));
82565   addrAgtB = sqlite3VdbeCurrentAddr(v);
82566   if( op==TK_ALL || op==TK_UNION ){
82567     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
82568   }
82569   sqlite3VdbeAddOp1(v, OP_Yield, regAddrB);
82570   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
82571   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
82572
82573   /* This code runs once to initialize everything.
82574   */
82575   sqlite3VdbeJumpHere(v, j1);
82576   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofA);
82577   sqlite3VdbeAddOp2(v, OP_Integer, 0, regEofB);
82578   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrA, addrSelectA);
82579   sqlite3VdbeAddOp2(v, OP_Gosub, regAddrB, addrSelectB);
82580   sqlite3VdbeAddOp2(v, OP_If, regEofA, addrEofA);
82581   sqlite3VdbeAddOp2(v, OP_If, regEofB, addrEofB);
82582
82583   /* Implement the main merge loop
82584   */
82585   sqlite3VdbeResolveLabel(v, labelCmpr);
82586   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
82587   sqlite3VdbeAddOp4(v, OP_Compare, destA.iMem, destB.iMem, nOrderBy,
82588                          (char*)pKeyMerge, P4_KEYINFO_HANDOFF);
82589   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
82590
82591   /* Release temporary registers
82592   */
82593   if( regPrev ){
82594     sqlite3ReleaseTempRange(pParse, regPrev, nOrderBy+1);
82595   }
82596
82597   /* Jump to the this point in order to terminate the query.
82598   */
82599   sqlite3VdbeResolveLabel(v, labelEnd);
82600
82601   /* Set the number of output columns
82602   */
82603   if( pDest->eDest==SRT_Output ){
82604     Select *pFirst = pPrior;
82605     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
82606     generateColumnNames(pParse, 0, pFirst->pEList);
82607   }
82608
82609   /* Reassembly the compound query so that it will be freed correctly
82610   ** by the calling function */
82611   if( p->pPrior ){
82612     sqlite3SelectDelete(db, p->pPrior);
82613   }
82614   p->pPrior = pPrior;
82615
82616   /*** TBD:  Insert subroutine calls to close cursors on incomplete
82617   **** subqueries ****/
82618   return SQLITE_OK;
82619 }
82620 #endif
82621
82622 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
82623 /* Forward Declarations */
82624 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
82625 static void substSelect(sqlite3*, Select *, int, ExprList *);
82626
82627 /*
82628 ** Scan through the expression pExpr.  Replace every reference to
82629 ** a column in table number iTable with a copy of the iColumn-th
82630 ** entry in pEList.  (But leave references to the ROWID column 
82631 ** unchanged.)
82632 **
82633 ** This routine is part of the flattening procedure.  A subquery
82634 ** whose result set is defined by pEList appears as entry in the
82635 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
82636 ** FORM clause entry is iTable.  This routine make the necessary 
82637 ** changes to pExpr so that it refers directly to the source table
82638 ** of the subquery rather the result set of the subquery.
82639 */
82640 static Expr *substExpr(
82641   sqlite3 *db,        /* Report malloc errors to this connection */
82642   Expr *pExpr,        /* Expr in which substitution occurs */
82643   int iTable,         /* Table to be substituted */
82644   ExprList *pEList    /* Substitute expressions */
82645 ){
82646   if( pExpr==0 ) return 0;
82647   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
82648     if( pExpr->iColumn<0 ){
82649       pExpr->op = TK_NULL;
82650     }else{
82651       Expr *pNew;
82652       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
82653       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
82654       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
82655       if( pNew && pExpr->pColl ){
82656         pNew->pColl = pExpr->pColl;
82657       }
82658       sqlite3ExprDelete(db, pExpr);
82659       pExpr = pNew;
82660     }
82661   }else{
82662     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
82663     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
82664     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
82665       substSelect(db, pExpr->x.pSelect, iTable, pEList);
82666     }else{
82667       substExprList(db, pExpr->x.pList, iTable, pEList);
82668     }
82669   }
82670   return pExpr;
82671 }
82672 static void substExprList(
82673   sqlite3 *db,         /* Report malloc errors here */
82674   ExprList *pList,     /* List to scan and in which to make substitutes */
82675   int iTable,          /* Table to be substituted */
82676   ExprList *pEList     /* Substitute values */
82677 ){
82678   int i;
82679   if( pList==0 ) return;
82680   for(i=0; i<pList->nExpr; i++){
82681     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
82682   }
82683 }
82684 static void substSelect(
82685   sqlite3 *db,         /* Report malloc errors here */
82686   Select *p,           /* SELECT statement in which to make substitutions */
82687   int iTable,          /* Table to be replaced */
82688   ExprList *pEList     /* Substitute values */
82689 ){
82690   SrcList *pSrc;
82691   struct SrcList_item *pItem;
82692   int i;
82693   if( !p ) return;
82694   substExprList(db, p->pEList, iTable, pEList);
82695   substExprList(db, p->pGroupBy, iTable, pEList);
82696   substExprList(db, p->pOrderBy, iTable, pEList);
82697   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
82698   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
82699   substSelect(db, p->pPrior, iTable, pEList);
82700   pSrc = p->pSrc;
82701   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
82702   if( ALWAYS(pSrc) ){
82703     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
82704       substSelect(db, pItem->pSelect, iTable, pEList);
82705     }
82706   }
82707 }
82708 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
82709
82710 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
82711 /*
82712 ** This routine attempts to flatten subqueries in order to speed
82713 ** execution.  It returns 1 if it makes changes and 0 if no flattening
82714 ** occurs.
82715 **
82716 ** To understand the concept of flattening, consider the following
82717 ** query:
82718 **
82719 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
82720 **
82721 ** The default way of implementing this query is to execute the
82722 ** subquery first and store the results in a temporary table, then
82723 ** run the outer query on that temporary table.  This requires two
82724 ** passes over the data.  Furthermore, because the temporary table
82725 ** has no indices, the WHERE clause on the outer query cannot be
82726 ** optimized.
82727 **
82728 ** This routine attempts to rewrite queries such as the above into
82729 ** a single flat select, like this:
82730 **
82731 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
82732 **
82733 ** The code generated for this simpification gives the same result
82734 ** but only has to scan the data once.  And because indices might 
82735 ** exist on the table t1, a complete scan of the data might be
82736 ** avoided.
82737 **
82738 ** Flattening is only attempted if all of the following are true:
82739 **
82740 **   (1)  The subquery and the outer query do not both use aggregates.
82741 **
82742 **   (2)  The subquery is not an aggregate or the outer query is not a join.
82743 **
82744 **   (3)  The subquery is not the right operand of a left outer join
82745 **        (Originally ticket #306.  Strenghtened by ticket #3300)
82746 **
82747 **   (4)  The subquery is not DISTINCT or the outer query is not a join.
82748 **
82749 **   (5)  The subquery is not DISTINCT or the outer query does not use
82750 **        aggregates.
82751 **
82752 **   (6)  The subquery does not use aggregates or the outer query is not
82753 **        DISTINCT.
82754 **
82755 **   (7)  The subquery has a FROM clause.
82756 **
82757 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
82758 **
82759 **   (9)  The subquery does not use LIMIT or the outer query does not use
82760 **        aggregates.
82761 **
82762 **  (10)  The subquery does not use aggregates or the outer query does not
82763 **        use LIMIT.
82764 **
82765 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
82766 **
82767 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
82768 **        a separate restriction deriving from ticket #350.
82769 **
82770 **  (13)  The subquery and outer query do not both use LIMIT
82771 **
82772 **  (14)  The subquery does not use OFFSET
82773 **
82774 **  (15)  The outer query is not part of a compound select or the
82775 **        subquery does not have both an ORDER BY and a LIMIT clause.
82776 **        (See ticket #2339)
82777 **
82778 **  (16)  The outer query is not an aggregate or the subquery does
82779 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
82780 **        until we introduced the group_concat() function.  
82781 **
82782 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
82783 **        compound clause made up entirely of non-aggregate queries, and 
82784 **        the parent query:
82785 **
82786 **          * is not itself part of a compound select,
82787 **          * is not an aggregate or DISTINCT query, and
82788 **          * has no other tables or sub-selects in the FROM clause.
82789 **
82790 **        The parent and sub-query may contain WHERE clauses. Subject to
82791 **        rules (11), (13) and (14), they may also contain ORDER BY,
82792 **        LIMIT and OFFSET clauses.
82793 **
82794 **  (18)  If the sub-query is a compound select, then all terms of the
82795 **        ORDER by clause of the parent must be simple references to 
82796 **        columns of the sub-query.
82797 **
82798 **  (19)  The subquery does not use LIMIT or the outer query does not
82799 **        have a WHERE clause.
82800 **
82801 **  (20)  If the sub-query is a compound select, then it must not use
82802 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
82803 **        somewhat by saying that the terms of the ORDER BY clause must
82804 **        appear as unmodified result columns in the outer query.  But
82805 **        have other optimizations in mind to deal with that case.
82806 **
82807 ** In this routine, the "p" parameter is a pointer to the outer query.
82808 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
82809 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
82810 **
82811 ** If flattening is not attempted, this routine is a no-op and returns 0.
82812 ** If flattening is attempted this routine returns 1.
82813 **
82814 ** All of the expression analysis must occur on both the outer query and
82815 ** the subquery before this routine runs.
82816 */
82817 static int flattenSubquery(
82818   Parse *pParse,       /* Parsing context */
82819   Select *p,           /* The parent or outer SELECT statement */
82820   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
82821   int isAgg,           /* True if outer SELECT uses aggregate functions */
82822   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
82823 ){
82824   const char *zSavedAuthContext = pParse->zAuthContext;
82825   Select *pParent;
82826   Select *pSub;       /* The inner query or "subquery" */
82827   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
82828   SrcList *pSrc;      /* The FROM clause of the outer query */
82829   SrcList *pSubSrc;   /* The FROM clause of the subquery */
82830   ExprList *pList;    /* The result set of the outer query */
82831   int iParent;        /* VDBE cursor number of the pSub result set temp table */
82832   int i;              /* Loop counter */
82833   Expr *pWhere;                    /* The WHERE clause */
82834   struct SrcList_item *pSubitem;   /* The subquery */
82835   sqlite3 *db = pParse->db;
82836
82837   /* Check to see if flattening is permitted.  Return 0 if not.
82838   */
82839   assert( p!=0 );
82840   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
82841   if( db->flags & SQLITE_QueryFlattener ) return 0;
82842   pSrc = p->pSrc;
82843   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
82844   pSubitem = &pSrc->a[iFrom];
82845   iParent = pSubitem->iCursor;
82846   pSub = pSubitem->pSelect;
82847   assert( pSub!=0 );
82848   if( isAgg && subqueryIsAgg ) return 0;                 /* Restriction (1)  */
82849   if( subqueryIsAgg && pSrc->nSrc>1 ) return 0;          /* Restriction (2)  */
82850   pSubSrc = pSub->pSrc;
82851   assert( pSubSrc );
82852   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
82853   ** not arbitrary expresssions, we allowed some combining of LIMIT and OFFSET
82854   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
82855   ** became arbitrary expressions, we were forced to add restrictions (13)
82856   ** and (14). */
82857   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
82858   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
82859   if( p->pRightmost && pSub->pLimit && pSub->pOrderBy ){
82860     return 0;                                            /* Restriction (15) */
82861   }
82862   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
82863   if( ((pSub->selFlags & SF_Distinct)!=0 || pSub->pLimit) 
82864          && (pSrc->nSrc>1 || isAgg) ){          /* Restrictions (4)(5)(8)(9) */
82865      return 0;       
82866   }
82867   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
82868      return 0;         /* Restriction (6)  */
82869   }
82870   if( p->pOrderBy && pSub->pOrderBy ){
82871      return 0;                                           /* Restriction (11) */
82872   }
82873   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
82874   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
82875
82876   /* OBSOLETE COMMENT 1:
82877   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
82878   ** not used as the right operand of an outer join.  Examples of why this
82879   ** is not allowed:
82880   **
82881   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
82882   **
82883   ** If we flatten the above, we would get
82884   **
82885   **         (t1 LEFT OUTER JOIN t2) JOIN t3
82886   **
82887   ** which is not at all the same thing.
82888   **
82889   ** OBSOLETE COMMENT 2:
82890   ** Restriction 12:  If the subquery is the right operand of a left outer
82891   ** join, make sure the subquery has no WHERE clause.
82892   ** An examples of why this is not allowed:
82893   **
82894   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
82895   **
82896   ** If we flatten the above, we would get
82897   **
82898   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
82899   **
82900   ** But the t2.x>0 test will always fail on a NULL row of t2, which
82901   ** effectively converts the OUTER JOIN into an INNER JOIN.
82902   **
82903   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
82904   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
82905   ** is fraught with danger.  Best to avoid the whole thing.  If the
82906   ** subquery is the right term of a LEFT JOIN, then do not flatten.
82907   */
82908   if( (pSubitem->jointype & JT_OUTER)!=0 ){
82909     return 0;
82910   }
82911
82912   /* Restriction 17: If the sub-query is a compound SELECT, then it must
82913   ** use only the UNION ALL operator. And none of the simple select queries
82914   ** that make up the compound SELECT are allowed to be aggregate or distinct
82915   ** queries.
82916   */
82917   if( pSub->pPrior ){
82918     if( pSub->pOrderBy ){
82919       return 0;  /* Restriction 20 */
82920     }
82921     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
82922       return 0;
82923     }
82924     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
82925       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
82926       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
82927       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
82928        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
82929        || NEVER(pSub1->pSrc==0) || pSub1->pSrc->nSrc!=1
82930       ){
82931         return 0;
82932       }
82933     }
82934
82935     /* Restriction 18. */
82936     if( p->pOrderBy ){
82937       int ii;
82938       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
82939         if( p->pOrderBy->a[ii].iCol==0 ) return 0;
82940       }
82941     }
82942   }
82943
82944   /***** If we reach this point, flattening is permitted. *****/
82945
82946   /* Authorize the subquery */
82947   pParse->zAuthContext = pSubitem->zName;
82948   sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
82949   pParse->zAuthContext = zSavedAuthContext;
82950
82951   /* If the sub-query is a compound SELECT statement, then (by restrictions
82952   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
82953   ** be of the form:
82954   **
82955   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
82956   **
82957   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
82958   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
82959   ** OFFSET clauses and joins them to the left-hand-side of the original
82960   ** using UNION ALL operators. In this case N is the number of simple
82961   ** select statements in the compound sub-query.
82962   **
82963   ** Example:
82964   **
82965   **     SELECT a+1 FROM (
82966   **        SELECT x FROM tab
82967   **        UNION ALL
82968   **        SELECT y FROM tab
82969   **        UNION ALL
82970   **        SELECT abs(z*2) FROM tab2
82971   **     ) WHERE a!=5 ORDER BY 1
82972   **
82973   ** Transformed into:
82974   **
82975   **     SELECT x+1 FROM tab WHERE x+1!=5
82976   **     UNION ALL
82977   **     SELECT y+1 FROM tab WHERE y+1!=5
82978   **     UNION ALL
82979   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
82980   **     ORDER BY 1
82981   **
82982   ** We call this the "compound-subquery flattening".
82983   */
82984   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
82985     Select *pNew;
82986     ExprList *pOrderBy = p->pOrderBy;
82987     Expr *pLimit = p->pLimit;
82988     Select *pPrior = p->pPrior;
82989     p->pOrderBy = 0;
82990     p->pSrc = 0;
82991     p->pPrior = 0;
82992     p->pLimit = 0;
82993     pNew = sqlite3SelectDup(db, p, 0);
82994     p->pLimit = pLimit;
82995     p->pOrderBy = pOrderBy;
82996     p->pSrc = pSrc;
82997     p->op = TK_ALL;
82998     p->pRightmost = 0;
82999     if( pNew==0 ){
83000       pNew = pPrior;
83001     }else{
83002       pNew->pPrior = pPrior;
83003       pNew->pRightmost = 0;
83004     }
83005     p->pPrior = pNew;
83006     if( db->mallocFailed ) return 1;
83007   }
83008
83009   /* Begin flattening the iFrom-th entry of the FROM clause 
83010   ** in the outer query.
83011   */
83012   pSub = pSub1 = pSubitem->pSelect;
83013
83014   /* Delete the transient table structure associated with the
83015   ** subquery
83016   */
83017   sqlite3DbFree(db, pSubitem->zDatabase);
83018   sqlite3DbFree(db, pSubitem->zName);
83019   sqlite3DbFree(db, pSubitem->zAlias);
83020   pSubitem->zDatabase = 0;
83021   pSubitem->zName = 0;
83022   pSubitem->zAlias = 0;
83023   pSubitem->pSelect = 0;
83024
83025   /* Defer deleting the Table object associated with the
83026   ** subquery until code generation is
83027   ** complete, since there may still exist Expr.pTab entries that
83028   ** refer to the subquery even after flattening.  Ticket #3346.
83029   **
83030   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
83031   */
83032   if( ALWAYS(pSubitem->pTab!=0) ){
83033     Table *pTabToDel = pSubitem->pTab;
83034     if( pTabToDel->nRef==1 ){
83035       Parse *pToplevel = sqlite3ParseToplevel(pParse);
83036       pTabToDel->pNextZombie = pToplevel->pZombieTab;
83037       pToplevel->pZombieTab = pTabToDel;
83038     }else{
83039       pTabToDel->nRef--;
83040     }
83041     pSubitem->pTab = 0;
83042   }
83043
83044   /* The following loop runs once for each term in a compound-subquery
83045   ** flattening (as described above).  If we are doing a different kind
83046   ** of flattening - a flattening other than a compound-subquery flattening -
83047   ** then this loop only runs once.
83048   **
83049   ** This loop moves all of the FROM elements of the subquery into the
83050   ** the FROM clause of the outer query.  Before doing this, remember
83051   ** the cursor number for the original outer query FROM element in
83052   ** iParent.  The iParent cursor will never be used.  Subsequent code
83053   ** will scan expressions looking for iParent references and replace
83054   ** those references with expressions that resolve to the subquery FROM
83055   ** elements we are now copying in.
83056   */
83057   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
83058     int nSubSrc;
83059     u8 jointype = 0;
83060     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
83061     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
83062     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
83063
83064     if( pSrc ){
83065       assert( pParent==p );  /* First time through the loop */
83066       jointype = pSubitem->jointype;
83067     }else{
83068       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
83069       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
83070       if( pSrc==0 ){
83071         assert( db->mallocFailed );
83072         break;
83073       }
83074     }
83075
83076     /* The subquery uses a single slot of the FROM clause of the outer
83077     ** query.  If the subquery has more than one element in its FROM clause,
83078     ** then expand the outer query to make space for it to hold all elements
83079     ** of the subquery.
83080     **
83081     ** Example:
83082     **
83083     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
83084     **
83085     ** The outer query has 3 slots in its FROM clause.  One slot of the
83086     ** outer query (the middle slot) is used by the subquery.  The next
83087     ** block of code will expand the out query to 4 slots.  The middle
83088     ** slot is expanded to two slots in order to make space for the
83089     ** two elements in the FROM clause of the subquery.
83090     */
83091     if( nSubSrc>1 ){
83092       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
83093       if( db->mallocFailed ){
83094         break;
83095       }
83096     }
83097
83098     /* Transfer the FROM clause terms from the subquery into the
83099     ** outer query.
83100     */
83101     for(i=0; i<nSubSrc; i++){
83102       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
83103       pSrc->a[i+iFrom] = pSubSrc->a[i];
83104       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
83105     }
83106     pSrc->a[iFrom].jointype = jointype;
83107   
83108     /* Now begin substituting subquery result set expressions for 
83109     ** references to the iParent in the outer query.
83110     ** 
83111     ** Example:
83112     **
83113     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
83114     **   \                     \_____________ subquery __________/          /
83115     **    \_____________________ outer query ______________________________/
83116     **
83117     ** We look at every expression in the outer query and every place we see
83118     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
83119     */
83120     pList = pParent->pEList;
83121     for(i=0; i<pList->nExpr; i++){
83122       if( pList->a[i].zName==0 ){
83123         const char *zSpan = pList->a[i].zSpan;
83124         if( ALWAYS(zSpan) ){
83125           pList->a[i].zName = sqlite3DbStrDup(db, zSpan);
83126         }
83127       }
83128     }
83129     substExprList(db, pParent->pEList, iParent, pSub->pEList);
83130     if( isAgg ){
83131       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
83132       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
83133     }
83134     if( pSub->pOrderBy ){
83135       assert( pParent->pOrderBy==0 );
83136       pParent->pOrderBy = pSub->pOrderBy;
83137       pSub->pOrderBy = 0;
83138     }else if( pParent->pOrderBy ){
83139       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
83140     }
83141     if( pSub->pWhere ){
83142       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
83143     }else{
83144       pWhere = 0;
83145     }
83146     if( subqueryIsAgg ){
83147       assert( pParent->pHaving==0 );
83148       pParent->pHaving = pParent->pWhere;
83149       pParent->pWhere = pWhere;
83150       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
83151       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
83152                                   sqlite3ExprDup(db, pSub->pHaving, 0));
83153       assert( pParent->pGroupBy==0 );
83154       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
83155     }else{
83156       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
83157       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
83158     }
83159   
83160     /* The flattened query is distinct if either the inner or the
83161     ** outer query is distinct. 
83162     */
83163     pParent->selFlags |= pSub->selFlags & SF_Distinct;
83164   
83165     /*
83166     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
83167     **
83168     ** One is tempted to try to add a and b to combine the limits.  But this
83169     ** does not work if either limit is negative.
83170     */
83171     if( pSub->pLimit ){
83172       pParent->pLimit = pSub->pLimit;
83173       pSub->pLimit = 0;
83174     }
83175   }
83176
83177   /* Finially, delete what is left of the subquery and return
83178   ** success.
83179   */
83180   sqlite3SelectDelete(db, pSub1);
83181
83182   return 1;
83183 }
83184 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
83185
83186 /*
83187 ** Analyze the SELECT statement passed as an argument to see if it
83188 ** is a min() or max() query. Return WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX if 
83189 ** it is, or 0 otherwise. At present, a query is considered to be
83190 ** a min()/max() query if:
83191 **
83192 **   1. There is a single object in the FROM clause.
83193 **
83194 **   2. There is a single expression in the result set, and it is
83195 **      either min(x) or max(x), where x is a column reference.
83196 */
83197 static u8 minMaxQuery(Select *p){
83198   Expr *pExpr;
83199   ExprList *pEList = p->pEList;
83200
83201   if( pEList->nExpr!=1 ) return WHERE_ORDERBY_NORMAL;
83202   pExpr = pEList->a[0].pExpr;
83203   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
83204   if( NEVER(ExprHasProperty(pExpr, EP_xIsSelect)) ) return 0;
83205   pEList = pExpr->x.pList;
83206   if( pEList==0 || pEList->nExpr!=1 ) return 0;
83207   if( pEList->a[0].pExpr->op!=TK_AGG_COLUMN ) return WHERE_ORDERBY_NORMAL;
83208   assert( !ExprHasProperty(pExpr, EP_IntValue) );
83209   if( sqlite3StrICmp(pExpr->u.zToken,"min")==0 ){
83210     return WHERE_ORDERBY_MIN;
83211   }else if( sqlite3StrICmp(pExpr->u.zToken,"max")==0 ){
83212     return WHERE_ORDERBY_MAX;
83213   }
83214   return WHERE_ORDERBY_NORMAL;
83215 }
83216
83217 /*
83218 ** The select statement passed as the first argument is an aggregate query.
83219 ** The second argment is the associated aggregate-info object. This 
83220 ** function tests if the SELECT is of the form:
83221 **
83222 **   SELECT count(*) FROM <tbl>
83223 **
83224 ** where table is a database table, not a sub-select or view. If the query
83225 ** does match this pattern, then a pointer to the Table object representing
83226 ** <tbl> is returned. Otherwise, 0 is returned.
83227 */
83228 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
83229   Table *pTab;
83230   Expr *pExpr;
83231
83232   assert( !p->pGroupBy );
83233
83234   if( p->pWhere || p->pEList->nExpr!=1 
83235    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
83236   ){
83237     return 0;
83238   }
83239   pTab = p->pSrc->a[0].pTab;
83240   pExpr = p->pEList->a[0].pExpr;
83241   assert( pTab && !pTab->pSelect && pExpr );
83242
83243   if( IsVirtual(pTab) ) return 0;
83244   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
83245   if( (pAggInfo->aFunc[0].pFunc->flags&SQLITE_FUNC_COUNT)==0 ) return 0;
83246   if( pExpr->flags&EP_Distinct ) return 0;
83247
83248   return pTab;
83249 }
83250
83251 /*
83252 ** If the source-list item passed as an argument was augmented with an
83253 ** INDEXED BY clause, then try to locate the specified index. If there
83254 ** was such a clause and the named index cannot be found, return 
83255 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
83256 ** pFrom->pIndex and return SQLITE_OK.
83257 */
83258 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
83259   if( pFrom->pTab && pFrom->zIndex ){
83260     Table *pTab = pFrom->pTab;
83261     char *zIndex = pFrom->zIndex;
83262     Index *pIdx;
83263     for(pIdx=pTab->pIndex; 
83264         pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
83265         pIdx=pIdx->pNext
83266     );
83267     if( !pIdx ){
83268       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
83269       return SQLITE_ERROR;
83270     }
83271     pFrom->pIndex = pIdx;
83272   }
83273   return SQLITE_OK;
83274 }
83275
83276 /*
83277 ** This routine is a Walker callback for "expanding" a SELECT statement.
83278 ** "Expanding" means to do the following:
83279 **
83280 **    (1)  Make sure VDBE cursor numbers have been assigned to every
83281 **         element of the FROM clause.
83282 **
83283 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
83284 **         defines FROM clause.  When views appear in the FROM clause,
83285 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
83286 **         that implements the view.  A copy is made of the view's SELECT
83287 **         statement so that we can freely modify or delete that statement
83288 **         without worrying about messing up the presistent representation
83289 **         of the view.
83290 **
83291 **    (3)  Add terms to the WHERE clause to accomodate the NATURAL keyword
83292 **         on joins and the ON and USING clause of joins.
83293 **
83294 **    (4)  Scan the list of columns in the result set (pEList) looking
83295 **         for instances of the "*" operator or the TABLE.* operator.
83296 **         If found, expand each "*" to be every column in every table
83297 **         and TABLE.* to be every column in TABLE.
83298 **
83299 */
83300 static int selectExpander(Walker *pWalker, Select *p){
83301   Parse *pParse = pWalker->pParse;
83302   int i, j, k;
83303   SrcList *pTabList;
83304   ExprList *pEList;
83305   struct SrcList_item *pFrom;
83306   sqlite3 *db = pParse->db;
83307
83308   if( db->mallocFailed  ){
83309     return WRC_Abort;
83310   }
83311   if( NEVER(p->pSrc==0) || (p->selFlags & SF_Expanded)!=0 ){
83312     return WRC_Prune;
83313   }
83314   p->selFlags |= SF_Expanded;
83315   pTabList = p->pSrc;
83316   pEList = p->pEList;
83317
83318   /* Make sure cursor numbers have been assigned to all entries in
83319   ** the FROM clause of the SELECT statement.
83320   */
83321   sqlite3SrcListAssignCursors(pParse, pTabList);
83322
83323   /* Look up every table named in the FROM clause of the select.  If
83324   ** an entry of the FROM clause is a subquery instead of a table or view,
83325   ** then create a transient table structure to describe the subquery.
83326   */
83327   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
83328     Table *pTab;
83329     if( pFrom->pTab!=0 ){
83330       /* This statement has already been prepared.  There is no need
83331       ** to go further. */
83332       assert( i==0 );
83333       return WRC_Prune;
83334     }
83335     if( pFrom->zName==0 ){
83336 #ifndef SQLITE_OMIT_SUBQUERY
83337       Select *pSel = pFrom->pSelect;
83338       /* A sub-query in the FROM clause of a SELECT */
83339       assert( pSel!=0 );
83340       assert( pFrom->pTab==0 );
83341       sqlite3WalkSelect(pWalker, pSel);
83342       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
83343       if( pTab==0 ) return WRC_Abort;
83344       pTab->dbMem = db->lookaside.bEnabled ? db : 0;
83345       pTab->nRef = 1;
83346       pTab->zName = sqlite3MPrintf(db, "sqlite_subquery_%p_", (void*)pTab);
83347       while( pSel->pPrior ){ pSel = pSel->pPrior; }
83348       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
83349       pTab->iPKey = -1;
83350       pTab->tabFlags |= TF_Ephemeral;
83351 #endif
83352     }else{
83353       /* An ordinary table or view name in the FROM clause */
83354       assert( pFrom->pTab==0 );
83355       pFrom->pTab = pTab = 
83356         sqlite3LocateTable(pParse,0,pFrom->zName,pFrom->zDatabase);
83357       if( pTab==0 ) return WRC_Abort;
83358       pTab->nRef++;
83359 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
83360       if( pTab->pSelect || IsVirtual(pTab) ){
83361         /* We reach here if the named table is a really a view */
83362         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
83363         assert( pFrom->pSelect==0 );
83364         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
83365         sqlite3WalkSelect(pWalker, pFrom->pSelect);
83366       }
83367 #endif
83368     }
83369
83370     /* Locate the index named by the INDEXED BY clause, if any. */
83371     if( sqlite3IndexedByLookup(pParse, pFrom) ){
83372       return WRC_Abort;
83373     }
83374   }
83375
83376   /* Process NATURAL keywords, and ON and USING clauses of joins.
83377   */
83378   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
83379     return WRC_Abort;
83380   }
83381
83382   /* For every "*" that occurs in the column list, insert the names of
83383   ** all columns in all tables.  And for every TABLE.* insert the names
83384   ** of all columns in TABLE.  The parser inserted a special expression
83385   ** with the TK_ALL operator for each "*" that it found in the column list.
83386   ** The following code just has to locate the TK_ALL expressions and expand
83387   ** each one to the list of all columns in all tables.
83388   **
83389   ** The first loop just checks to see if there are any "*" operators
83390   ** that need expanding.
83391   */
83392   for(k=0; k<pEList->nExpr; k++){
83393     Expr *pE = pEList->a[k].pExpr;
83394     if( pE->op==TK_ALL ) break;
83395     assert( pE->op!=TK_DOT || pE->pRight!=0 );
83396     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
83397     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
83398   }
83399   if( k<pEList->nExpr ){
83400     /*
83401     ** If we get here it means the result set contains one or more "*"
83402     ** operators that need to be expanded.  Loop through each expression
83403     ** in the result set and expand them one by one.
83404     */
83405     struct ExprList_item *a = pEList->a;
83406     ExprList *pNew = 0;
83407     int flags = pParse->db->flags;
83408     int longNames = (flags & SQLITE_FullColNames)!=0
83409                       && (flags & SQLITE_ShortColNames)==0;
83410
83411     for(k=0; k<pEList->nExpr; k++){
83412       Expr *pE = a[k].pExpr;
83413       assert( pE->op!=TK_DOT || pE->pRight!=0 );
83414       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pE->pRight->op!=TK_ALL) ){
83415         /* This particular expression does not need to be expanded.
83416         */
83417         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
83418         if( pNew ){
83419           pNew->a[pNew->nExpr-1].zName = a[k].zName;
83420           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
83421           a[k].zName = 0;
83422           a[k].zSpan = 0;
83423         }
83424         a[k].pExpr = 0;
83425       }else{
83426         /* This expression is a "*" or a "TABLE.*" and needs to be
83427         ** expanded. */
83428         int tableSeen = 0;      /* Set to 1 when TABLE matches */
83429         char *zTName;            /* text of name of TABLE */
83430         if( pE->op==TK_DOT ){
83431           assert( pE->pLeft!=0 );
83432           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
83433           zTName = pE->pLeft->u.zToken;
83434         }else{
83435           zTName = 0;
83436         }
83437         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
83438           Table *pTab = pFrom->pTab;
83439           char *zTabName = pFrom->zAlias;
83440           if( zTabName==0 ){
83441             zTabName = pTab->zName;
83442           }
83443           if( db->mallocFailed ) break;
83444           if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
83445             continue;
83446           }
83447           tableSeen = 1;
83448           for(j=0; j<pTab->nCol; j++){
83449             Expr *pExpr, *pRight;
83450             char *zName = pTab->aCol[j].zName;
83451             char *zColname;  /* The computed column name */
83452             char *zToFree;   /* Malloced string that needs to be freed */
83453             Token sColname;  /* Computed column name as a token */
83454
83455             /* If a column is marked as 'hidden' (currently only possible
83456             ** for virtual tables), do not include it in the expanded
83457             ** result-set list.
83458             */
83459             if( IsHiddenColumn(&pTab->aCol[j]) ){
83460               assert(IsVirtual(pTab));
83461               continue;
83462             }
83463
83464             if( i>0 && zTName==0 ){
83465               if( (pFrom->jointype & JT_NATURAL)!=0
83466                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
83467               ){
83468                 /* In a NATURAL join, omit the join columns from the 
83469                 ** table to the right of the join */
83470                 continue;
83471               }
83472               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
83473                 /* In a join with a USING clause, omit columns in the
83474                 ** using clause from the table on the right. */
83475                 continue;
83476               }
83477             }
83478             pRight = sqlite3Expr(db, TK_ID, zName);
83479             zColname = zName;
83480             zToFree = 0;
83481             if( longNames || pTabList->nSrc>1 ){
83482               Expr *pLeft;
83483               pLeft = sqlite3Expr(db, TK_ID, zTabName);
83484               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
83485               if( longNames ){
83486                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
83487                 zToFree = zColname;
83488               }
83489             }else{
83490               pExpr = pRight;
83491             }
83492             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
83493             sColname.z = zColname;
83494             sColname.n = sqlite3Strlen30(zColname);
83495             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
83496             sqlite3DbFree(db, zToFree);
83497           }
83498         }
83499         if( !tableSeen ){
83500           if( zTName ){
83501             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
83502           }else{
83503             sqlite3ErrorMsg(pParse, "no tables specified");
83504           }
83505         }
83506       }
83507     }
83508     sqlite3ExprListDelete(db, pEList);
83509     p->pEList = pNew;
83510   }
83511 #if SQLITE_MAX_COLUMN
83512   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
83513     sqlite3ErrorMsg(pParse, "too many columns in result set");
83514   }
83515 #endif
83516   return WRC_Continue;
83517 }
83518
83519 /*
83520 ** No-op routine for the parse-tree walker.
83521 **
83522 ** When this routine is the Walker.xExprCallback then expression trees
83523 ** are walked without any actions being taken at each node.  Presumably,
83524 ** when this routine is used for Walker.xExprCallback then 
83525 ** Walker.xSelectCallback is set to do something useful for every 
83526 ** subquery in the parser tree.
83527 */
83528 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
83529   UNUSED_PARAMETER2(NotUsed, NotUsed2);
83530   return WRC_Continue;
83531 }
83532
83533 /*
83534 ** This routine "expands" a SELECT statement and all of its subqueries.
83535 ** For additional information on what it means to "expand" a SELECT
83536 ** statement, see the comment on the selectExpand worker callback above.
83537 **
83538 ** Expanding a SELECT statement is the first step in processing a
83539 ** SELECT statement.  The SELECT statement must be expanded before
83540 ** name resolution is performed.
83541 **
83542 ** If anything goes wrong, an error message is written into pParse.
83543 ** The calling function can detect the problem by looking at pParse->nErr
83544 ** and/or pParse->db->mallocFailed.
83545 */
83546 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
83547   Walker w;
83548   w.xSelectCallback = selectExpander;
83549   w.xExprCallback = exprWalkNoop;
83550   w.pParse = pParse;
83551   sqlite3WalkSelect(&w, pSelect);
83552 }
83553
83554
83555 #ifndef SQLITE_OMIT_SUBQUERY
83556 /*
83557 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
83558 ** interface.
83559 **
83560 ** For each FROM-clause subquery, add Column.zType and Column.zColl
83561 ** information to the Table structure that represents the result set
83562 ** of that subquery.
83563 **
83564 ** The Table structure that represents the result set was constructed
83565 ** by selectExpander() but the type and collation information was omitted
83566 ** at that point because identifiers had not yet been resolved.  This
83567 ** routine is called after identifier resolution.
83568 */
83569 static int selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
83570   Parse *pParse;
83571   int i;
83572   SrcList *pTabList;
83573   struct SrcList_item *pFrom;
83574
83575   assert( p->selFlags & SF_Resolved );
83576   if( (p->selFlags & SF_HasTypeInfo)==0 ){
83577     p->selFlags |= SF_HasTypeInfo;
83578     pParse = pWalker->pParse;
83579     pTabList = p->pSrc;
83580     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
83581       Table *pTab = pFrom->pTab;
83582       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
83583         /* A sub-query in the FROM clause of a SELECT */
83584         Select *pSel = pFrom->pSelect;
83585         assert( pSel );
83586         while( pSel->pPrior ) pSel = pSel->pPrior;
83587         selectAddColumnTypeAndCollation(pParse, pTab->nCol, pTab->aCol, pSel);
83588       }
83589     }
83590   }
83591   return WRC_Continue;
83592 }
83593 #endif
83594
83595
83596 /*
83597 ** This routine adds datatype and collating sequence information to
83598 ** the Table structures of all FROM-clause subqueries in a
83599 ** SELECT statement.
83600 **
83601 ** Use this routine after name resolution.
83602 */
83603 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
83604 #ifndef SQLITE_OMIT_SUBQUERY
83605   Walker w;
83606   w.xSelectCallback = selectAddSubqueryTypeInfo;
83607   w.xExprCallback = exprWalkNoop;
83608   w.pParse = pParse;
83609   sqlite3WalkSelect(&w, pSelect);
83610 #endif
83611 }
83612
83613
83614 /*
83615 ** This routine sets of a SELECT statement for processing.  The
83616 ** following is accomplished:
83617 **
83618 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
83619 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
83620 **     *  ON and USING clauses are shifted into WHERE statements
83621 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
83622 **     *  Identifiers in expression are matched to tables.
83623 **
83624 ** This routine acts recursively on all subqueries within the SELECT.
83625 */
83626 SQLITE_PRIVATE void sqlite3SelectPrep(
83627   Parse *pParse,         /* The parser context */
83628   Select *p,             /* The SELECT statement being coded. */
83629   NameContext *pOuterNC  /* Name context for container */
83630 ){
83631   sqlite3 *db;
83632   if( NEVER(p==0) ) return;
83633   db = pParse->db;
83634   if( p->selFlags & SF_HasTypeInfo ) return;
83635   sqlite3SelectExpand(pParse, p);
83636   if( pParse->nErr || db->mallocFailed ) return;
83637   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
83638   if( pParse->nErr || db->mallocFailed ) return;
83639   sqlite3SelectAddTypeInfo(pParse, p);
83640 }
83641
83642 /*
83643 ** Reset the aggregate accumulator.
83644 **
83645 ** The aggregate accumulator is a set of memory cells that hold
83646 ** intermediate results while calculating an aggregate.  This
83647 ** routine simply stores NULLs in all of those memory cells.
83648 */
83649 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
83650   Vdbe *v = pParse->pVdbe;
83651   int i;
83652   struct AggInfo_func *pFunc;
83653   if( pAggInfo->nFunc+pAggInfo->nColumn==0 ){
83654     return;
83655   }
83656   for(i=0; i<pAggInfo->nColumn; i++){
83657     sqlite3VdbeAddOp2(v, OP_Null, 0, pAggInfo->aCol[i].iMem);
83658   }
83659   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
83660     sqlite3VdbeAddOp2(v, OP_Null, 0, pFunc->iMem);
83661     if( pFunc->iDistinct>=0 ){
83662       Expr *pE = pFunc->pExpr;
83663       assert( !ExprHasProperty(pE, EP_xIsSelect) );
83664       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
83665         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
83666            "argument");
83667         pFunc->iDistinct = -1;
83668       }else{
83669         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList);
83670         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
83671                           (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
83672       }
83673     }
83674   }
83675 }
83676
83677 /*
83678 ** Invoke the OP_AggFinalize opcode for every aggregate function
83679 ** in the AggInfo structure.
83680 */
83681 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
83682   Vdbe *v = pParse->pVdbe;
83683   int i;
83684   struct AggInfo_func *pF;
83685   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
83686     ExprList *pList = pF->pExpr->x.pList;
83687     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
83688     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
83689                       (void*)pF->pFunc, P4_FUNCDEF);
83690   }
83691 }
83692
83693 /*
83694 ** Update the accumulator memory cells for an aggregate based on
83695 ** the current cursor position.
83696 */
83697 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
83698   Vdbe *v = pParse->pVdbe;
83699   int i;
83700   struct AggInfo_func *pF;
83701   struct AggInfo_col *pC;
83702
83703   pAggInfo->directMode = 1;
83704   sqlite3ExprCacheClear(pParse);
83705   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
83706     int nArg;
83707     int addrNext = 0;
83708     int regAgg;
83709     ExprList *pList = pF->pExpr->x.pList;
83710     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
83711     if( pList ){
83712       nArg = pList->nExpr;
83713       regAgg = sqlite3GetTempRange(pParse, nArg);
83714       sqlite3ExprCodeExprList(pParse, pList, regAgg, 0);
83715     }else{
83716       nArg = 0;
83717       regAgg = 0;
83718     }
83719     if( pF->iDistinct>=0 ){
83720       addrNext = sqlite3VdbeMakeLabel(v);
83721       assert( nArg==1 );
83722       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
83723     }
83724     if( pF->pFunc->flags & SQLITE_FUNC_NEEDCOLL ){
83725       CollSeq *pColl = 0;
83726       struct ExprList_item *pItem;
83727       int j;
83728       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
83729       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
83730         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
83731       }
83732       if( !pColl ){
83733         pColl = pParse->db->pDfltColl;
83734       }
83735       sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
83736     }
83737     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
83738                       (void*)pF->pFunc, P4_FUNCDEF);
83739     sqlite3VdbeChangeP5(v, (u8)nArg);
83740     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
83741     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
83742     if( addrNext ){
83743       sqlite3VdbeResolveLabel(v, addrNext);
83744       sqlite3ExprCacheClear(pParse);
83745     }
83746   }
83747   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
83748     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
83749   }
83750   pAggInfo->directMode = 0;
83751   sqlite3ExprCacheClear(pParse);
83752 }
83753
83754 /*
83755 ** Generate code for the SELECT statement given in the p argument.  
83756 **
83757 ** The results are distributed in various ways depending on the
83758 ** contents of the SelectDest structure pointed to by argument pDest
83759 ** as follows:
83760 **
83761 **     pDest->eDest    Result
83762 **     ------------    -------------------------------------------
83763 **     SRT_Output      Generate a row of output (using the OP_ResultRow
83764 **                     opcode) for each row in the result set.
83765 **
83766 **     SRT_Mem         Only valid if the result is a single column.
83767 **                     Store the first column of the first result row
83768 **                     in register pDest->iParm then abandon the rest
83769 **                     of the query.  This destination implies "LIMIT 1".
83770 **
83771 **     SRT_Set         The result must be a single column.  Store each
83772 **                     row of result as the key in table pDest->iParm. 
83773 **                     Apply the affinity pDest->affinity before storing
83774 **                     results.  Used to implement "IN (SELECT ...)".
83775 **
83776 **     SRT_Union       Store results as a key in a temporary table pDest->iParm.
83777 **
83778 **     SRT_Except      Remove results from the temporary table pDest->iParm.
83779 **
83780 **     SRT_Table       Store results in temporary table pDest->iParm.
83781 **                     This is like SRT_EphemTab except that the table
83782 **                     is assumed to already be open.
83783 **
83784 **     SRT_EphemTab    Create an temporary table pDest->iParm and store
83785 **                     the result there. The cursor is left open after
83786 **                     returning.  This is like SRT_Table except that
83787 **                     this destination uses OP_OpenEphemeral to create
83788 **                     the table first.
83789 **
83790 **     SRT_Coroutine   Generate a co-routine that returns a new row of
83791 **                     results each time it is invoked.  The entry point
83792 **                     of the co-routine is stored in register pDest->iParm.
83793 **
83794 **     SRT_Exists      Store a 1 in memory cell pDest->iParm if the result
83795 **                     set is not empty.
83796 **
83797 **     SRT_Discard     Throw the results away.  This is used by SELECT
83798 **                     statements within triggers whose only purpose is
83799 **                     the side-effects of functions.
83800 **
83801 ** This routine returns the number of errors.  If any errors are
83802 ** encountered, then an appropriate error message is left in
83803 ** pParse->zErrMsg.
83804 **
83805 ** This routine does NOT free the Select structure passed in.  The
83806 ** calling function needs to do that.
83807 */
83808 SQLITE_PRIVATE int sqlite3Select(
83809   Parse *pParse,         /* The parser context */
83810   Select *p,             /* The SELECT statement being coded. */
83811   SelectDest *pDest      /* What to do with the query results */
83812 ){
83813   int i, j;              /* Loop counters */
83814   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
83815   Vdbe *v;               /* The virtual machine under construction */
83816   int isAgg;             /* True for select lists like "count(*)" */
83817   ExprList *pEList;      /* List of columns to extract. */
83818   SrcList *pTabList;     /* List of tables to select from */
83819   Expr *pWhere;          /* The WHERE clause.  May be NULL */
83820   ExprList *pOrderBy;    /* The ORDER BY clause.  May be NULL */
83821   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
83822   Expr *pHaving;         /* The HAVING clause.  May be NULL */
83823   int isDistinct;        /* True if the DISTINCT keyword is present */
83824   int distinct;          /* Table to use for the distinct set */
83825   int rc = 1;            /* Value to return from this function */
83826   int addrSortIndex;     /* Address of an OP_OpenEphemeral instruction */
83827   AggInfo sAggInfo;      /* Information used by aggregate queries */
83828   int iEnd;              /* Address of the end of the query */
83829   sqlite3 *db;           /* The database connection */
83830
83831   db = pParse->db;
83832   if( p==0 || db->mallocFailed || pParse->nErr ){
83833     return 1;
83834   }
83835   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
83836   memset(&sAggInfo, 0, sizeof(sAggInfo));
83837
83838   if( IgnorableOrderby(pDest) ){
83839     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
83840            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard);
83841     /* If ORDER BY makes no difference in the output then neither does
83842     ** DISTINCT so it can be removed too. */
83843     sqlite3ExprListDelete(db, p->pOrderBy);
83844     p->pOrderBy = 0;
83845     p->selFlags &= ~SF_Distinct;
83846   }
83847   sqlite3SelectPrep(pParse, p, 0);
83848   pOrderBy = p->pOrderBy;
83849   pTabList = p->pSrc;
83850   pEList = p->pEList;
83851   if( pParse->nErr || db->mallocFailed ){
83852     goto select_end;
83853   }
83854   isAgg = (p->selFlags & SF_Aggregate)!=0;
83855   assert( pEList!=0 );
83856
83857   /* Begin generating code.
83858   */
83859   v = sqlite3GetVdbe(pParse);
83860   if( v==0 ) goto select_end;
83861
83862   /* Generate code for all sub-queries in the FROM clause
83863   */
83864 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
83865   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
83866     struct SrcList_item *pItem = &pTabList->a[i];
83867     SelectDest dest;
83868     Select *pSub = pItem->pSelect;
83869     int isAggSub;
83870
83871     if( pSub==0 || pItem->isPopulated ) continue;
83872
83873     /* Increment Parse.nHeight by the height of the largest expression
83874     ** tree refered to by this, the parent select. The child select
83875     ** may contain expression trees of at most
83876     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
83877     ** more conservative than necessary, but much easier than enforcing
83878     ** an exact limit.
83879     */
83880     pParse->nHeight += sqlite3SelectExprHeight(p);
83881
83882     /* Check to see if the subquery can be absorbed into the parent. */
83883     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
83884     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
83885       if( isAggSub ){
83886         isAgg = 1;
83887         p->selFlags |= SF_Aggregate;
83888       }
83889       i = -1;
83890     }else{
83891       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
83892       assert( pItem->isPopulated==0 );
83893       sqlite3Select(pParse, pSub, &dest);
83894       pItem->isPopulated = 1;
83895     }
83896     if( /*pParse->nErr ||*/ db->mallocFailed ){
83897       goto select_end;
83898     }
83899     pParse->nHeight -= sqlite3SelectExprHeight(p);
83900     pTabList = p->pSrc;
83901     if( !IgnorableOrderby(pDest) ){
83902       pOrderBy = p->pOrderBy;
83903     }
83904   }
83905   pEList = p->pEList;
83906 #endif
83907   pWhere = p->pWhere;
83908   pGroupBy = p->pGroupBy;
83909   pHaving = p->pHaving;
83910   isDistinct = (p->selFlags & SF_Distinct)!=0;
83911
83912 #ifndef SQLITE_OMIT_COMPOUND_SELECT
83913   /* If there is are a sequence of queries, do the earlier ones first.
83914   */
83915   if( p->pPrior ){
83916     if( p->pRightmost==0 ){
83917       Select *pLoop, *pRight = 0;
83918       int cnt = 0;
83919       int mxSelect;
83920       for(pLoop=p; pLoop; pLoop=pLoop->pPrior, cnt++){
83921         pLoop->pRightmost = p;
83922         pLoop->pNext = pRight;
83923         pRight = pLoop;
83924       }
83925       mxSelect = db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
83926       if( mxSelect && cnt>mxSelect ){
83927         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
83928         return 1;
83929       }
83930     }
83931     return multiSelect(pParse, p, pDest);
83932   }
83933 #endif
83934
83935   /* If writing to memory or generating a set
83936   ** only a single column may be output.
83937   */
83938 #ifndef SQLITE_OMIT_SUBQUERY
83939   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
83940     goto select_end;
83941   }
83942 #endif
83943
83944   /* If possible, rewrite the query to use GROUP BY instead of DISTINCT.
83945   ** GROUP BY might use an index, DISTINCT never does.
83946   */
83947   assert( p->pGroupBy==0 || (p->selFlags & SF_Aggregate)!=0 );
83948   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct ){
83949     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
83950     pGroupBy = p->pGroupBy;
83951     p->selFlags &= ~SF_Distinct;
83952     isDistinct = 0;
83953   }
83954
83955   /* If there is an ORDER BY clause, then this sorting
83956   ** index might end up being unused if the data can be 
83957   ** extracted in pre-sorted order.  If that is the case, then the
83958   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
83959   ** we figure out that the sorting index is not needed.  The addrSortIndex
83960   ** variable is used to facilitate that change.
83961   */
83962   if( pOrderBy ){
83963     KeyInfo *pKeyInfo;
83964     pKeyInfo = keyInfoFromExprList(pParse, pOrderBy);
83965     pOrderBy->iECursor = pParse->nTab++;
83966     p->addrOpenEphm[2] = addrSortIndex =
83967       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
83968                            pOrderBy->iECursor, pOrderBy->nExpr+2, 0,
83969                            (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
83970   }else{
83971     addrSortIndex = -1;
83972   }
83973
83974   /* If the output is destined for a temporary table, open that table.
83975   */
83976   if( pDest->eDest==SRT_EphemTab ){
83977     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iParm, pEList->nExpr);
83978   }
83979
83980   /* Set the limiter.
83981   */
83982   iEnd = sqlite3VdbeMakeLabel(v);
83983   computeLimitRegisters(pParse, p, iEnd);
83984
83985   /* Open a virtual index to use for the distinct set.
83986   */
83987   if( isDistinct ){
83988     KeyInfo *pKeyInfo;
83989     assert( isAgg || pGroupBy );
83990     distinct = pParse->nTab++;
83991     pKeyInfo = keyInfoFromExprList(pParse, p->pEList);
83992     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, distinct, 0, 0,
83993                         (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
83994   }else{
83995     distinct = -1;
83996   }
83997
83998   /* Aggregate and non-aggregate queries are handled differently */
83999   if( !isAgg && pGroupBy==0 ){
84000     /* This case is for non-aggregate queries
84001     ** Begin the database scan
84002     */
84003     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pOrderBy, 0);
84004     if( pWInfo==0 ) goto select_end;
84005
84006     /* If sorting index that was created by a prior OP_OpenEphemeral 
84007     ** instruction ended up not being needed, then change the OP_OpenEphemeral
84008     ** into an OP_Noop.
84009     */
84010     if( addrSortIndex>=0 && pOrderBy==0 ){
84011       sqlite3VdbeChangeToNoop(v, addrSortIndex, 1);
84012       p->addrOpenEphm[2] = -1;
84013     }
84014
84015     /* Use the standard inner loop
84016     */
84017     assert(!isDistinct);
84018     selectInnerLoop(pParse, p, pEList, 0, 0, pOrderBy, -1, pDest,
84019                     pWInfo->iContinue, pWInfo->iBreak);
84020
84021     /* End the database scan loop.
84022     */
84023     sqlite3WhereEnd(pWInfo);
84024   }else{
84025     /* This is the processing for aggregate queries */
84026     NameContext sNC;    /* Name context for processing aggregate information */
84027     int iAMem;          /* First Mem address for storing current GROUP BY */
84028     int iBMem;          /* First Mem address for previous GROUP BY */
84029     int iUseFlag;       /* Mem address holding flag indicating that at least
84030                         ** one row of the input to the aggregator has been
84031                         ** processed */
84032     int iAbortFlag;     /* Mem address which causes query abort if positive */
84033     int groupBySort;    /* Rows come from source in GROUP BY order */
84034     int addrEnd;        /* End of processing for this SELECT */
84035
84036     /* Remove any and all aliases between the result set and the
84037     ** GROUP BY clause.
84038     */
84039     if( pGroupBy ){
84040       int k;                        /* Loop counter */
84041       struct ExprList_item *pItem;  /* For looping over expression in a list */
84042
84043       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
84044         pItem->iAlias = 0;
84045       }
84046       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
84047         pItem->iAlias = 0;
84048       }
84049     }
84050
84051  
84052     /* Create a label to jump to when we want to abort the query */
84053     addrEnd = sqlite3VdbeMakeLabel(v);
84054
84055     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
84056     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
84057     ** SELECT statement.
84058     */
84059     memset(&sNC, 0, sizeof(sNC));
84060     sNC.pParse = pParse;
84061     sNC.pSrcList = pTabList;
84062     sNC.pAggInfo = &sAggInfo;
84063     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr+1 : 0;
84064     sAggInfo.pGroupBy = pGroupBy;
84065     sqlite3ExprAnalyzeAggList(&sNC, pEList);
84066     sqlite3ExprAnalyzeAggList(&sNC, pOrderBy);
84067     if( pHaving ){
84068       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
84069     }
84070     sAggInfo.nAccumulator = sAggInfo.nColumn;
84071     for(i=0; i<sAggInfo.nFunc; i++){
84072       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
84073       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
84074     }
84075     if( db->mallocFailed ) goto select_end;
84076
84077     /* Processing for aggregates with GROUP BY is very different and
84078     ** much more complex than aggregates without a GROUP BY.
84079     */
84080     if( pGroupBy ){
84081       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
84082       int j1;             /* A-vs-B comparision jump */
84083       int addrOutputRow;  /* Start of subroutine that outputs a result row */
84084       int regOutputRow;   /* Return address register for output subroutine */
84085       int addrSetAbort;   /* Set the abort flag and return */
84086       int addrTopOfLoop;  /* Top of the input loop */
84087       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
84088       int addrReset;      /* Subroutine for resetting the accumulator */
84089       int regReset;       /* Return address register for reset subroutine */
84090
84091       /* If there is a GROUP BY clause we might need a sorting index to
84092       ** implement it.  Allocate that sorting index now.  If it turns out
84093       ** that we do not need it after all, the OpenEphemeral instruction
84094       ** will be converted into a Noop.  
84095       */
84096       sAggInfo.sortingIdx = pParse->nTab++;
84097       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy);
84098       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_OpenEphemeral, 
84099           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
84100           0, (char*)pKeyInfo, P4_KEYINFO_HANDOFF);
84101
84102       /* Initialize memory locations used by GROUP BY aggregate processing
84103       */
84104       iUseFlag = ++pParse->nMem;
84105       iAbortFlag = ++pParse->nMem;
84106       regOutputRow = ++pParse->nMem;
84107       addrOutputRow = sqlite3VdbeMakeLabel(v);
84108       regReset = ++pParse->nMem;
84109       addrReset = sqlite3VdbeMakeLabel(v);
84110       iAMem = pParse->nMem + 1;
84111       pParse->nMem += pGroupBy->nExpr;
84112       iBMem = pParse->nMem + 1;
84113       pParse->nMem += pGroupBy->nExpr;
84114       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
84115       VdbeComment((v, "clear abort flag"));
84116       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
84117       VdbeComment((v, "indicate accumulator empty"));
84118
84119       /* Begin a loop that will extract all source rows in GROUP BY order.
84120       ** This might involve two separate loops with an OP_Sort in between, or
84121       ** it might be a single loop that uses an index to extract information
84122       ** in the right order to begin with.
84123       */
84124       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
84125       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pGroupBy, 0);
84126       if( pWInfo==0 ) goto select_end;
84127       if( pGroupBy==0 ){
84128         /* The optimizer is able to deliver rows in group by order so
84129         ** we do not have to sort.  The OP_OpenEphemeral table will be
84130         ** cancelled later because we still need to use the pKeyInfo
84131         */
84132         pGroupBy = p->pGroupBy;
84133         groupBySort = 0;
84134       }else{
84135         /* Rows are coming out in undetermined order.  We have to push
84136         ** each row into a sorting index, terminate the first loop,
84137         ** then loop over the sorting index in order to get the output
84138         ** in sorted order
84139         */
84140         int regBase;
84141         int regRecord;
84142         int nCol;
84143         int nGroupBy;
84144
84145         groupBySort = 1;
84146         nGroupBy = pGroupBy->nExpr;
84147         nCol = nGroupBy + 1;
84148         j = nGroupBy+1;
84149         for(i=0; i<sAggInfo.nColumn; i++){
84150           if( sAggInfo.aCol[i].iSorterColumn>=j ){
84151             nCol++;
84152             j++;
84153           }
84154         }
84155         regBase = sqlite3GetTempRange(pParse, nCol);
84156         sqlite3ExprCacheClear(pParse);
84157         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
84158         sqlite3VdbeAddOp2(v, OP_Sequence, sAggInfo.sortingIdx,regBase+nGroupBy);
84159         j = nGroupBy+1;
84160         for(i=0; i<sAggInfo.nColumn; i++){
84161           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
84162           if( pCol->iSorterColumn>=j ){
84163             int r1 = j + regBase;
84164             int r2;
84165
84166             r2 = sqlite3ExprCodeGetColumn(pParse, 
84167                                pCol->pTab, pCol->iColumn, pCol->iTable, r1);
84168             if( r1!=r2 ){
84169               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
84170             }
84171             j++;
84172           }
84173         }
84174         regRecord = sqlite3GetTempReg(pParse);
84175         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
84176         sqlite3VdbeAddOp2(v, OP_IdxInsert, sAggInfo.sortingIdx, regRecord);
84177         sqlite3ReleaseTempReg(pParse, regRecord);
84178         sqlite3ReleaseTempRange(pParse, regBase, nCol);
84179         sqlite3WhereEnd(pWInfo);
84180         sqlite3VdbeAddOp2(v, OP_Sort, sAggInfo.sortingIdx, addrEnd);
84181         VdbeComment((v, "GROUP BY sort"));
84182         sAggInfo.useSortingIdx = 1;
84183         sqlite3ExprCacheClear(pParse);
84184       }
84185
84186       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
84187       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
84188       ** Then compare the current GROUP BY terms against the GROUP BY terms
84189       ** from the previous row currently stored in a0, a1, a2...
84190       */
84191       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
84192       sqlite3ExprCacheClear(pParse);
84193       for(j=0; j<pGroupBy->nExpr; j++){
84194         if( groupBySort ){
84195           sqlite3VdbeAddOp3(v, OP_Column, sAggInfo.sortingIdx, j, iBMem+j);
84196         }else{
84197           sAggInfo.directMode = 1;
84198           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
84199         }
84200       }
84201       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
84202                           (char*)pKeyInfo, P4_KEYINFO);
84203       j1 = sqlite3VdbeCurrentAddr(v);
84204       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1);
84205
84206       /* Generate code that runs whenever the GROUP BY changes.
84207       ** Changes in the GROUP BY are detected by the previous code
84208       ** block.  If there were no changes, this block is skipped.
84209       **
84210       ** This code copies current group by terms in b0,b1,b2,...
84211       ** over to a0,a1,a2.  It then calls the output subroutine
84212       ** and resets the aggregate accumulator registers in preparation
84213       ** for the next GROUP BY batch.
84214       */
84215       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
84216       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
84217       VdbeComment((v, "output one row"));
84218       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd);
84219       VdbeComment((v, "check abort flag"));
84220       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
84221       VdbeComment((v, "reset accumulator"));
84222
84223       /* Update the aggregate accumulators based on the content of
84224       ** the current row
84225       */
84226       sqlite3VdbeJumpHere(v, j1);
84227       updateAccumulator(pParse, &sAggInfo);
84228       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
84229       VdbeComment((v, "indicate data in accumulator"));
84230
84231       /* End of the loop
84232       */
84233       if( groupBySort ){
84234         sqlite3VdbeAddOp2(v, OP_Next, sAggInfo.sortingIdx, addrTopOfLoop);
84235       }else{
84236         sqlite3WhereEnd(pWInfo);
84237         sqlite3VdbeChangeToNoop(v, addrSortingIdx, 1);
84238       }
84239
84240       /* Output the final row of result
84241       */
84242       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
84243       VdbeComment((v, "output final row"));
84244
84245       /* Jump over the subroutines
84246       */
84247       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
84248
84249       /* Generate a subroutine that outputs a single row of the result
84250       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
84251       ** is less than or equal to zero, the subroutine is a no-op.  If
84252       ** the processing calls for the query to abort, this subroutine
84253       ** increments the iAbortFlag memory location before returning in
84254       ** order to signal the caller to abort.
84255       */
84256       addrSetAbort = sqlite3VdbeCurrentAddr(v);
84257       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
84258       VdbeComment((v, "set abort flag"));
84259       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
84260       sqlite3VdbeResolveLabel(v, addrOutputRow);
84261       addrOutputRow = sqlite3VdbeCurrentAddr(v);
84262       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
84263       VdbeComment((v, "Groupby result generator entry point"));
84264       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
84265       finalizeAggFunctions(pParse, &sAggInfo);
84266       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
84267       selectInnerLoop(pParse, p, p->pEList, 0, 0, pOrderBy,
84268                       distinct, pDest,
84269                       addrOutputRow+1, addrSetAbort);
84270       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
84271       VdbeComment((v, "end groupby result generator"));
84272
84273       /* Generate a subroutine that will reset the group-by accumulator
84274       */
84275       sqlite3VdbeResolveLabel(v, addrReset);
84276       resetAccumulator(pParse, &sAggInfo);
84277       sqlite3VdbeAddOp1(v, OP_Return, regReset);
84278      
84279     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
84280     else {
84281       ExprList *pDel = 0;
84282 #ifndef SQLITE_OMIT_BTREECOUNT
84283       Table *pTab;
84284       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
84285         /* If isSimpleCount() returns a pointer to a Table structure, then
84286         ** the SQL statement is of the form:
84287         **
84288         **   SELECT count(*) FROM <tbl>
84289         **
84290         ** where the Table structure returned represents table <tbl>.
84291         **
84292         ** This statement is so common that it is optimized specially. The
84293         ** OP_Count instruction is executed either on the intkey table that
84294         ** contains the data for table <tbl> or on one of its indexes. It
84295         ** is better to execute the op on an index, as indexes are almost
84296         ** always spread across less pages than their corresponding tables.
84297         */
84298         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
84299         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
84300         Index *pIdx;                         /* Iterator variable */
84301         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
84302         Index *pBest = 0;                    /* Best index found so far */
84303         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
84304
84305         sqlite3CodeVerifySchema(pParse, iDb);
84306         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
84307
84308         /* Search for the index that has the least amount of columns. If
84309         ** there is such an index, and it has less columns than the table
84310         ** does, then we can assume that it consumes less space on disk and
84311         ** will therefore be cheaper to scan to determine the query result.
84312         ** In this case set iRoot to the root page number of the index b-tree
84313         ** and pKeyInfo to the KeyInfo structure required to navigate the
84314         ** index.
84315         **
84316         ** In practice the KeyInfo structure will not be used. It is only 
84317         ** passed to keep OP_OpenRead happy.
84318         */
84319         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
84320           if( !pBest || pIdx->nColumn<pBest->nColumn ){
84321             pBest = pIdx;
84322           }
84323         }
84324         if( pBest && pBest->nColumn<pTab->nCol ){
84325           iRoot = pBest->tnum;
84326           pKeyInfo = sqlite3IndexKeyinfo(pParse, pBest);
84327         }
84328
84329         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
84330         sqlite3VdbeAddOp3(v, OP_OpenRead, iCsr, iRoot, iDb);
84331         if( pKeyInfo ){
84332           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO_HANDOFF);
84333         }
84334         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
84335         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
84336       }else
84337 #endif /* SQLITE_OMIT_BTREECOUNT */
84338       {
84339         /* Check if the query is of one of the following forms:
84340         **
84341         **   SELECT min(x) FROM ...
84342         **   SELECT max(x) FROM ...
84343         **
84344         ** If it is, then ask the code in where.c to attempt to sort results
84345         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
84346         ** If where.c is able to produce results sorted in this order, then
84347         ** add vdbe code to break out of the processing loop after the 
84348         ** first iteration (since the first iteration of the loop is 
84349         ** guaranteed to operate on the row with the minimum or maximum 
84350         ** value of x, the only row required).
84351         **
84352         ** A special flag must be passed to sqlite3WhereBegin() to slightly
84353         ** modify behaviour as follows:
84354         **
84355         **   + If the query is a "SELECT min(x)", then the loop coded by
84356         **     where.c should not iterate over any values with a NULL value
84357         **     for x.
84358         **
84359         **   + The optimizer code in where.c (the thing that decides which
84360         **     index or indices to use) should place a different priority on 
84361         **     satisfying the 'ORDER BY' clause than it does in other cases.
84362         **     Refer to code and comments in where.c for details.
84363         */
84364         ExprList *pMinMax = 0;
84365         u8 flag = minMaxQuery(p);
84366         if( flag ){
84367           assert( !ExprHasProperty(p->pEList->a[0].pExpr, EP_xIsSelect) );
84368           pMinMax = sqlite3ExprListDup(db, p->pEList->a[0].pExpr->x.pList,0);
84369           pDel = pMinMax;
84370           if( pMinMax && !db->mallocFailed ){
84371             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
84372             pMinMax->a[0].pExpr->op = TK_COLUMN;
84373           }
84374         }
84375   
84376         /* This case runs if the aggregate has no GROUP BY clause.  The
84377         ** processing is much simpler since there is only a single row
84378         ** of output.
84379         */
84380         resetAccumulator(pParse, &sAggInfo);
84381         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, &pMinMax, flag);
84382         if( pWInfo==0 ){
84383           sqlite3ExprListDelete(db, pDel);
84384           goto select_end;
84385         }
84386         updateAccumulator(pParse, &sAggInfo);
84387         if( !pMinMax && flag ){
84388           sqlite3VdbeAddOp2(v, OP_Goto, 0, pWInfo->iBreak);
84389           VdbeComment((v, "%s() by index",
84390                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
84391         }
84392         sqlite3WhereEnd(pWInfo);
84393         finalizeAggFunctions(pParse, &sAggInfo);
84394       }
84395
84396       pOrderBy = 0;
84397       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
84398       selectInnerLoop(pParse, p, p->pEList, 0, 0, 0, -1, 
84399                       pDest, addrEnd, addrEnd);
84400       sqlite3ExprListDelete(db, pDel);
84401     }
84402     sqlite3VdbeResolveLabel(v, addrEnd);
84403     
84404   } /* endif aggregate query */
84405
84406   /* If there is an ORDER BY clause, then we need to sort the results
84407   ** and send them to the callback one by one.
84408   */
84409   if( pOrderBy ){
84410     generateSortTail(pParse, p, v, pEList->nExpr, pDest);
84411   }
84412
84413   /* Jump here to skip this query
84414   */
84415   sqlite3VdbeResolveLabel(v, iEnd);
84416
84417   /* The SELECT was successfully coded.   Set the return code to 0
84418   ** to indicate no errors.
84419   */
84420   rc = 0;
84421
84422   /* Control jumps to here if an error is encountered above, or upon
84423   ** successful coding of the SELECT.
84424   */
84425 select_end:
84426
84427   /* Identify column names if results of the SELECT are to be output.
84428   */
84429   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
84430     generateColumnNames(pParse, pTabList, pEList);
84431   }
84432
84433   sqlite3DbFree(db, sAggInfo.aCol);
84434   sqlite3DbFree(db, sAggInfo.aFunc);
84435   return rc;
84436 }
84437
84438 #if defined(SQLITE_DEBUG)
84439 /*
84440 *******************************************************************************
84441 ** The following code is used for testing and debugging only.  The code
84442 ** that follows does not appear in normal builds.
84443 **
84444 ** These routines are used to print out the content of all or part of a 
84445 ** parse structures such as Select or Expr.  Such printouts are useful
84446 ** for helping to understand what is happening inside the code generator
84447 ** during the execution of complex SELECT statements.
84448 **
84449 ** These routine are not called anywhere from within the normal
84450 ** code base.  Then are intended to be called from within the debugger
84451 ** or from temporary "printf" statements inserted for debugging.
84452 */
84453 SQLITE_PRIVATE void sqlite3PrintExpr(Expr *p){
84454   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
84455     sqlite3DebugPrintf("(%s", p->u.zToken);
84456   }else{
84457     sqlite3DebugPrintf("(%d", p->op);
84458   }
84459   if( p->pLeft ){
84460     sqlite3DebugPrintf(" ");
84461     sqlite3PrintExpr(p->pLeft);
84462   }
84463   if( p->pRight ){
84464     sqlite3DebugPrintf(" ");
84465     sqlite3PrintExpr(p->pRight);
84466   }
84467   sqlite3DebugPrintf(")");
84468 }
84469 SQLITE_PRIVATE void sqlite3PrintExprList(ExprList *pList){
84470   int i;
84471   for(i=0; i<pList->nExpr; i++){
84472     sqlite3PrintExpr(pList->a[i].pExpr);
84473     if( i<pList->nExpr-1 ){
84474       sqlite3DebugPrintf(", ");
84475     }
84476   }
84477 }
84478 SQLITE_PRIVATE void sqlite3PrintSelect(Select *p, int indent){
84479   sqlite3DebugPrintf("%*sSELECT(%p) ", indent, "", p);
84480   sqlite3PrintExprList(p->pEList);
84481   sqlite3DebugPrintf("\n");
84482   if( p->pSrc ){
84483     char *zPrefix;
84484     int i;
84485     zPrefix = "FROM";
84486     for(i=0; i<p->pSrc->nSrc; i++){
84487       struct SrcList_item *pItem = &p->pSrc->a[i];
84488       sqlite3DebugPrintf("%*s ", indent+6, zPrefix);
84489       zPrefix = "";
84490       if( pItem->pSelect ){
84491         sqlite3DebugPrintf("(\n");
84492         sqlite3PrintSelect(pItem->pSelect, indent+10);
84493         sqlite3DebugPrintf("%*s)", indent+8, "");
84494       }else if( pItem->zName ){
84495         sqlite3DebugPrintf("%s", pItem->zName);
84496       }
84497       if( pItem->pTab ){
84498         sqlite3DebugPrintf("(table: %s)", pItem->pTab->zName);
84499       }
84500       if( pItem->zAlias ){
84501         sqlite3DebugPrintf(" AS %s", pItem->zAlias);
84502       }
84503       if( i<p->pSrc->nSrc-1 ){
84504         sqlite3DebugPrintf(",");
84505       }
84506       sqlite3DebugPrintf("\n");
84507     }
84508   }
84509   if( p->pWhere ){
84510     sqlite3DebugPrintf("%*s WHERE ", indent, "");
84511     sqlite3PrintExpr(p->pWhere);
84512     sqlite3DebugPrintf("\n");
84513   }
84514   if( p->pGroupBy ){
84515     sqlite3DebugPrintf("%*s GROUP BY ", indent, "");
84516     sqlite3PrintExprList(p->pGroupBy);
84517     sqlite3DebugPrintf("\n");
84518   }
84519   if( p->pHaving ){
84520     sqlite3DebugPrintf("%*s HAVING ", indent, "");
84521     sqlite3PrintExpr(p->pHaving);
84522     sqlite3DebugPrintf("\n");
84523   }
84524   if( p->pOrderBy ){
84525     sqlite3DebugPrintf("%*s ORDER BY ", indent, "");
84526     sqlite3PrintExprList(p->pOrderBy);
84527     sqlite3DebugPrintf("\n");
84528   }
84529 }
84530 /* End of the structure debug printing code
84531 *****************************************************************************/
84532 #endif /* defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
84533
84534 /************** End of select.c **********************************************/
84535 /************** Begin file table.c *******************************************/
84536 /*
84537 ** 2001 September 15
84538 **
84539 ** The author disclaims copyright to this source code.  In place of
84540 ** a legal notice, here is a blessing:
84541 **
84542 **    May you do good and not evil.
84543 **    May you find forgiveness for yourself and forgive others.
84544 **    May you share freely, never taking more than you give.
84545 **
84546 *************************************************************************
84547 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
84548 ** interface routines.  These are just wrappers around the main
84549 ** interface routine of sqlite3_exec().
84550 **
84551 ** These routines are in a separate files so that they will not be linked
84552 ** if they are not used.
84553 */
84554
84555 #ifndef SQLITE_OMIT_GET_TABLE
84556
84557 /*
84558 ** This structure is used to pass data from sqlite3_get_table() through
84559 ** to the callback function is uses to build the result.
84560 */
84561 typedef struct TabResult {
84562   char **azResult;   /* Accumulated output */
84563   char *zErrMsg;     /* Error message text, if an error occurs */
84564   int nAlloc;        /* Slots allocated for azResult[] */
84565   int nRow;          /* Number of rows in the result */
84566   int nColumn;       /* Number of columns in the result */
84567   int nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
84568   int rc;            /* Return code from sqlite3_exec() */
84569 } TabResult;
84570
84571 /*
84572 ** This routine is called once for each row in the result table.  Its job
84573 ** is to fill in the TabResult structure appropriately, allocating new
84574 ** memory as necessary.
84575 */
84576 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
84577   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
84578   int need;                         /* Slots needed in p->azResult[] */
84579   int i;                            /* Loop counter */
84580   char *z;                          /* A single column of result */
84581
84582   /* Make sure there is enough space in p->azResult to hold everything
84583   ** we need to remember from this invocation of the callback.
84584   */
84585   if( p->nRow==0 && argv!=0 ){
84586     need = nCol*2;
84587   }else{
84588     need = nCol;
84589   }
84590   if( p->nData + need > p->nAlloc ){
84591     char **azNew;
84592     p->nAlloc = p->nAlloc*2 + need;
84593     azNew = sqlite3_realloc( p->azResult, sizeof(char*)*p->nAlloc );
84594     if( azNew==0 ) goto malloc_failed;
84595     p->azResult = azNew;
84596   }
84597
84598   /* If this is the first row, then generate an extra row containing
84599   ** the names of all columns.
84600   */
84601   if( p->nRow==0 ){
84602     p->nColumn = nCol;
84603     for(i=0; i<nCol; i++){
84604       z = sqlite3_mprintf("%s", colv[i]);
84605       if( z==0 ) goto malloc_failed;
84606       p->azResult[p->nData++] = z;
84607     }
84608   }else if( p->nColumn!=nCol ){
84609     sqlite3_free(p->zErrMsg);
84610     p->zErrMsg = sqlite3_mprintf(
84611        "sqlite3_get_table() called with two or more incompatible queries"
84612     );
84613     p->rc = SQLITE_ERROR;
84614     return 1;
84615   }
84616
84617   /* Copy over the row data
84618   */
84619   if( argv!=0 ){
84620     for(i=0; i<nCol; i++){
84621       if( argv[i]==0 ){
84622         z = 0;
84623       }else{
84624         int n = sqlite3Strlen30(argv[i])+1;
84625         z = sqlite3_malloc( n );
84626         if( z==0 ) goto malloc_failed;
84627         memcpy(z, argv[i], n);
84628       }
84629       p->azResult[p->nData++] = z;
84630     }
84631     p->nRow++;
84632   }
84633   return 0;
84634
84635 malloc_failed:
84636   p->rc = SQLITE_NOMEM;
84637   return 1;
84638 }
84639
84640 /*
84641 ** Query the database.  But instead of invoking a callback for each row,
84642 ** malloc() for space to hold the result and return the entire results
84643 ** at the conclusion of the call.
84644 **
84645 ** The result that is written to ***pazResult is held in memory obtained
84646 ** from malloc().  But the caller cannot free this memory directly.  
84647 ** Instead, the entire table should be passed to sqlite3_free_table() when
84648 ** the calling procedure is finished using it.
84649 */
84650 SQLITE_API int sqlite3_get_table(
84651   sqlite3 *db,                /* The database on which the SQL executes */
84652   const char *zSql,           /* The SQL to be executed */
84653   char ***pazResult,          /* Write the result table here */
84654   int *pnRow,                 /* Write the number of rows in the result here */
84655   int *pnColumn,              /* Write the number of columns of result here */
84656   char **pzErrMsg             /* Write error messages here */
84657 ){
84658   int rc;
84659   TabResult res;
84660
84661   *pazResult = 0;
84662   if( pnColumn ) *pnColumn = 0;
84663   if( pnRow ) *pnRow = 0;
84664   if( pzErrMsg ) *pzErrMsg = 0;
84665   res.zErrMsg = 0;
84666   res.nRow = 0;
84667   res.nColumn = 0;
84668   res.nData = 1;
84669   res.nAlloc = 20;
84670   res.rc = SQLITE_OK;
84671   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
84672   if( res.azResult==0 ){
84673      db->errCode = SQLITE_NOMEM;
84674      return SQLITE_NOMEM;
84675   }
84676   res.azResult[0] = 0;
84677   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
84678   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
84679   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
84680   if( (rc&0xff)==SQLITE_ABORT ){
84681     sqlite3_free_table(&res.azResult[1]);
84682     if( res.zErrMsg ){
84683       if( pzErrMsg ){
84684         sqlite3_free(*pzErrMsg);
84685         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
84686       }
84687       sqlite3_free(res.zErrMsg);
84688     }
84689     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
84690     return res.rc;
84691   }
84692   sqlite3_free(res.zErrMsg);
84693   if( rc!=SQLITE_OK ){
84694     sqlite3_free_table(&res.azResult[1]);
84695     return rc;
84696   }
84697   if( res.nAlloc>res.nData ){
84698     char **azNew;
84699     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
84700     if( azNew==0 ){
84701       sqlite3_free_table(&res.azResult[1]);
84702       db->errCode = SQLITE_NOMEM;
84703       return SQLITE_NOMEM;
84704     }
84705     res.azResult = azNew;
84706   }
84707   *pazResult = &res.azResult[1];
84708   if( pnColumn ) *pnColumn = res.nColumn;
84709   if( pnRow ) *pnRow = res.nRow;
84710   return rc;
84711 }
84712
84713 /*
84714 ** This routine frees the space the sqlite3_get_table() malloced.
84715 */
84716 SQLITE_API void sqlite3_free_table(
84717   char **azResult            /* Result returned from from sqlite3_get_table() */
84718 ){
84719   if( azResult ){
84720     int i, n;
84721     azResult--;
84722     assert( azResult!=0 );
84723     n = SQLITE_PTR_TO_INT(azResult[0]);
84724     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
84725     sqlite3_free(azResult);
84726   }
84727 }
84728
84729 #endif /* SQLITE_OMIT_GET_TABLE */
84730
84731 /************** End of table.c ***********************************************/
84732 /************** Begin file trigger.c *****************************************/
84733 /*
84734 **
84735 ** The author disclaims copyright to this source code.  In place of
84736 ** a legal notice, here is a blessing:
84737 **
84738 **    May you do good and not evil.
84739 **    May you find forgiveness for yourself and forgive others.
84740 **    May you share freely, never taking more than you give.
84741 **
84742 *************************************************************************
84743 ** This file contains the implementation for TRIGGERs
84744 */
84745
84746 #ifndef SQLITE_OMIT_TRIGGER
84747 /*
84748 ** Delete a linked list of TriggerStep structures.
84749 */
84750 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
84751   while( pTriggerStep ){
84752     TriggerStep * pTmp = pTriggerStep;
84753     pTriggerStep = pTriggerStep->pNext;
84754
84755     sqlite3ExprDelete(db, pTmp->pWhere);
84756     sqlite3ExprListDelete(db, pTmp->pExprList);
84757     sqlite3SelectDelete(db, pTmp->pSelect);
84758     sqlite3IdListDelete(db, pTmp->pIdList);
84759
84760     sqlite3DbFree(db, pTmp);
84761   }
84762 }
84763
84764 /*
84765 ** Given table pTab, return a list of all the triggers attached to 
84766 ** the table. The list is connected by Trigger.pNext pointers.
84767 **
84768 ** All of the triggers on pTab that are in the same database as pTab
84769 ** are already attached to pTab->pTrigger.  But there might be additional
84770 ** triggers on pTab in the TEMP schema.  This routine prepends all
84771 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
84772 ** and returns the combined list.
84773 **
84774 ** To state it another way:  This routine returns a list of all triggers
84775 ** that fire off of pTab.  The list will include any TEMP triggers on
84776 ** pTab as well as the triggers lised in pTab->pTrigger.
84777 */
84778 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
84779   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
84780   Trigger *pList = 0;                  /* List of triggers to return */
84781
84782   if( pParse->disableTriggers ){
84783     return 0;
84784   }
84785
84786   if( pTmpSchema!=pTab->pSchema ){
84787     HashElem *p;
84788     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
84789       Trigger *pTrig = (Trigger *)sqliteHashData(p);
84790       if( pTrig->pTabSchema==pTab->pSchema
84791        && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 
84792       ){
84793         pTrig->pNext = (pList ? pList : pTab->pTrigger);
84794         pList = pTrig;
84795       }
84796     }
84797   }
84798
84799   return (pList ? pList : pTab->pTrigger);
84800 }
84801
84802 /*
84803 ** This is called by the parser when it sees a CREATE TRIGGER statement
84804 ** up to the point of the BEGIN before the trigger actions.  A Trigger
84805 ** structure is generated based on the information available and stored
84806 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
84807 ** sqlite3FinishTrigger() function is called to complete the trigger
84808 ** construction process.
84809 */
84810 SQLITE_PRIVATE void sqlite3BeginTrigger(
84811   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
84812   Token *pName1,      /* The name of the trigger */
84813   Token *pName2,      /* The name of the trigger */
84814   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
84815   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
84816   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
84817   SrcList *pTableName,/* The name of the table/view the trigger applies to */
84818   Expr *pWhen,        /* WHEN clause */
84819   int isTemp,         /* True if the TEMPORARY keyword is present */
84820   int noErr           /* Suppress errors if the trigger already exists */
84821 ){
84822   Trigger *pTrigger = 0;  /* The new trigger */
84823   Table *pTab;            /* Table that the trigger fires off of */
84824   char *zName = 0;        /* Name of the trigger */
84825   sqlite3 *db = pParse->db;  /* The database connection */
84826   int iDb;                /* The database to store the trigger in */
84827   Token *pName;           /* The unqualified db name */
84828   DbFixer sFix;           /* State vector for the DB fixer */
84829   int iTabDb;             /* Index of the database holding pTab */
84830
84831   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
84832   assert( pName2!=0 );
84833   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
84834   assert( op>0 && op<0xff );
84835   if( isTemp ){
84836     /* If TEMP was specified, then the trigger name may not be qualified. */
84837     if( pName2->n>0 ){
84838       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
84839       goto trigger_cleanup;
84840     }
84841     iDb = 1;
84842     pName = pName1;
84843   }else{
84844     /* Figure out the db that the the trigger will be created in */
84845     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
84846     if( iDb<0 ){
84847       goto trigger_cleanup;
84848     }
84849   }
84850
84851   /* If the trigger name was unqualified, and the table is a temp table,
84852   ** then set iDb to 1 to create the trigger in the temporary database.
84853   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
84854   ** exist, the error is caught by the block below.
84855   */
84856   if( !pTableName || db->mallocFailed ){
84857     goto trigger_cleanup;
84858   }
84859   pTab = sqlite3SrcListLookup(pParse, pTableName);
84860   if( db->init.busy==0 && pName2->n==0 && pTab
84861         && pTab->pSchema==db->aDb[1].pSchema ){
84862     iDb = 1;
84863   }
84864
84865   /* Ensure the table name matches database name and that the table exists */
84866   if( db->mallocFailed ) goto trigger_cleanup;
84867   assert( pTableName->nSrc==1 );
84868   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) && 
84869       sqlite3FixSrcList(&sFix, pTableName) ){
84870     goto trigger_cleanup;
84871   }
84872   pTab = sqlite3SrcListLookup(pParse, pTableName);
84873   if( !pTab ){
84874     /* The table does not exist. */
84875     if( db->init.iDb==1 ){
84876       /* Ticket #3810.
84877       ** Normally, whenever a table is dropped, all associated triggers are
84878       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
84879       ** and the table is dropped by a different database connection, the
84880       ** trigger is not visible to the database connection that does the
84881       ** drop so the trigger cannot be dropped.  This results in an
84882       ** "orphaned trigger" - a trigger whose associated table is missing.
84883       */
84884       db->init.orphanTrigger = 1;
84885     }
84886     goto trigger_cleanup;
84887   }
84888   if( IsVirtual(pTab) ){
84889     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
84890     goto trigger_cleanup;
84891   }
84892
84893   /* Check that the trigger name is not reserved and that no trigger of the
84894   ** specified name exists */
84895   zName = sqlite3NameFromToken(db, pName);
84896   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
84897     goto trigger_cleanup;
84898   }
84899   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
84900                       zName, sqlite3Strlen30(zName)) ){
84901     if( !noErr ){
84902       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
84903     }
84904     goto trigger_cleanup;
84905   }
84906
84907   /* Do not create a trigger on a system table */
84908   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
84909     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
84910     pParse->nErr++;
84911     goto trigger_cleanup;
84912   }
84913
84914   /* INSTEAD of triggers are only for views and views only support INSTEAD
84915   ** of triggers.
84916   */
84917   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
84918     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
84919         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
84920     goto trigger_cleanup;
84921   }
84922   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
84923     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
84924         " trigger on table: %S", pTableName, 0);
84925     goto trigger_cleanup;
84926   }
84927   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84928
84929 #ifndef SQLITE_OMIT_AUTHORIZATION
84930   {
84931     int code = SQLITE_CREATE_TRIGGER;
84932     const char *zDb = db->aDb[iTabDb].zName;
84933     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
84934     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
84935     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
84936       goto trigger_cleanup;
84937     }
84938     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
84939       goto trigger_cleanup;
84940     }
84941   }
84942 #endif
84943
84944   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
84945   ** cannot appear on views.  So we might as well translate every
84946   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
84947   ** elsewhere.
84948   */
84949   if (tr_tm == TK_INSTEAD){
84950     tr_tm = TK_BEFORE;
84951   }
84952
84953   /* Build the Trigger object */
84954   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
84955   if( pTrigger==0 ) goto trigger_cleanup;
84956   pTrigger->zName = zName;
84957   zName = 0;
84958   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
84959   pTrigger->pSchema = db->aDb[iDb].pSchema;
84960   pTrigger->pTabSchema = pTab->pSchema;
84961   pTrigger->op = (u8)op;
84962   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
84963   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
84964   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
84965   assert( pParse->pNewTrigger==0 );
84966   pParse->pNewTrigger = pTrigger;
84967
84968 trigger_cleanup:
84969   sqlite3DbFree(db, zName);
84970   sqlite3SrcListDelete(db, pTableName);
84971   sqlite3IdListDelete(db, pColumns);
84972   sqlite3ExprDelete(db, pWhen);
84973   if( !pParse->pNewTrigger ){
84974     sqlite3DeleteTrigger(db, pTrigger);
84975   }else{
84976     assert( pParse->pNewTrigger==pTrigger );
84977   }
84978 }
84979
84980 /*
84981 ** This routine is called after all of the trigger actions have been parsed
84982 ** in order to complete the process of building the trigger.
84983 */
84984 SQLITE_PRIVATE void sqlite3FinishTrigger(
84985   Parse *pParse,          /* Parser context */
84986   TriggerStep *pStepList, /* The triggered program */
84987   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
84988 ){
84989   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
84990   char *zName;                            /* Name of trigger */
84991   sqlite3 *db = pParse->db;               /* The database */
84992   DbFixer sFix;                           /* Fixer object */
84993   int iDb;                                /* Database containing the trigger */
84994   Token nameToken;                        /* Trigger name for error reporting */
84995
84996   pTrig = pParse->pNewTrigger;
84997   pParse->pNewTrigger = 0;
84998   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
84999   zName = pTrig->zName;
85000   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
85001   pTrig->step_list = pStepList;
85002   while( pStepList ){
85003     pStepList->pTrig = pTrig;
85004     pStepList = pStepList->pNext;
85005   }
85006   nameToken.z = pTrig->zName;
85007   nameToken.n = sqlite3Strlen30(nameToken.z);
85008   if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken) 
85009           && sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
85010     goto triggerfinish_cleanup;
85011   }
85012
85013   /* if we are not initializing,
85014   ** build the sqlite_master entry
85015   */
85016   if( !db->init.busy ){
85017     Vdbe *v;
85018     char *z;
85019
85020     /* Make an entry in the sqlite_master table */
85021     v = sqlite3GetVdbe(pParse);
85022     if( v==0 ) goto triggerfinish_cleanup;
85023     sqlite3BeginWriteOperation(pParse, 0, iDb);
85024     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
85025     sqlite3NestedParse(pParse,
85026        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
85027        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
85028        pTrig->table, z);
85029     sqlite3DbFree(db, z);
85030     sqlite3ChangeCookie(pParse, iDb);
85031     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
85032         db, "type='trigger' AND name='%q'", zName), P4_DYNAMIC
85033     );
85034   }
85035
85036   if( db->init.busy ){
85037     Trigger *pLink = pTrig;
85038     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
85039     pTrig = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), pTrig);
85040     if( pTrig ){
85041       db->mallocFailed = 1;
85042     }else if( pLink->pSchema==pLink->pTabSchema ){
85043       Table *pTab;
85044       int n = sqlite3Strlen30(pLink->table);
85045       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table, n);
85046       assert( pTab!=0 );
85047       pLink->pNext = pTab->pTrigger;
85048       pTab->pTrigger = pLink;
85049     }
85050   }
85051
85052 triggerfinish_cleanup:
85053   sqlite3DeleteTrigger(db, pTrig);
85054   assert( !pParse->pNewTrigger );
85055   sqlite3DeleteTriggerStep(db, pStepList);
85056 }
85057
85058 /*
85059 ** Turn a SELECT statement (that the pSelect parameter points to) into
85060 ** a trigger step.  Return a pointer to a TriggerStep structure.
85061 **
85062 ** The parser calls this routine when it finds a SELECT statement in
85063 ** body of a TRIGGER.  
85064 */
85065 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
85066   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
85067   if( pTriggerStep==0 ) {
85068     sqlite3SelectDelete(db, pSelect);
85069     return 0;
85070   }
85071   pTriggerStep->op = TK_SELECT;
85072   pTriggerStep->pSelect = pSelect;
85073   pTriggerStep->orconf = OE_Default;
85074   return pTriggerStep;
85075 }
85076
85077 /*
85078 ** Allocate space to hold a new trigger step.  The allocated space
85079 ** holds both the TriggerStep object and the TriggerStep.target.z string.
85080 **
85081 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
85082 */
85083 static TriggerStep *triggerStepAllocate(
85084   sqlite3 *db,                /* Database connection */
85085   u8 op,                      /* Trigger opcode */
85086   Token *pName                /* The target name */
85087 ){
85088   TriggerStep *pTriggerStep;
85089
85090   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
85091   if( pTriggerStep ){
85092     char *z = (char*)&pTriggerStep[1];
85093     memcpy(z, pName->z, pName->n);
85094     pTriggerStep->target.z = z;
85095     pTriggerStep->target.n = pName->n;
85096     pTriggerStep->op = op;
85097   }
85098   return pTriggerStep;
85099 }
85100
85101 /*
85102 ** Build a trigger step out of an INSERT statement.  Return a pointer
85103 ** to the new trigger step.
85104 **
85105 ** The parser calls this routine when it sees an INSERT inside the
85106 ** body of a trigger.
85107 */
85108 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
85109   sqlite3 *db,        /* The database connection */
85110   Token *pTableName,  /* Name of the table into which we insert */
85111   IdList *pColumn,    /* List of columns in pTableName to insert into */
85112   ExprList *pEList,   /* The VALUE clause: a list of values to be inserted */
85113   Select *pSelect,    /* A SELECT statement that supplies values */
85114   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
85115 ){
85116   TriggerStep *pTriggerStep;
85117
85118   assert(pEList == 0 || pSelect == 0);
85119   assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
85120
85121   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
85122   if( pTriggerStep ){
85123     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
85124     pTriggerStep->pIdList = pColumn;
85125     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
85126     pTriggerStep->orconf = orconf;
85127   }else{
85128     sqlite3IdListDelete(db, pColumn);
85129   }
85130   sqlite3ExprListDelete(db, pEList);
85131   sqlite3SelectDelete(db, pSelect);
85132
85133   return pTriggerStep;
85134 }
85135
85136 /*
85137 ** Construct a trigger step that implements an UPDATE statement and return
85138 ** a pointer to that trigger step.  The parser calls this routine when it
85139 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
85140 */
85141 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
85142   sqlite3 *db,         /* The database connection */
85143   Token *pTableName,   /* Name of the table to be updated */
85144   ExprList *pEList,    /* The SET clause: list of column and new values */
85145   Expr *pWhere,        /* The WHERE clause */
85146   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
85147 ){
85148   TriggerStep *pTriggerStep;
85149
85150   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
85151   if( pTriggerStep ){
85152     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
85153     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
85154     pTriggerStep->orconf = orconf;
85155   }
85156   sqlite3ExprListDelete(db, pEList);
85157   sqlite3ExprDelete(db, pWhere);
85158   return pTriggerStep;
85159 }
85160
85161 /*
85162 ** Construct a trigger step that implements a DELETE statement and return
85163 ** a pointer to that trigger step.  The parser calls this routine when it
85164 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
85165 */
85166 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
85167   sqlite3 *db,            /* Database connection */
85168   Token *pTableName,      /* The table from which rows are deleted */
85169   Expr *pWhere            /* The WHERE clause */
85170 ){
85171   TriggerStep *pTriggerStep;
85172
85173   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
85174   if( pTriggerStep ){
85175     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
85176     pTriggerStep->orconf = OE_Default;
85177   }
85178   sqlite3ExprDelete(db, pWhere);
85179   return pTriggerStep;
85180 }
85181
85182 /* 
85183 ** Recursively delete a Trigger structure
85184 */
85185 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
85186   if( pTrigger==0 ) return;
85187   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
85188   sqlite3DbFree(db, pTrigger->zName);
85189   sqlite3DbFree(db, pTrigger->table);
85190   sqlite3ExprDelete(db, pTrigger->pWhen);
85191   sqlite3IdListDelete(db, pTrigger->pColumns);
85192   sqlite3DbFree(db, pTrigger);
85193 }
85194
85195 /*
85196 ** This function is called to drop a trigger from the database schema. 
85197 **
85198 ** This may be called directly from the parser and therefore identifies
85199 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
85200 ** same job as this routine except it takes a pointer to the trigger
85201 ** instead of the trigger name.
85202 **/
85203 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
85204   Trigger *pTrigger = 0;
85205   int i;
85206   const char *zDb;
85207   const char *zName;
85208   int nName;
85209   sqlite3 *db = pParse->db;
85210
85211   if( db->mallocFailed ) goto drop_trigger_cleanup;
85212   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
85213     goto drop_trigger_cleanup;
85214   }
85215
85216   assert( pName->nSrc==1 );
85217   zDb = pName->a[0].zDatabase;
85218   zName = pName->a[0].zName;
85219   nName = sqlite3Strlen30(zName);
85220   for(i=OMIT_TEMPDB; i<db->nDb; i++){
85221     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
85222     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
85223     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
85224     if( pTrigger ) break;
85225   }
85226   if( !pTrigger ){
85227     if( !noErr ){
85228       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
85229     }
85230     goto drop_trigger_cleanup;
85231   }
85232   sqlite3DropTriggerPtr(pParse, pTrigger);
85233
85234 drop_trigger_cleanup:
85235   sqlite3SrcListDelete(db, pName);
85236 }
85237
85238 /*
85239 ** Return a pointer to the Table structure for the table that a trigger
85240 ** is set on.
85241 */
85242 static Table *tableOfTrigger(Trigger *pTrigger){
85243   int n = sqlite3Strlen30(pTrigger->table);
85244   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
85245 }
85246
85247
85248 /*
85249 ** Drop a trigger given a pointer to that trigger. 
85250 */
85251 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
85252   Table   *pTable;
85253   Vdbe *v;
85254   sqlite3 *db = pParse->db;
85255   int iDb;
85256
85257   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
85258   assert( iDb>=0 && iDb<db->nDb );
85259   pTable = tableOfTrigger(pTrigger);
85260   assert( pTable );
85261   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
85262 #ifndef SQLITE_OMIT_AUTHORIZATION
85263   {
85264     int code = SQLITE_DROP_TRIGGER;
85265     const char *zDb = db->aDb[iDb].zName;
85266     const char *zTab = SCHEMA_TABLE(iDb);
85267     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
85268     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
85269       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
85270       return;
85271     }
85272   }
85273 #endif
85274
85275   /* Generate code to destroy the database record of the trigger.
85276   */
85277   assert( pTable!=0 );
85278   if( (v = sqlite3GetVdbe(pParse))!=0 ){
85279     int base;
85280     static const VdbeOpList dropTrigger[] = {
85281       { OP_Rewind,     0, ADDR(9),  0},
85282       { OP_String8,    0, 1,        0}, /* 1 */
85283       { OP_Column,     0, 1,        2},
85284       { OP_Ne,         2, ADDR(8),  1},
85285       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
85286       { OP_Column,     0, 0,        2},
85287       { OP_Ne,         2, ADDR(8),  1},
85288       { OP_Delete,     0, 0,        0},
85289       { OP_Next,       0, ADDR(1),  0}, /* 8 */
85290     };
85291
85292     sqlite3BeginWriteOperation(pParse, 0, iDb);
85293     sqlite3OpenMasterTable(pParse, iDb);
85294     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger);
85295     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, 0);
85296     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
85297     sqlite3ChangeCookie(pParse, iDb);
85298     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
85299     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
85300     if( pParse->nMem<3 ){
85301       pParse->nMem = 3;
85302     }
85303   }
85304 }
85305
85306 /*
85307 ** Remove a trigger from the hash tables of the sqlite* pointer.
85308 */
85309 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
85310   Hash *pHash = &(db->aDb[iDb].pSchema->trigHash);
85311   Trigger *pTrigger;
85312   pTrigger = sqlite3HashInsert(pHash, zName, sqlite3Strlen30(zName), 0);
85313   if( ALWAYS(pTrigger) ){
85314     if( pTrigger->pSchema==pTrigger->pTabSchema ){
85315       Table *pTab = tableOfTrigger(pTrigger);
85316       Trigger **pp;
85317       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
85318       *pp = (*pp)->pNext;
85319     }
85320     sqlite3DeleteTrigger(db, pTrigger);
85321     db->flags |= SQLITE_InternChanges;
85322   }
85323 }
85324
85325 /*
85326 ** pEList is the SET clause of an UPDATE statement.  Each entry
85327 ** in pEList is of the format <id>=<expr>.  If any of the entries
85328 ** in pEList have an <id> which matches an identifier in pIdList,
85329 ** then return TRUE.  If pIdList==NULL, then it is considered a
85330 ** wildcard that matches anything.  Likewise if pEList==NULL then
85331 ** it matches anything so always return true.  Return false only
85332 ** if there is no match.
85333 */
85334 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
85335   int e;
85336   if( pIdList==0 || NEVER(pEList==0) ) return 1;
85337   for(e=0; e<pEList->nExpr; e++){
85338     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
85339   }
85340   return 0; 
85341 }
85342
85343 /*
85344 ** Return a list of all triggers on table pTab if there exists at least
85345 ** one trigger that must be fired when an operation of type 'op' is 
85346 ** performed on the table, and, if that operation is an UPDATE, if at
85347 ** least one of the columns in pChanges is being modified.
85348 */
85349 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
85350   Parse *pParse,          /* Parse context */
85351   Table *pTab,            /* The table the contains the triggers */
85352   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
85353   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
85354   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
85355 ){
85356   int mask = 0;
85357   Trigger *pList = sqlite3TriggerList(pParse, pTab);
85358   Trigger *p;
85359   assert( pList==0 || IsVirtual(pTab)==0 );
85360   for(p=pList; p; p=p->pNext){
85361     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
85362       mask |= p->tr_tm;
85363     }
85364   }
85365   if( pMask ){
85366     *pMask = mask;
85367   }
85368   return (mask ? pList : 0);
85369 }
85370
85371 /*
85372 ** Convert the pStep->target token into a SrcList and return a pointer
85373 ** to that SrcList.
85374 **
85375 ** This routine adds a specific database name, if needed, to the target when
85376 ** forming the SrcList.  This prevents a trigger in one database from
85377 ** referring to a target in another database.  An exception is when the
85378 ** trigger is in TEMP in which case it can refer to any other database it
85379 ** wants.
85380 */
85381 static SrcList *targetSrcList(
85382   Parse *pParse,       /* The parsing context */
85383   TriggerStep *pStep   /* The trigger containing the target token */
85384 ){
85385   int iDb;             /* Index of the database to use */
85386   SrcList *pSrc;       /* SrcList to be returned */
85387
85388   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
85389   if( pSrc ){
85390     assert( pSrc->nSrc>0 );
85391     assert( pSrc->a!=0 );
85392     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
85393     if( iDb==0 || iDb>=2 ){
85394       sqlite3 *db = pParse->db;
85395       assert( iDb<pParse->db->nDb );
85396       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
85397     }
85398   }
85399   return pSrc;
85400 }
85401
85402 /*
85403 ** Generate VDBE code for the statements inside the body of a single 
85404 ** trigger.
85405 */
85406 static int codeTriggerProgram(
85407   Parse *pParse,            /* The parser context */
85408   TriggerStep *pStepList,   /* List of statements inside the trigger body */
85409   int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
85410 ){
85411   TriggerStep *pStep;
85412   Vdbe *v = pParse->pVdbe;
85413   sqlite3 *db = pParse->db;
85414
85415   assert( pParse->pTriggerTab && pParse->pToplevel );
85416   assert( pStepList );
85417   assert( v!=0 );
85418   for(pStep=pStepList; pStep; pStep=pStep->pNext){
85419     /* Figure out the ON CONFLICT policy that will be used for this step
85420     ** of the trigger program. If the statement that caused this trigger
85421     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
85422     ** the ON CONFLICT policy that was specified as part of the trigger
85423     ** step statement. Example:
85424     **
85425     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
85426     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
85427     **   END;
85428     **
85429     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
85430     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
85431     */
85432     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
85433
85434     switch( pStep->op ){
85435       case TK_UPDATE: {
85436         sqlite3Update(pParse, 
85437           targetSrcList(pParse, pStep),
85438           sqlite3ExprListDup(db, pStep->pExprList, 0), 
85439           sqlite3ExprDup(db, pStep->pWhere, 0), 
85440           pParse->eOrconf
85441         );
85442         break;
85443       }
85444       case TK_INSERT: {
85445         sqlite3Insert(pParse, 
85446           targetSrcList(pParse, pStep),
85447           sqlite3ExprListDup(db, pStep->pExprList, 0), 
85448           sqlite3SelectDup(db, pStep->pSelect, 0), 
85449           sqlite3IdListDup(db, pStep->pIdList), 
85450           pParse->eOrconf
85451         );
85452         break;
85453       }
85454       case TK_DELETE: {
85455         sqlite3DeleteFrom(pParse, 
85456           targetSrcList(pParse, pStep),
85457           sqlite3ExprDup(db, pStep->pWhere, 0)
85458         );
85459         break;
85460       }
85461       default: assert( pStep->op==TK_SELECT ); {
85462         SelectDest sDest;
85463         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
85464         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
85465         sqlite3Select(pParse, pSelect, &sDest);
85466         sqlite3SelectDelete(db, pSelect);
85467         break;
85468       }
85469     } 
85470     if( pStep->op!=TK_SELECT ){
85471       sqlite3VdbeAddOp0(v, OP_ResetCount);
85472     }
85473   }
85474
85475   return 0;
85476 }
85477
85478 #ifdef SQLITE_DEBUG
85479 /*
85480 ** This function is used to add VdbeComment() annotations to a VDBE
85481 ** program. It is not used in production code, only for debugging.
85482 */
85483 static const char *onErrorText(int onError){
85484   switch( onError ){
85485     case OE_Abort:    return "abort";
85486     case OE_Rollback: return "rollback";
85487     case OE_Fail:     return "fail";
85488     case OE_Replace:  return "replace";
85489     case OE_Ignore:   return "ignore";
85490     case OE_Default:  return "default";
85491   }
85492   return "n/a";
85493 }
85494 #endif
85495
85496 /*
85497 ** Parse context structure pFrom has just been used to create a sub-vdbe
85498 ** (trigger program). If an error has occurred, transfer error information
85499 ** from pFrom to pTo.
85500 */
85501 static void transferParseError(Parse *pTo, Parse *pFrom){
85502   assert( pFrom->zErrMsg==0 || pFrom->nErr );
85503   assert( pTo->zErrMsg==0 || pTo->nErr );
85504   if( pTo->nErr==0 ){
85505     pTo->zErrMsg = pFrom->zErrMsg;
85506     pTo->nErr = pFrom->nErr;
85507   }else{
85508     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
85509   }
85510 }
85511
85512 /*
85513 ** Create and populate a new TriggerPrg object with a sub-program 
85514 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
85515 */
85516 static TriggerPrg *codeRowTrigger(
85517   Parse *pParse,       /* Current parse context */
85518   Trigger *pTrigger,   /* Trigger to code */
85519   Table *pTab,         /* The table pTrigger is attached to */
85520   int orconf           /* ON CONFLICT policy to code trigger program with */
85521 ){
85522   Parse *pTop = sqlite3ParseToplevel(pParse);
85523   sqlite3 *db = pParse->db;   /* Database handle */
85524   TriggerPrg *pPrg;           /* Value to return */
85525   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
85526   Vdbe *v;                    /* Temporary VM */
85527   NameContext sNC;            /* Name context for sub-vdbe */
85528   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
85529   Parse *pSubParse;           /* Parse context for sub-vdbe */
85530   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
85531
85532   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
85533
85534   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
85535   ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
85536   ** list of the top-level Parse object sooner rather than later.  */
85537   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
85538   if( !pPrg ) return 0;
85539   pPrg->pNext = pTop->pTriggerPrg;
85540   pTop->pTriggerPrg = pPrg;
85541   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
85542   if( !pProgram ) return 0;
85543   pProgram->nRef = 1;
85544   pPrg->pTrigger = pTrigger;
85545   pPrg->orconf = orconf;
85546   pPrg->aColmask[0] = 0xffffffff;
85547   pPrg->aColmask[1] = 0xffffffff;
85548
85549   /* Allocate and populate a new Parse context to use for coding the 
85550   ** trigger sub-program.  */
85551   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
85552   if( !pSubParse ) return 0;
85553   memset(&sNC, 0, sizeof(sNC));
85554   sNC.pParse = pSubParse;
85555   pSubParse->db = db;
85556   pSubParse->pTriggerTab = pTab;
85557   pSubParse->pToplevel = pTop;
85558   pSubParse->zAuthContext = pTrigger->zName;
85559   pSubParse->eTriggerOp = pTrigger->op;
85560
85561   v = sqlite3GetVdbe(pSubParse);
85562   if( v ){
85563     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
85564       pTrigger->zName, onErrorText(orconf),
85565       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
85566         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
85567         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
85568         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
85569       pTab->zName
85570     ));
85571 #ifndef SQLITE_OMIT_TRACE
85572     sqlite3VdbeChangeP4(v, -1, 
85573       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
85574     );
85575 #endif
85576
85577     /* If one was specified, code the WHEN clause. If it evaluates to false
85578     ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
85579     ** OP_Halt inserted at the end of the program.  */
85580     if( pTrigger->pWhen ){
85581       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
85582       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
85583        && db->mallocFailed==0 
85584       ){
85585         iEndTrigger = sqlite3VdbeMakeLabel(v);
85586         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
85587       }
85588       sqlite3ExprDelete(db, pWhen);
85589     }
85590
85591     /* Code the trigger program into the sub-vdbe. */
85592     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
85593
85594     /* Insert an OP_Halt at the end of the sub-program. */
85595     if( iEndTrigger ){
85596       sqlite3VdbeResolveLabel(v, iEndTrigger);
85597     }
85598     sqlite3VdbeAddOp0(v, OP_Halt);
85599     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
85600
85601     transferParseError(pParse, pSubParse);
85602     if( db->mallocFailed==0 ){
85603       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
85604     }
85605     pProgram->nMem = pSubParse->nMem;
85606     pProgram->nCsr = pSubParse->nTab;
85607     pProgram->token = (void *)pTrigger;
85608     pPrg->aColmask[0] = pSubParse->oldmask;
85609     pPrg->aColmask[1] = pSubParse->newmask;
85610     sqlite3VdbeDelete(v);
85611   }
85612
85613   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
85614   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
85615   sqlite3StackFree(db, pSubParse);
85616
85617   return pPrg;
85618 }
85619     
85620 /*
85621 ** Return a pointer to a TriggerPrg object containing the sub-program for
85622 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
85623 ** TriggerPrg object exists, a new object is allocated and populated before
85624 ** being returned.
85625 */
85626 static TriggerPrg *getRowTrigger(
85627   Parse *pParse,       /* Current parse context */
85628   Trigger *pTrigger,   /* Trigger to code */
85629   Table *pTab,         /* The table trigger pTrigger is attached to */
85630   int orconf           /* ON CONFLICT algorithm. */
85631 ){
85632   Parse *pRoot = sqlite3ParseToplevel(pParse);
85633   TriggerPrg *pPrg;
85634
85635   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
85636
85637   /* It may be that this trigger has already been coded (or is in the
85638   ** process of being coded). If this is the case, then an entry with
85639   ** a matching TriggerPrg.pTrigger field will be present somewhere
85640   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
85641   for(pPrg=pRoot->pTriggerPrg; 
85642       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
85643       pPrg=pPrg->pNext
85644   );
85645
85646   /* If an existing TriggerPrg could not be located, create a new one. */
85647   if( !pPrg ){
85648     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
85649   }
85650
85651   return pPrg;
85652 }
85653
85654 /*
85655 ** Generate code for the trigger program associated with trigger p on 
85656 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
85657 ** function are the same as those described in the header function for
85658 ** sqlite3CodeRowTrigger()
85659 */
85660 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
85661   Parse *pParse,       /* Parse context */
85662   Trigger *p,          /* Trigger to code */
85663   Table *pTab,         /* The table to code triggers from */
85664   int reg,             /* Reg array containing OLD.* and NEW.* values */
85665   int orconf,          /* ON CONFLICT policy */
85666   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
85667 ){
85668   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
85669   TriggerPrg *pPrg;
85670   pPrg = getRowTrigger(pParse, p, pTab, orconf);
85671   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
85672
85673   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
85674   ** is a pointer to the sub-vdbe containing the trigger program.  */
85675   if( pPrg ){
85676     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
85677     pPrg->pProgram->nRef++;
85678     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
85679     VdbeComment(
85680         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
85681
85682     /* Set the P5 operand of the OP_Program instruction to non-zero if
85683     ** recursive invocation of this trigger program is disallowed. Recursive
85684     ** invocation is disallowed if (a) the sub-program is really a trigger,
85685     ** not a foreign key action, and (b) the flag to enable recursive triggers
85686     ** is clear.  */
85687     sqlite3VdbeChangeP5(v, (u8)(p->zName && !(pParse->db->flags&SQLITE_RecTriggers)));
85688   }
85689 }
85690
85691 /*
85692 ** This is called to code the required FOR EACH ROW triggers for an operation
85693 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
85694 ** is given by the op paramater. The tr_tm parameter determines whether the
85695 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
85696 ** parameter pChanges is passed the list of columns being modified.
85697 **
85698 ** If there are no triggers that fire at the specified time for the specified
85699 ** operation on pTab, this function is a no-op.
85700 **
85701 ** The reg argument is the address of the first in an array of registers 
85702 ** that contain the values substituted for the new.* and old.* references
85703 ** in the trigger program. If N is the number of columns in table pTab
85704 ** (a copy of pTab->nCol), then registers are populated as follows:
85705 **
85706 **   Register       Contains
85707 **   ------------------------------------------------------
85708 **   reg+0          OLD.rowid
85709 **   reg+1          OLD.* value of left-most column of pTab
85710 **   ...            ...
85711 **   reg+N          OLD.* value of right-most column of pTab
85712 **   reg+N+1        NEW.rowid
85713 **   reg+N+2        OLD.* value of left-most column of pTab
85714 **   ...            ...
85715 **   reg+N+N+1      NEW.* value of right-most column of pTab
85716 **
85717 ** For ON DELETE triggers, the registers containing the NEW.* values will
85718 ** never be accessed by the trigger program, so they are not allocated or 
85719 ** populated by the caller (there is no data to populate them with anyway). 
85720 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
85721 ** are never accessed, and so are not allocated by the caller. So, for an
85722 ** ON INSERT trigger, the value passed to this function as parameter reg
85723 ** is not a readable register, although registers (reg+N) through 
85724 ** (reg+N+N+1) are.
85725 **
85726 ** Parameter orconf is the default conflict resolution algorithm for the
85727 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
85728 ** is the instruction that control should jump to if a trigger program
85729 ** raises an IGNORE exception.
85730 */
85731 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
85732   Parse *pParse,       /* Parse context */
85733   Trigger *pTrigger,   /* List of triggers on table pTab */
85734   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
85735   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
85736   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
85737   Table *pTab,         /* The table to code triggers from */
85738   int reg,             /* The first in an array of registers (see above) */
85739   int orconf,          /* ON CONFLICT policy */
85740   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
85741 ){
85742   Trigger *p;          /* Used to iterate through pTrigger list */
85743
85744   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
85745   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
85746   assert( (op==TK_UPDATE)==(pChanges!=0) );
85747
85748   for(p=pTrigger; p; p=p->pNext){
85749
85750     /* Sanity checking:  The schema for the trigger and for the table are
85751     ** always defined.  The trigger must be in the same schema as the table
85752     ** or else it must be a TEMP trigger. */
85753     assert( p->pSchema!=0 );
85754     assert( p->pTabSchema!=0 );
85755     assert( p->pSchema==p->pTabSchema 
85756          || p->pSchema==pParse->db->aDb[1].pSchema );
85757
85758     /* Determine whether we should code this trigger */
85759     if( p->op==op 
85760      && p->tr_tm==tr_tm 
85761      && checkColumnOverlap(p->pColumns, pChanges)
85762     ){
85763       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
85764     }
85765   }
85766 }
85767
85768 /*
85769 ** Triggers may access values stored in the old.* or new.* pseudo-table. 
85770 ** This function returns a 32-bit bitmask indicating which columns of the 
85771 ** old.* or new.* tables actually are used by triggers. This information 
85772 ** may be used by the caller, for example, to avoid having to load the entire
85773 ** old.* record into memory when executing an UPDATE or DELETE command.
85774 **
85775 ** Bit 0 of the returned mask is set if the left-most column of the
85776 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
85777 ** the second leftmost column value is required, and so on. If there
85778 ** are more than 32 columns in the table, and at least one of the columns
85779 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
85780 **
85781 ** It is not possible to determine if the old.rowid or new.rowid column is 
85782 ** accessed by triggers. The caller must always assume that it is.
85783 **
85784 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
85785 ** applies to the old.* table. If 1, the new.* table.
85786 **
85787 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
85788 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
85789 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
85790 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
85791 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
85792 */
85793 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
85794   Parse *pParse,       /* Parse context */
85795   Trigger *pTrigger,   /* List of triggers on table pTab */
85796   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
85797   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
85798   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
85799   Table *pTab,         /* The table to code triggers from */
85800   int orconf           /* Default ON CONFLICT policy for trigger steps */
85801 ){
85802   const int op = pChanges ? TK_UPDATE : TK_DELETE;
85803   u32 mask = 0;
85804   Trigger *p;
85805
85806   assert( isNew==1 || isNew==0 );
85807   for(p=pTrigger; p; p=p->pNext){
85808     if( p->op==op && (tr_tm&p->tr_tm)
85809      && checkColumnOverlap(p->pColumns,pChanges)
85810     ){
85811       TriggerPrg *pPrg;
85812       pPrg = getRowTrigger(pParse, p, pTab, orconf);
85813       if( pPrg ){
85814         mask |= pPrg->aColmask[isNew];
85815       }
85816     }
85817   }
85818
85819   return mask;
85820 }
85821
85822 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
85823
85824 /************** End of trigger.c *********************************************/
85825 /************** Begin file update.c ******************************************/
85826 /*
85827 ** 2001 September 15
85828 **
85829 ** The author disclaims copyright to this source code.  In place of
85830 ** a legal notice, here is a blessing:
85831 **
85832 **    May you do good and not evil.
85833 **    May you find forgiveness for yourself and forgive others.
85834 **    May you share freely, never taking more than you give.
85835 **
85836 *************************************************************************
85837 ** This file contains C code routines that are called by the parser
85838 ** to handle UPDATE statements.
85839 */
85840
85841 #ifndef SQLITE_OMIT_VIRTUALTABLE
85842 /* Forward declaration */
85843 static void updateVirtualTable(
85844   Parse *pParse,       /* The parsing context */
85845   SrcList *pSrc,       /* The virtual table to be modified */
85846   Table *pTab,         /* The virtual table */
85847   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
85848   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
85849   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
85850   Expr *pWhere         /* WHERE clause of the UPDATE statement */
85851 );
85852 #endif /* SQLITE_OMIT_VIRTUALTABLE */
85853
85854 /*
85855 ** The most recently coded instruction was an OP_Column to retrieve the
85856 ** i-th column of table pTab. This routine sets the P4 parameter of the 
85857 ** OP_Column to the default value, if any.
85858 **
85859 ** The default value of a column is specified by a DEFAULT clause in the 
85860 ** column definition. This was either supplied by the user when the table
85861 ** was created, or added later to the table definition by an ALTER TABLE
85862 ** command. If the latter, then the row-records in the table btree on disk
85863 ** may not contain a value for the column and the default value, taken
85864 ** from the P4 parameter of the OP_Column instruction, is returned instead.
85865 ** If the former, then all row-records are guaranteed to include a value
85866 ** for the column and the P4 value is not required.
85867 **
85868 ** Column definitions created by an ALTER TABLE command may only have 
85869 ** literal default values specified: a number, null or a string. (If a more
85870 ** complicated default expression value was provided, it is evaluated 
85871 ** when the ALTER TABLE is executed and one of the literal values written
85872 ** into the sqlite_master table.)
85873 **
85874 ** Therefore, the P4 parameter is only required if the default value for
85875 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
85876 ** function is capable of transforming these types of expressions into
85877 ** sqlite3_value objects.
85878 **
85879 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
85880 ** on register iReg. This is used when an equivalent integer value is 
85881 ** stored in place of an 8-byte floating point value in order to save 
85882 ** space.
85883 */
85884 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
85885   assert( pTab!=0 );
85886   if( !pTab->pSelect ){
85887     sqlite3_value *pValue;
85888     u8 enc = ENC(sqlite3VdbeDb(v));
85889     Column *pCol = &pTab->aCol[i];
85890     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
85891     assert( i<pTab->nCol );
85892     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
85893                          pCol->affinity, &pValue);
85894     if( pValue ){
85895       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
85896     }
85897 #ifndef SQLITE_OMIT_FLOATING_POINT
85898     if( iReg>=0 && pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
85899       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
85900     }
85901 #endif
85902   }
85903 }
85904
85905 /*
85906 ** Process an UPDATE statement.
85907 **
85908 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
85909 **          \_______/ \________/     \______/       \________________/
85910 *            onError   pTabList      pChanges             pWhere
85911 */
85912 SQLITE_PRIVATE void sqlite3Update(
85913   Parse *pParse,         /* The parser context */
85914   SrcList *pTabList,     /* The table in which we should change things */
85915   ExprList *pChanges,    /* Things to be changed */
85916   Expr *pWhere,          /* The WHERE clause.  May be null */
85917   int onError            /* How to handle constraint errors */
85918 ){
85919   int i, j;              /* Loop counters */
85920   Table *pTab;           /* The table to be updated */
85921   int addr = 0;          /* VDBE instruction address of the start of the loop */
85922   WhereInfo *pWInfo;     /* Information about the WHERE clause */
85923   Vdbe *v;               /* The virtual database engine */
85924   Index *pIdx;           /* For looping over indices */
85925   int nIdx;              /* Number of indices that need updating */
85926   int iCur;              /* VDBE Cursor number of pTab */
85927   sqlite3 *db;           /* The database structure */
85928   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
85929   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
85930                          ** an expression for the i-th column of the table.
85931                          ** aXRef[i]==-1 if the i-th column is not changed. */
85932   int chngRowid;         /* True if the record number is being changed */
85933   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
85934   int openAll = 0;       /* True if all indices need to be opened */
85935   AuthContext sContext;  /* The authorization context */
85936   NameContext sNC;       /* The name-context to resolve expressions in */
85937   int iDb;               /* Database containing the table being updated */
85938   int okOnePass;         /* True for one-pass algorithm without the FIFO */
85939   int hasFK;             /* True if foreign key processing is required */
85940
85941 #ifndef SQLITE_OMIT_TRIGGER
85942   int isView;            /* True when updating a view (INSTEAD OF trigger) */
85943   Trigger *pTrigger;     /* List of triggers on pTab, if required */
85944   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
85945 #endif
85946   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
85947
85948   /* Register Allocations */
85949   int regRowCount = 0;   /* A count of rows changed */
85950   int regOldRowid;       /* The old rowid */
85951   int regNewRowid;       /* The new rowid */
85952   int regNew;
85953   int regOld = 0;
85954   int regRowSet = 0;     /* Rowset of rows to be updated */
85955   int regRec;            /* Register used for new table record to insert */
85956
85957   memset(&sContext, 0, sizeof(sContext));
85958   db = pParse->db;
85959   if( pParse->nErr || db->mallocFailed ){
85960     goto update_cleanup;
85961   }
85962   assert( pTabList->nSrc==1 );
85963
85964   /* Locate the table which we want to update. 
85965   */
85966   pTab = sqlite3SrcListLookup(pParse, pTabList);
85967   if( pTab==0 ) goto update_cleanup;
85968   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
85969
85970   /* Figure out if we have any triggers and if the table being
85971   ** updated is a view.
85972   */
85973 #ifndef SQLITE_OMIT_TRIGGER
85974   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
85975   isView = pTab->pSelect!=0;
85976   assert( pTrigger || tmask==0 );
85977 #else
85978 # define pTrigger 0
85979 # define isView 0
85980 # define tmask 0
85981 #endif
85982 #ifdef SQLITE_OMIT_VIEW
85983 # undef isView
85984 # define isView 0
85985 #endif
85986
85987   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
85988     goto update_cleanup;
85989   }
85990   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
85991     goto update_cleanup;
85992   }
85993   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * pTab->nCol );
85994   if( aXRef==0 ) goto update_cleanup;
85995   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
85996
85997   /* Allocate a cursors for the main database table and for all indices.
85998   ** The index cursors might not be used, but if they are used they
85999   ** need to occur right after the database cursor.  So go ahead and
86000   ** allocate enough space, just in case.
86001   */
86002   pTabList->a[0].iCursor = iCur = pParse->nTab++;
86003   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
86004     pParse->nTab++;
86005   }
86006
86007   /* Initialize the name-context */
86008   memset(&sNC, 0, sizeof(sNC));
86009   sNC.pParse = pParse;
86010   sNC.pSrcList = pTabList;
86011
86012   /* Resolve the column names in all the expressions of the
86013   ** of the UPDATE statement.  Also find the column index
86014   ** for each column to be updated in the pChanges array.  For each
86015   ** column to be updated, make sure we have authorization to change
86016   ** that column.
86017   */
86018   chngRowid = 0;
86019   for(i=0; i<pChanges->nExpr; i++){
86020     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
86021       goto update_cleanup;
86022     }
86023     for(j=0; j<pTab->nCol; j++){
86024       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
86025         if( j==pTab->iPKey ){
86026           chngRowid = 1;
86027           pRowidExpr = pChanges->a[i].pExpr;
86028         }
86029         aXRef[j] = i;
86030         break;
86031       }
86032     }
86033     if( j>=pTab->nCol ){
86034       if( sqlite3IsRowid(pChanges->a[i].zName) ){
86035         chngRowid = 1;
86036         pRowidExpr = pChanges->a[i].pExpr;
86037       }else{
86038         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
86039         goto update_cleanup;
86040       }
86041     }
86042 #ifndef SQLITE_OMIT_AUTHORIZATION
86043     {
86044       int rc;
86045       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
86046                            pTab->aCol[j].zName, db->aDb[iDb].zName);
86047       if( rc==SQLITE_DENY ){
86048         goto update_cleanup;
86049       }else if( rc==SQLITE_IGNORE ){
86050         aXRef[j] = -1;
86051       }
86052     }
86053 #endif
86054   }
86055
86056   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngRowid);
86057
86058   /* Allocate memory for the array aRegIdx[].  There is one entry in the
86059   ** array for each index associated with table being updated.  Fill in
86060   ** the value with a register number for indices that are to be used
86061   ** and with zero for unused indices.
86062   */
86063   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){}
86064   if( nIdx>0 ){
86065     aRegIdx = sqlite3DbMallocRaw(db, sizeof(Index*) * nIdx );
86066     if( aRegIdx==0 ) goto update_cleanup;
86067   }
86068   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
86069     int reg;
86070     if( chngRowid ){
86071       reg = ++pParse->nMem;
86072     }else{
86073       reg = 0;
86074       for(i=0; i<pIdx->nColumn; i++){
86075         if( aXRef[pIdx->aiColumn[i]]>=0 ){
86076           reg = ++pParse->nMem;
86077           break;
86078         }
86079       }
86080     }
86081     aRegIdx[j] = reg;
86082   }
86083
86084   /* Begin generating code. */
86085   v = sqlite3GetVdbe(pParse);
86086   if( v==0 ) goto update_cleanup;
86087   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
86088   sqlite3BeginWriteOperation(pParse, 1, iDb);
86089
86090 #ifndef SQLITE_OMIT_VIRTUALTABLE
86091   /* Virtual tables must be handled separately */
86092   if( IsVirtual(pTab) ){
86093     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
86094                        pWhere);
86095     pWhere = 0;
86096     pTabList = 0;
86097     goto update_cleanup;
86098   }
86099 #endif
86100
86101   /* Allocate required registers. */
86102   regOldRowid = regNewRowid = ++pParse->nMem;
86103   if( pTrigger || hasFK ){
86104     regOld = pParse->nMem + 1;
86105     pParse->nMem += pTab->nCol;
86106   }
86107   if( chngRowid || pTrigger || hasFK ){
86108     regNewRowid = ++pParse->nMem;
86109   }
86110   regNew = pParse->nMem + 1;
86111   pParse->nMem += pTab->nCol;
86112   regRec = ++pParse->nMem;
86113
86114   /* Start the view context. */
86115   if( isView ){
86116     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
86117   }
86118
86119   /* If we are trying to update a view, realize that view into
86120   ** a ephemeral table.
86121   */
86122 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
86123   if( isView ){
86124     sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
86125   }
86126 #endif
86127
86128   /* Resolve the column names in all the expressions in the
86129   ** WHERE clause.
86130   */
86131   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
86132     goto update_cleanup;
86133   }
86134
86135   /* Begin the database scan
86136   */
86137   sqlite3VdbeAddOp2(v, OP_Null, 0, regOldRowid);
86138   pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere,0, WHERE_ONEPASS_DESIRED);
86139   if( pWInfo==0 ) goto update_cleanup;
86140   okOnePass = pWInfo->okOnePass;
86141
86142   /* Remember the rowid of every item to be updated.
86143   */
86144   sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regOldRowid);
86145   if( !okOnePass ){
86146     regRowSet = ++pParse->nMem;
86147     sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
86148   }
86149
86150   /* End the database scan loop.
86151   */
86152   sqlite3WhereEnd(pWInfo);
86153
86154   /* Initialize the count of updated rows
86155   */
86156   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
86157     regRowCount = ++pParse->nMem;
86158     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
86159   }
86160
86161   if( !isView ){
86162     /* 
86163     ** Open every index that needs updating.  Note that if any
86164     ** index could potentially invoke a REPLACE conflict resolution 
86165     ** action, then we need to open all indices because we might need
86166     ** to be deleting some records.
86167     */
86168     if( !okOnePass ) sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenWrite); 
86169     if( onError==OE_Replace ){
86170       openAll = 1;
86171     }else{
86172       openAll = 0;
86173       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
86174         if( pIdx->onError==OE_Replace ){
86175           openAll = 1;
86176           break;
86177         }
86178       }
86179     }
86180     for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
86181       if( openAll || aRegIdx[i]>0 ){
86182         KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
86183         sqlite3VdbeAddOp4(v, OP_OpenWrite, iCur+i+1, pIdx->tnum, iDb,
86184                        (char*)pKey, P4_KEYINFO_HANDOFF);
86185         assert( pParse->nTab>iCur+i+1 );
86186       }
86187     }
86188   }
86189
86190   /* Top of the update loop */
86191   if( okOnePass ){
86192     int a1 = sqlite3VdbeAddOp1(v, OP_NotNull, regOldRowid);
86193     addr = sqlite3VdbeAddOp0(v, OP_Goto);
86194     sqlite3VdbeJumpHere(v, a1);
86195   }else{
86196     addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, 0, regOldRowid);
86197   }
86198
86199   /* Make cursor iCur point to the record that is being updated. If
86200   ** this record does not exist for some reason (deleted by a trigger,
86201   ** for example, then jump to the next iteration of the RowSet loop.  */
86202   sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
86203
86204   /* If the record number will change, set register regNewRowid to
86205   ** contain the new value. If the record number is not being modified,
86206   ** then regNewRowid is the same register as regOldRowid, which is
86207   ** already populated.  */
86208   assert( chngRowid || pTrigger || hasFK || regOldRowid==regNewRowid );
86209   if( chngRowid ){
86210     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
86211     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid);
86212   }
86213
86214   /* If there are triggers on this table, populate an array of registers 
86215   ** with the required old.* column data.  */
86216   if( hasFK || pTrigger ){
86217     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
86218     oldmask |= sqlite3TriggerColmask(pParse, 
86219         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
86220     );
86221     for(i=0; i<pTab->nCol; i++){
86222       if( aXRef[i]<0 || oldmask==0xffffffff || (oldmask & (1<<i)) ){
86223         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regOld+i);
86224         sqlite3ColumnDefault(v, pTab, i, regOld+i);
86225       }else{
86226         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
86227       }
86228     }
86229     if( chngRowid==0 ){
86230       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
86231     }
86232   }
86233
86234   /* Populate the array of registers beginning at regNew with the new
86235   ** row data. This array is used to check constaints, create the new
86236   ** table and index records, and as the values for any new.* references
86237   ** made by triggers.
86238   **
86239   ** If there are one or more BEFORE triggers, then do not populate the
86240   ** registers associated with columns that are (a) not modified by
86241   ** this UPDATE statement and (b) not accessed by new.* references. The
86242   ** values for registers not modified by the UPDATE must be reloaded from 
86243   ** the database after the BEFORE triggers are fired anyway (as the trigger 
86244   ** may have modified them). So not loading those that are not going to
86245   ** be used eliminates some redundant opcodes.
86246   */
86247   newmask = sqlite3TriggerColmask(
86248       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
86249   );
86250   for(i=0; i<pTab->nCol; i++){
86251     if( i==pTab->iPKey ){
86252       sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
86253     }else{
86254       j = aXRef[i];
86255       if( j>=0 ){
86256         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
86257       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask&(1<<i)) ){
86258         /* This branch loads the value of a column that will not be changed 
86259         ** into a register. This is done if there are no BEFORE triggers, or
86260         ** if there are one or more BEFORE triggers that use this value via
86261         ** a new.* reference in a trigger program.
86262         */
86263         testcase( i==31 );
86264         testcase( i==32 );
86265         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
86266         sqlite3ColumnDefault(v, pTab, i, regNew+i);
86267       }
86268     }
86269   }
86270
86271   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
86272   ** verified. One could argue that this is wrong.
86273   */
86274   if( tmask&TRIGGER_BEFORE ){
86275     sqlite3VdbeAddOp2(v, OP_Affinity, regNew, pTab->nCol);
86276     sqlite3TableAffinityStr(v, pTab);
86277     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
86278         TRIGGER_BEFORE, pTab, regOldRowid, onError, addr);
86279
86280     /* The row-trigger may have deleted the row being updated. In this
86281     ** case, jump to the next row. No updates or AFTER triggers are 
86282     ** required. This behaviour - what happens when the row being updated
86283     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
86284     ** documentation.
86285     */
86286     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addr, regOldRowid);
86287
86288     /* If it did not delete it, the row-trigger may still have modified 
86289     ** some of the columns of the row being updated. Load the values for 
86290     ** all columns not modified by the update statement into their 
86291     ** registers in case this has happened.
86292     */
86293     for(i=0; i<pTab->nCol; i++){
86294       if( aXRef[i]<0 && i!=pTab->iPKey ){
86295         sqlite3VdbeAddOp3(v, OP_Column, iCur, i, regNew+i);
86296         sqlite3ColumnDefault(v, pTab, i, regNew+i);
86297       }
86298     }
86299   }
86300
86301   if( !isView ){
86302     int j1;                       /* Address of jump instruction */
86303
86304     /* Do constraint checks. */
86305     sqlite3GenerateConstraintChecks(pParse, pTab, iCur, regNewRowid,
86306         aRegIdx, (chngRowid?regOldRowid:0), 1, onError, addr, 0);
86307
86308     /* Do FK constraint checks. */
86309     if( hasFK ){
86310       sqlite3FkCheck(pParse, pTab, regOldRowid, 0);
86311     }
86312
86313     /* Delete the index entries associated with the current record.  */
86314     j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regOldRowid);
86315     sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
86316   
86317     /* If changing the record number, delete the old record.  */
86318     if( hasFK || chngRowid ){
86319       sqlite3VdbeAddOp2(v, OP_Delete, iCur, 0);
86320     }
86321     sqlite3VdbeJumpHere(v, j1);
86322
86323     if( hasFK ){
86324       sqlite3FkCheck(pParse, pTab, 0, regNewRowid);
86325     }
86326   
86327     /* Insert the new index entries and the new record. */
86328     sqlite3CompleteInsertion(pParse, pTab, iCur, regNewRowid, aRegIdx, 1, 0, 0);
86329
86330     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
86331     ** handle rows (possibly in other tables) that refer via a foreign key
86332     ** to the row just updated. */ 
86333     if( hasFK ){
86334       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid);
86335     }
86336   }
86337
86338   /* Increment the row counter 
86339   */
86340   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
86341     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
86342   }
86343
86344   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
86345       TRIGGER_AFTER, pTab, regOldRowid, onError, addr);
86346
86347   /* Repeat the above with the next record to be updated, until
86348   ** all record selected by the WHERE clause have been updated.
86349   */
86350   sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
86351   sqlite3VdbeJumpHere(v, addr);
86352
86353   /* Close all tables */
86354   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
86355     if( openAll || aRegIdx[i]>0 ){
86356       sqlite3VdbeAddOp2(v, OP_Close, iCur+i+1, 0);
86357     }
86358   }
86359   sqlite3VdbeAddOp2(v, OP_Close, iCur, 0);
86360
86361   /* Update the sqlite_sequence table by storing the content of the
86362   ** maximum rowid counter values recorded while inserting into
86363   ** autoincrement tables.
86364   */
86365   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
86366     sqlite3AutoincrementEnd(pParse);
86367   }
86368
86369   /*
86370   ** Return the number of rows that were changed. If this routine is 
86371   ** generating code because of a call to sqlite3NestedParse(), do not
86372   ** invoke the callback function.
86373   */
86374   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
86375     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
86376     sqlite3VdbeSetNumCols(v, 1);
86377     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
86378   }
86379
86380 update_cleanup:
86381   sqlite3AuthContextPop(&sContext);
86382   sqlite3DbFree(db, aRegIdx);
86383   sqlite3DbFree(db, aXRef);
86384   sqlite3SrcListDelete(db, pTabList);
86385   sqlite3ExprListDelete(db, pChanges);
86386   sqlite3ExprDelete(db, pWhere);
86387   return;
86388 }
86389 /* Make sure "isView" and other macros defined above are undefined. Otherwise
86390 ** thely may interfere with compilation of other functions in this file
86391 ** (or in another file, if this file becomes part of the amalgamation).  */
86392 #ifdef isView
86393  #undef isView
86394 #endif
86395 #ifdef pTrigger
86396  #undef pTrigger
86397 #endif
86398
86399 #ifndef SQLITE_OMIT_VIRTUALTABLE
86400 /*
86401 ** Generate code for an UPDATE of a virtual table.
86402 **
86403 ** The strategy is that we create an ephemerial table that contains
86404 ** for each row to be changed:
86405 **
86406 **   (A)  The original rowid of that row.
86407 **   (B)  The revised rowid for the row. (note1)
86408 **   (C)  The content of every column in the row.
86409 **
86410 ** Then we loop over this ephemeral table and for each row in
86411 ** the ephermeral table call VUpdate.
86412 **
86413 ** When finished, drop the ephemeral table.
86414 **
86415 ** (note1) Actually, if we know in advance that (A) is always the same
86416 ** as (B) we only store (A), then duplicate (A) when pulling
86417 ** it out of the ephemeral table before calling VUpdate.
86418 */
86419 static void updateVirtualTable(
86420   Parse *pParse,       /* The parsing context */
86421   SrcList *pSrc,       /* The virtual table to be modified */
86422   Table *pTab,         /* The virtual table */
86423   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
86424   Expr *pRowid,        /* Expression used to recompute the rowid */
86425   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
86426   Expr *pWhere         /* WHERE clause of the UPDATE statement */
86427 ){
86428   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
86429   ExprList *pEList = 0;     /* The result set of the SELECT statement */
86430   Select *pSelect = 0;      /* The SELECT statement */
86431   Expr *pExpr;              /* Temporary expression */
86432   int ephemTab;             /* Table holding the result of the SELECT */
86433   int i;                    /* Loop counter */
86434   int addr;                 /* Address of top of loop */
86435   int iReg;                 /* First register in set passed to OP_VUpdate */
86436   sqlite3 *db = pParse->db; /* Database connection */
86437   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
86438   SelectDest dest;
86439
86440   /* Construct the SELECT statement that will find the new values for
86441   ** all updated rows. 
86442   */
86443   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
86444   if( pRowid ){
86445     pEList = sqlite3ExprListAppend(pParse, pEList,
86446                                    sqlite3ExprDup(db, pRowid, 0));
86447   }
86448   assert( pTab->iPKey<0 );
86449   for(i=0; i<pTab->nCol; i++){
86450     if( aXRef[i]>=0 ){
86451       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
86452     }else{
86453       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
86454     }
86455     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
86456   }
86457   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
86458   
86459   /* Create the ephemeral table into which the update results will
86460   ** be stored.
86461   */
86462   assert( v );
86463   ephemTab = pParse->nTab++;
86464   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
86465
86466   /* fill the ephemeral table 
86467   */
86468   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
86469   sqlite3Select(pParse, pSelect, &dest);
86470
86471   /* Generate code to scan the ephemeral table and call VUpdate. */
86472   iReg = ++pParse->nMem;
86473   pParse->nMem += pTab->nCol+1;
86474   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0);
86475   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
86476   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
86477   for(i=0; i<pTab->nCol; i++){
86478     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
86479   }
86480   sqlite3VtabMakeWritable(pParse, pTab);
86481   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
86482   sqlite3MayAbort(pParse);
86483   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1);
86484   sqlite3VdbeJumpHere(v, addr);
86485   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
86486
86487   /* Cleanup */
86488   sqlite3SelectDelete(db, pSelect);  
86489 }
86490 #endif /* SQLITE_OMIT_VIRTUALTABLE */
86491
86492 /************** End of update.c **********************************************/
86493 /************** Begin file vacuum.c ******************************************/
86494 /*
86495 ** 2003 April 6
86496 **
86497 ** The author disclaims copyright to this source code.  In place of
86498 ** a legal notice, here is a blessing:
86499 **
86500 **    May you do good and not evil.
86501 **    May you find forgiveness for yourself and forgive others.
86502 **    May you share freely, never taking more than you give.
86503 **
86504 *************************************************************************
86505 ** This file contains code used to implement the VACUUM command.
86506 **
86507 ** Most of the code in this file may be omitted by defining the
86508 ** SQLITE_OMIT_VACUUM macro.
86509 */
86510
86511 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
86512 /*
86513 ** Finalize a prepared statement.  If there was an error, store the
86514 ** text of the error message in *pzErrMsg.  Return the result code.
86515 */
86516 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
86517   int rc;
86518   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
86519   if( rc ){
86520     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
86521   }
86522   return rc;
86523 }
86524
86525 /*
86526 ** Execute zSql on database db. Return an error code.
86527 */
86528 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
86529   sqlite3_stmt *pStmt;
86530   VVA_ONLY( int rc; )
86531   if( !zSql ){
86532     return SQLITE_NOMEM;
86533   }
86534   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
86535     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
86536     return sqlite3_errcode(db);
86537   }
86538   VVA_ONLY( rc = ) sqlite3_step(pStmt);
86539   assert( rc!=SQLITE_ROW );
86540   return vacuumFinalize(db, pStmt, pzErrMsg);
86541 }
86542
86543 /*
86544 ** Execute zSql on database db. The statement returns exactly
86545 ** one column. Execute this as SQL on the same database.
86546 */
86547 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
86548   sqlite3_stmt *pStmt;
86549   int rc;
86550
86551   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
86552   if( rc!=SQLITE_OK ) return rc;
86553
86554   while( SQLITE_ROW==sqlite3_step(pStmt) ){
86555     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
86556     if( rc!=SQLITE_OK ){
86557       vacuumFinalize(db, pStmt, pzErrMsg);
86558       return rc;
86559     }
86560   }
86561
86562   return vacuumFinalize(db, pStmt, pzErrMsg);
86563 }
86564
86565 /*
86566 ** The non-standard VACUUM command is used to clean up the database,
86567 ** collapse free space, etc.  It is modelled after the VACUUM command
86568 ** in PostgreSQL.
86569 **
86570 ** In version 1.0.x of SQLite, the VACUUM command would call
86571 ** gdbm_reorganize() on all the database tables.  But beginning
86572 ** with 2.0.0, SQLite no longer uses GDBM so this command has
86573 ** become a no-op.
86574 */
86575 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
86576   Vdbe *v = sqlite3GetVdbe(pParse);
86577   if( v ){
86578     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
86579   }
86580   return;
86581 }
86582
86583 /*
86584 ** This routine implements the OP_Vacuum opcode of the VDBE.
86585 */
86586 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
86587   int rc = SQLITE_OK;     /* Return code from service routines */
86588   Btree *pMain;           /* The database being vacuumed */
86589   Btree *pTemp;           /* The temporary database we vacuum into */
86590   char *zSql = 0;         /* SQL statements */
86591   int saved_flags;        /* Saved value of the db->flags */
86592   int saved_nChange;      /* Saved value of db->nChange */
86593   int saved_nTotalChange; /* Saved value of db->nTotalChange */
86594   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
86595   Db *pDb = 0;            /* Database to detach at end of vacuum */
86596   int isMemDb;            /* True if vacuuming a :memory: database */
86597   int nRes;
86598
86599   if( !db->autoCommit ){
86600     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
86601     return SQLITE_ERROR;
86602   }
86603
86604   /* Save the current value of the database flags so that it can be 
86605   ** restored before returning. Then set the writable-schema flag, and
86606   ** disable CHECK and foreign key constraints.  */
86607   saved_flags = db->flags;
86608   saved_nChange = db->nChange;
86609   saved_nTotalChange = db->nTotalChange;
86610   saved_xTrace = db->xTrace;
86611   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks;
86612   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
86613   db->xTrace = 0;
86614
86615   pMain = db->aDb[0].pBt;
86616   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
86617
86618   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
86619   ** can be set to 'off' for this file, as it is not recovered if a crash
86620   ** occurs anyway. The integrity of the database is maintained by a
86621   ** (possibly synchronous) transaction opened on the main database before
86622   ** sqlite3BtreeCopyFile() is called.
86623   **
86624   ** An optimisation would be to use a non-journaled pager.
86625   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
86626   ** that actually made the VACUUM run slower.  Very little journalling
86627   ** actually occurs when doing a vacuum since the vacuum_db is initially
86628   ** empty.  Only the journal header is written.  Apparently it takes more
86629   ** time to parse and run the PRAGMA to turn journalling off than it does
86630   ** to write the journal header file.
86631   */
86632   if( sqlite3TempInMemory(db) ){
86633     zSql = "ATTACH ':memory:' AS vacuum_db;";
86634   }else{
86635     zSql = "ATTACH '' AS vacuum_db;";
86636   }
86637   rc = execSql(db, pzErrMsg, zSql);
86638   if( rc!=SQLITE_OK ) goto end_of_vacuum;
86639   pDb = &db->aDb[db->nDb-1];
86640   assert( strcmp(db->aDb[db->nDb-1].zName,"vacuum_db")==0 );
86641   pTemp = db->aDb[db->nDb-1].pBt;
86642
86643   /* The call to execSql() to attach the temp database has left the file
86644   ** locked (as there was more than one active statement when the transaction
86645   ** to read the schema was concluded. Unlock it here so that this doesn't
86646   ** cause problems for the call to BtreeSetPageSize() below.  */
86647   sqlite3BtreeCommit(pTemp);
86648
86649   nRes = sqlite3BtreeGetReserve(pMain);
86650
86651   /* A VACUUM cannot change the pagesize of an encrypted database. */
86652 #ifdef SQLITE_HAS_CODEC
86653   if( db->nextPagesize ){
86654     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
86655     int nKey;
86656     char *zKey;
86657     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
86658     if( nKey ) db->nextPagesize = 0;
86659   }
86660 #endif
86661
86662   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
86663    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
86664    || NEVER(db->mallocFailed)
86665   ){
86666     rc = SQLITE_NOMEM;
86667     goto end_of_vacuum;
86668   }
86669   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
86670   if( rc!=SQLITE_OK ){
86671     goto end_of_vacuum;
86672   }
86673
86674 #ifndef SQLITE_OMIT_AUTOVACUUM
86675   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
86676                                            sqlite3BtreeGetAutoVacuum(pMain));
86677 #endif
86678
86679   /* Begin a transaction */
86680   rc = execSql(db, pzErrMsg, "BEGIN EXCLUSIVE;");
86681   if( rc!=SQLITE_OK ) goto end_of_vacuum;
86682
86683   /* Query the schema of the main database. Create a mirror schema
86684   ** in the temporary database.
86685   */
86686   rc = execExecSql(db, pzErrMsg,
86687       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
86688       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
86689       "   AND rootpage>0"
86690   );
86691   if( rc!=SQLITE_OK ) goto end_of_vacuum;
86692   rc = execExecSql(db, pzErrMsg,
86693       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
86694       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
86695   if( rc!=SQLITE_OK ) goto end_of_vacuum;
86696   rc = execExecSql(db, pzErrMsg,
86697       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
86698       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
86699   if( rc!=SQLITE_OK ) goto end_of_vacuum;
86700
86701   /* Loop through the tables in the main database. For each, do
86702   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
86703   ** the contents to the temporary database.
86704   */
86705   rc = execExecSql(db, pzErrMsg,
86706       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
86707       "|| ' SELECT * FROM main.' || quote(name) || ';'"
86708       "FROM main.sqlite_master "
86709       "WHERE type = 'table' AND name!='sqlite_sequence' "
86710       "  AND rootpage>0"
86711   );
86712   if( rc!=SQLITE_OK ) goto end_of_vacuum;
86713
86714   /* Copy over the sequence table
86715   */
86716   rc = execExecSql(db, pzErrMsg,
86717       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
86718       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
86719   );
86720   if( rc!=SQLITE_OK ) goto end_of_vacuum;
86721   rc = execExecSql(db, pzErrMsg,
86722       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
86723       "|| ' SELECT * FROM main.' || quote(name) || ';' "
86724       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
86725   );
86726   if( rc!=SQLITE_OK ) goto end_of_vacuum;
86727
86728
86729   /* Copy the triggers, views, and virtual tables from the main database
86730   ** over to the temporary database.  None of these objects has any
86731   ** associated storage, so all we have to do is copy their entries
86732   ** from the SQLITE_MASTER table.
86733   */
86734   rc = execSql(db, pzErrMsg,
86735       "INSERT INTO vacuum_db.sqlite_master "
86736       "  SELECT type, name, tbl_name, rootpage, sql"
86737       "    FROM main.sqlite_master"
86738       "   WHERE type='view' OR type='trigger'"
86739       "      OR (type='table' AND rootpage=0)"
86740   );
86741   if( rc ) goto end_of_vacuum;
86742
86743   /* At this point, unless the main db was completely empty, there is now a
86744   ** transaction open on the vacuum database, but not on the main database.
86745   ** Open a btree level transaction on the main database. This allows a
86746   ** call to sqlite3BtreeCopyFile(). The main database btree level
86747   ** transaction is then committed, so the SQL level never knows it was
86748   ** opened for writing. This way, the SQL transaction used to create the
86749   ** temporary database never needs to be committed.
86750   */
86751   {
86752     u32 meta;
86753     int i;
86754
86755     /* This array determines which meta meta values are preserved in the
86756     ** vacuum.  Even entries are the meta value number and odd entries
86757     ** are an increment to apply to the meta value after the vacuum.
86758     ** The increment is used to increase the schema cookie so that other
86759     ** connections to the same database will know to reread the schema.
86760     */
86761     static const unsigned char aCopy[] = {
86762        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
86763        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
86764        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
86765        BTREE_USER_VERSION,       0,  /* Preserve the user version */
86766     };
86767
86768     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
86769     assert( 1==sqlite3BtreeIsInTrans(pMain) );
86770
86771     /* Copy Btree meta values */
86772     for(i=0; i<ArraySize(aCopy); i+=2){
86773       /* GetMeta() and UpdateMeta() cannot fail in this context because
86774       ** we already have page 1 loaded into cache and marked dirty. */
86775       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
86776       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
86777       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
86778     }
86779
86780     rc = sqlite3BtreeCopyFile(pMain, pTemp);
86781     if( rc!=SQLITE_OK ) goto end_of_vacuum;
86782     rc = sqlite3BtreeCommit(pTemp);
86783     if( rc!=SQLITE_OK ) goto end_of_vacuum;
86784 #ifndef SQLITE_OMIT_AUTOVACUUM
86785     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
86786 #endif
86787   }
86788
86789   assert( rc==SQLITE_OK );
86790   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
86791
86792 end_of_vacuum:
86793   /* Restore the original value of db->flags */
86794   db->flags = saved_flags;
86795   db->nChange = saved_nChange;
86796   db->nTotalChange = saved_nTotalChange;
86797   db->xTrace = saved_xTrace;
86798
86799   /* Currently there is an SQL level transaction open on the vacuum
86800   ** database. No locks are held on any other files (since the main file
86801   ** was committed at the btree level). So it safe to end the transaction
86802   ** by manually setting the autoCommit flag to true and detaching the
86803   ** vacuum database. The vacuum_db journal file is deleted when the pager
86804   ** is closed by the DETACH.
86805   */
86806   db->autoCommit = 1;
86807
86808   if( pDb ){
86809     sqlite3BtreeClose(pDb->pBt);
86810     pDb->pBt = 0;
86811     pDb->pSchema = 0;
86812   }
86813
86814   sqlite3ResetInternalSchema(db, 0);
86815
86816   return rc;
86817 }
86818 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
86819
86820 /************** End of vacuum.c **********************************************/
86821 /************** Begin file vtab.c ********************************************/
86822 /*
86823 ** 2006 June 10
86824 **
86825 ** The author disclaims copyright to this source code.  In place of
86826 ** a legal notice, here is a blessing:
86827 **
86828 **    May you do good and not evil.
86829 **    May you find forgiveness for yourself and forgive others.
86830 **    May you share freely, never taking more than you give.
86831 **
86832 *************************************************************************
86833 ** This file contains code used to help implement virtual tables.
86834 */
86835 #ifndef SQLITE_OMIT_VIRTUALTABLE
86836
86837 /*
86838 ** The actual function that does the work of creating a new module.
86839 ** This function implements the sqlite3_create_module() and
86840 ** sqlite3_create_module_v2() interfaces.
86841 */
86842 static int createModule(
86843   sqlite3 *db,                    /* Database in which module is registered */
86844   const char *zName,              /* Name assigned to this module */
86845   const sqlite3_module *pModule,  /* The definition of the module */
86846   void *pAux,                     /* Context pointer for xCreate/xConnect */
86847   void (*xDestroy)(void *)        /* Module destructor function */
86848 ){
86849   int rc, nName;
86850   Module *pMod;
86851
86852   sqlite3_mutex_enter(db->mutex);
86853   nName = sqlite3Strlen30(zName);
86854   pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
86855   if( pMod ){
86856     Module *pDel;
86857     char *zCopy = (char *)(&pMod[1]);
86858     memcpy(zCopy, zName, nName+1);
86859     pMod->zName = zCopy;
86860     pMod->pModule = pModule;
86861     pMod->pAux = pAux;
86862     pMod->xDestroy = xDestroy;
86863     pDel = (Module *)sqlite3HashInsert(&db->aModule, zCopy, nName, (void*)pMod);
86864     if( pDel && pDel->xDestroy ){
86865       pDel->xDestroy(pDel->pAux);
86866     }
86867     sqlite3DbFree(db, pDel);
86868     if( pDel==pMod ){
86869       db->mallocFailed = 1;
86870     }
86871     sqlite3ResetInternalSchema(db, 0);
86872   }else if( xDestroy ){
86873     xDestroy(pAux);
86874   }
86875   rc = sqlite3ApiExit(db, SQLITE_OK);
86876   sqlite3_mutex_leave(db->mutex);
86877   return rc;
86878 }
86879
86880
86881 /*
86882 ** External API function used to create a new virtual-table module.
86883 */
86884 SQLITE_API int sqlite3_create_module(
86885   sqlite3 *db,                    /* Database in which module is registered */
86886   const char *zName,              /* Name assigned to this module */
86887   const sqlite3_module *pModule,  /* The definition of the module */
86888   void *pAux                      /* Context pointer for xCreate/xConnect */
86889 ){
86890   return createModule(db, zName, pModule, pAux, 0);
86891 }
86892
86893 /*
86894 ** External API function used to create a new virtual-table module.
86895 */
86896 SQLITE_API int sqlite3_create_module_v2(
86897   sqlite3 *db,                    /* Database in which module is registered */
86898   const char *zName,              /* Name assigned to this module */
86899   const sqlite3_module *pModule,  /* The definition of the module */
86900   void *pAux,                     /* Context pointer for xCreate/xConnect */
86901   void (*xDestroy)(void *)        /* Module destructor function */
86902 ){
86903   return createModule(db, zName, pModule, pAux, xDestroy);
86904 }
86905
86906 /*
86907 ** Lock the virtual table so that it cannot be disconnected.
86908 ** Locks nest.  Every lock should have a corresponding unlock.
86909 ** If an unlock is omitted, resources leaks will occur.  
86910 **
86911 ** If a disconnect is attempted while a virtual table is locked,
86912 ** the disconnect is deferred until all locks have been removed.
86913 */
86914 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
86915   pVTab->nRef++;
86916 }
86917
86918
86919 /*
86920 ** pTab is a pointer to a Table structure representing a virtual-table.
86921 ** Return a pointer to the VTable object used by connection db to access 
86922 ** this virtual-table, if one has been created, or NULL otherwise.
86923 */
86924 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
86925   VTable *pVtab;
86926   assert( IsVirtual(pTab) );
86927   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
86928   return pVtab;
86929 }
86930
86931 /*
86932 ** Decrement the ref-count on a virtual table object. When the ref-count
86933 ** reaches zero, call the xDisconnect() method to delete the object.
86934 */
86935 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
86936   sqlite3 *db = pVTab->db;
86937
86938   assert( db );
86939   assert( pVTab->nRef>0 );
86940   assert( sqlite3SafetyCheckOk(db) );
86941
86942   pVTab->nRef--;
86943   if( pVTab->nRef==0 ){
86944     sqlite3_vtab *p = pVTab->pVtab;
86945     if( p ){
86946       p->pModule->xDisconnect(p);
86947     }
86948     sqlite3DbFree(db, pVTab);
86949   }
86950 }
86951
86952 /*
86953 ** Table p is a virtual table. This function moves all elements in the
86954 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
86955 ** database connections to be disconnected at the next opportunity. 
86956 ** Except, if argument db is not NULL, then the entry associated with
86957 ** connection db is left in the p->pVTable list.
86958 */
86959 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
86960   VTable *pRet = 0;
86961   VTable *pVTable = p->pVTable;
86962   p->pVTable = 0;
86963
86964   /* Assert that the mutex (if any) associated with the BtShared database 
86965   ** that contains table p is held by the caller. See header comments 
86966   ** above function sqlite3VtabUnlockList() for an explanation of why
86967   ** this makes it safe to access the sqlite3.pDisconnect list of any
86968   ** database connection that may have an entry in the p->pVTable list.  */
86969   assert( db==0 ||
86970     sqlite3BtreeHoldsMutex(db->aDb[sqlite3SchemaToIndex(db, p->pSchema)].pBt) 
86971   );
86972
86973   while( pVTable ){
86974     sqlite3 *db2 = pVTable->db;
86975     VTable *pNext = pVTable->pNext;
86976     assert( db2 );
86977     if( db2==db ){
86978       pRet = pVTable;
86979       p->pVTable = pRet;
86980       pRet->pNext = 0;
86981     }else{
86982       pVTable->pNext = db2->pDisconnect;
86983       db2->pDisconnect = pVTable;
86984     }
86985     pVTable = pNext;
86986   }
86987
86988   assert( !db || pRet );
86989   return pRet;
86990 }
86991
86992
86993 /*
86994 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
86995 **
86996 ** This function may only be called when the mutexes associated with all
86997 ** shared b-tree databases opened using connection db are held by the 
86998 ** caller. This is done to protect the sqlite3.pDisconnect list. The
86999 ** sqlite3.pDisconnect list is accessed only as follows:
87000 **
87001 **   1) By this function. In this case, all BtShared mutexes and the mutex
87002 **      associated with the database handle itself must be held.
87003 **
87004 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
87005 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
87006 **      associated with the database the virtual table is stored in is held
87007 **      or, if the virtual table is stored in a non-sharable database, then
87008 **      the database handle mutex is held.
87009 **
87010 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously 
87011 ** by multiple threads. It is thread-safe.
87012 */
87013 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
87014   VTable *p = db->pDisconnect;
87015   db->pDisconnect = 0;
87016
87017   assert( sqlite3BtreeHoldsAllMutexes(db) );
87018   assert( sqlite3_mutex_held(db->mutex) );
87019
87020   if( p ){
87021     sqlite3ExpirePreparedStatements(db);
87022     do {
87023       VTable *pNext = p->pNext;
87024       sqlite3VtabUnlock(p);
87025       p = pNext;
87026     }while( p );
87027   }
87028 }
87029
87030 /*
87031 ** Clear any and all virtual-table information from the Table record.
87032 ** This routine is called, for example, just before deleting the Table
87033 ** record.
87034 **
87035 ** Since it is a virtual-table, the Table structure contains a pointer
87036 ** to the head of a linked list of VTable structures. Each VTable 
87037 ** structure is associated with a single sqlite3* user of the schema.
87038 ** The reference count of the VTable structure associated with database 
87039 ** connection db is decremented immediately (which may lead to the 
87040 ** structure being xDisconnected and free). Any other VTable structures
87041 ** in the list are moved to the sqlite3.pDisconnect list of the associated 
87042 ** database connection.
87043 */
87044 SQLITE_PRIVATE void sqlite3VtabClear(Table *p){
87045   vtabDisconnectAll(0, p);
87046   if( p->azModuleArg ){
87047     int i;
87048     for(i=0; i<p->nModuleArg; i++){
87049       sqlite3DbFree(p->dbMem, p->azModuleArg[i]);
87050     }
87051     sqlite3DbFree(p->dbMem, p->azModuleArg);
87052   }
87053 }
87054
87055 /*
87056 ** Add a new module argument to pTable->azModuleArg[].
87057 ** The string is not copied - the pointer is stored.  The
87058 ** string will be freed automatically when the table is
87059 ** deleted.
87060 */
87061 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
87062   int i = pTable->nModuleArg++;
87063   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
87064   char **azModuleArg;
87065   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
87066   if( azModuleArg==0 ){
87067     int j;
87068     for(j=0; j<i; j++){
87069       sqlite3DbFree(db, pTable->azModuleArg[j]);
87070     }
87071     sqlite3DbFree(db, zArg);
87072     sqlite3DbFree(db, pTable->azModuleArg);
87073     pTable->nModuleArg = 0;
87074   }else{
87075     azModuleArg[i] = zArg;
87076     azModuleArg[i+1] = 0;
87077   }
87078   pTable->azModuleArg = azModuleArg;
87079 }
87080
87081 /*
87082 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
87083 ** statement.  The module name has been parsed, but the optional list
87084 ** of parameters that follow the module name are still pending.
87085 */
87086 SQLITE_PRIVATE void sqlite3VtabBeginParse(
87087   Parse *pParse,        /* Parsing context */
87088   Token *pName1,        /* Name of new table, or database name */
87089   Token *pName2,        /* Name of new table or NULL */
87090   Token *pModuleName    /* Name of the module for the virtual table */
87091 ){
87092   int iDb;              /* The database the table is being created in */
87093   Table *pTable;        /* The new virtual table */
87094   sqlite3 *db;          /* Database connection */
87095
87096   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, 0);
87097   pTable = pParse->pNewTable;
87098   if( pTable==0 ) return;
87099   assert( 0==pTable->pIndex );
87100
87101   db = pParse->db;
87102   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
87103   assert( iDb>=0 );
87104
87105   pTable->tabFlags |= TF_Virtual;
87106   pTable->nModuleArg = 0;
87107   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
87108   addModuleArgument(db, pTable, sqlite3DbStrDup(db, db->aDb[iDb].zName));
87109   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
87110   pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
87111
87112 #ifndef SQLITE_OMIT_AUTHORIZATION
87113   /* Creating a virtual table invokes the authorization callback twice.
87114   ** The first invocation, to obtain permission to INSERT a row into the
87115   ** sqlite_master table, has already been made by sqlite3StartTable().
87116   ** The second call, to obtain permission to create the table, is made now.
87117   */
87118   if( pTable->azModuleArg ){
87119     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
87120             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
87121   }
87122 #endif
87123 }
87124
87125 /*
87126 ** This routine takes the module argument that has been accumulating
87127 ** in pParse->zArg[] and appends it to the list of arguments on the
87128 ** virtual table currently under construction in pParse->pTable.
87129 */
87130 static void addArgumentToVtab(Parse *pParse){
87131   if( pParse->sArg.z && ALWAYS(pParse->pNewTable) ){
87132     const char *z = (const char*)pParse->sArg.z;
87133     int n = pParse->sArg.n;
87134     sqlite3 *db = pParse->db;
87135     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
87136   }
87137 }
87138
87139 /*
87140 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
87141 ** has been completely parsed.
87142 */
87143 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
87144   Table *pTab = pParse->pNewTable;  /* The table being constructed */
87145   sqlite3 *db = pParse->db;         /* The database connection */
87146
87147   if( pTab==0 ) return;
87148   addArgumentToVtab(pParse);
87149   pParse->sArg.z = 0;
87150   if( pTab->nModuleArg<1 ) return;
87151   
87152   /* If the CREATE VIRTUAL TABLE statement is being entered for the
87153   ** first time (in other words if the virtual table is actually being
87154   ** created now instead of just being read out of sqlite_master) then
87155   ** do additional initialization work and store the statement text
87156   ** in the sqlite_master table.
87157   */
87158   if( !db->init.busy ){
87159     char *zStmt;
87160     char *zWhere;
87161     int iDb;
87162     Vdbe *v;
87163
87164     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
87165     if( pEnd ){
87166       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
87167     }
87168     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
87169
87170     /* A slot for the record has already been allocated in the 
87171     ** SQLITE_MASTER table.  We just need to update that slot with all
87172     ** the information we've collected.  
87173     **
87174     ** The VM register number pParse->regRowid holds the rowid of an
87175     ** entry in the sqlite_master table tht was created for this vtab
87176     ** by sqlite3StartTable().
87177     */
87178     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
87179     sqlite3NestedParse(pParse,
87180       "UPDATE %Q.%s "
87181          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
87182        "WHERE rowid=#%d",
87183       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
87184       pTab->zName,
87185       pTab->zName,
87186       zStmt,
87187       pParse->regRowid
87188     );
87189     sqlite3DbFree(db, zStmt);
87190     v = sqlite3GetVdbe(pParse);
87191     sqlite3ChangeCookie(pParse, iDb);
87192
87193     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
87194     zWhere = sqlite3MPrintf(db, "name='%q'", pTab->zName);
87195     sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 1, 0, zWhere, P4_DYNAMIC);
87196     sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0, 
87197                          pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
87198   }
87199
87200   /* If we are rereading the sqlite_master table create the in-memory
87201   ** record of the table. The xConnect() method is not called until
87202   ** the first time the virtual table is used in an SQL statement. This
87203   ** allows a schema that contains virtual tables to be loaded before
87204   ** the required virtual table implementations are registered.  */
87205   else {
87206     Table *pOld;
87207     Schema *pSchema = pTab->pSchema;
87208     const char *zName = pTab->zName;
87209     int nName = sqlite3Strlen30(zName);
87210     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, nName, pTab);
87211     if( pOld ){
87212       db->mallocFailed = 1;
87213       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
87214       return;
87215     }
87216     pSchema->db = pParse->db;
87217     pParse->pNewTable = 0;
87218   }
87219 }
87220
87221 /*
87222 ** The parser calls this routine when it sees the first token
87223 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
87224 */
87225 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
87226   addArgumentToVtab(pParse);
87227   pParse->sArg.z = 0;
87228   pParse->sArg.n = 0;
87229 }
87230
87231 /*
87232 ** The parser calls this routine for each token after the first token
87233 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
87234 */
87235 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
87236   Token *pArg = &pParse->sArg;
87237   if( pArg->z==0 ){
87238     pArg->z = p->z;
87239     pArg->n = p->n;
87240   }else{
87241     assert(pArg->z < p->z);
87242     pArg->n = (int)(&p->z[p->n] - pArg->z);
87243   }
87244 }
87245
87246 /*
87247 ** Invoke a virtual table constructor (either xCreate or xConnect). The
87248 ** pointer to the function to invoke is passed as the fourth parameter
87249 ** to this procedure.
87250 */
87251 static int vtabCallConstructor(
87252   sqlite3 *db, 
87253   Table *pTab,
87254   Module *pMod,
87255   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
87256   char **pzErr
87257 ){
87258   VTable *pVTable;
87259   int rc;
87260   const char *const*azArg = (const char *const*)pTab->azModuleArg;
87261   int nArg = pTab->nModuleArg;
87262   char *zErr = 0;
87263   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
87264
87265   if( !zModuleName ){
87266     return SQLITE_NOMEM;
87267   }
87268
87269   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
87270   if( !pVTable ){
87271     sqlite3DbFree(db, zModuleName);
87272     return SQLITE_NOMEM;
87273   }
87274   pVTable->db = db;
87275   pVTable->pMod = pMod;
87276
87277   assert( !db->pVTab );
87278   assert( xConstruct );
87279   db->pVTab = pTab;
87280
87281   /* Invoke the virtual table constructor */
87282   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
87283   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
87284
87285   if( SQLITE_OK!=rc ){
87286     if( zErr==0 ){
87287       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
87288     }else {
87289       *pzErr = sqlite3MPrintf(db, "%s", zErr);
87290       sqlite3DbFree(db, zErr);
87291     }
87292     sqlite3DbFree(db, pVTable);
87293   }else if( ALWAYS(pVTable->pVtab) ){
87294     /* Justification of ALWAYS():  A correct vtab constructor must allocate
87295     ** the sqlite3_vtab object if successful.  */
87296     pVTable->pVtab->pModule = pMod->pModule;
87297     pVTable->nRef = 1;
87298     if( db->pVTab ){
87299       const char *zFormat = "vtable constructor did not declare schema: %s";
87300       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
87301       sqlite3VtabUnlock(pVTable);
87302       rc = SQLITE_ERROR;
87303     }else{
87304       int iCol;
87305       /* If everything went according to plan, link the new VTable structure
87306       ** into the linked list headed by pTab->pVTable. Then loop through the 
87307       ** columns of the table to see if any of them contain the token "hidden".
87308       ** If so, set the Column.isHidden flag and remove the token from
87309       ** the type string.  */
87310       pVTable->pNext = pTab->pVTable;
87311       pTab->pVTable = pVTable;
87312
87313       for(iCol=0; iCol<pTab->nCol; iCol++){
87314         char *zType = pTab->aCol[iCol].zType;
87315         int nType;
87316         int i = 0;
87317         if( !zType ) continue;
87318         nType = sqlite3Strlen30(zType);
87319         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
87320           for(i=0; i<nType; i++){
87321             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
87322              && (zType[i+7]=='\0' || zType[i+7]==' ')
87323             ){
87324               i++;
87325               break;
87326             }
87327           }
87328         }
87329         if( i<nType ){
87330           int j;
87331           int nDel = 6 + (zType[i+6] ? 1 : 0);
87332           for(j=i; (j+nDel)<=nType; j++){
87333             zType[j] = zType[j+nDel];
87334           }
87335           if( zType[i]=='\0' && i>0 ){
87336             assert(zType[i-1]==' ');
87337             zType[i-1] = '\0';
87338           }
87339           pTab->aCol[iCol].isHidden = 1;
87340         }
87341       }
87342     }
87343   }
87344
87345   sqlite3DbFree(db, zModuleName);
87346   db->pVTab = 0;
87347   return rc;
87348 }
87349
87350 /*
87351 ** This function is invoked by the parser to call the xConnect() method
87352 ** of the virtual table pTab. If an error occurs, an error code is returned 
87353 ** and an error left in pParse.
87354 **
87355 ** This call is a no-op if table pTab is not a virtual table.
87356 */
87357 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
87358   sqlite3 *db = pParse->db;
87359   const char *zMod;
87360   Module *pMod;
87361   int rc;
87362
87363   assert( pTab );
87364   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
87365     return SQLITE_OK;
87366   }
87367
87368   /* Locate the required virtual table module */
87369   zMod = pTab->azModuleArg[0];
87370   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
87371
87372   if( !pMod ){
87373     const char *zModule = pTab->azModuleArg[0];
87374     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
87375     rc = SQLITE_ERROR;
87376   }else{
87377     char *zErr = 0;
87378     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
87379     if( rc!=SQLITE_OK ){
87380       sqlite3ErrorMsg(pParse, "%s", zErr);
87381     }
87382     sqlite3DbFree(db, zErr);
87383   }
87384
87385   return rc;
87386 }
87387
87388 /*
87389 ** Add the virtual table pVTab to the array sqlite3.aVTrans[].
87390 */
87391 static int addToVTrans(sqlite3 *db, VTable *pVTab){
87392   const int ARRAY_INCR = 5;
87393
87394   /* Grow the sqlite3.aVTrans array if required */
87395   if( (db->nVTrans%ARRAY_INCR)==0 ){
87396     VTable **aVTrans;
87397     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
87398     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
87399     if( !aVTrans ){
87400       return SQLITE_NOMEM;
87401     }
87402     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
87403     db->aVTrans = aVTrans;
87404   }
87405
87406   /* Add pVtab to the end of sqlite3.aVTrans */
87407   db->aVTrans[db->nVTrans++] = pVTab;
87408   sqlite3VtabLock(pVTab);
87409   return SQLITE_OK;
87410 }
87411
87412 /*
87413 ** This function is invoked by the vdbe to call the xCreate method
87414 ** of the virtual table named zTab in database iDb. 
87415 **
87416 ** If an error occurs, *pzErr is set to point an an English language
87417 ** description of the error and an SQLITE_XXX error code is returned.
87418 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
87419 */
87420 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
87421   int rc = SQLITE_OK;
87422   Table *pTab;
87423   Module *pMod;
87424   const char *zMod;
87425
87426   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
87427   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
87428
87429   /* Locate the required virtual table module */
87430   zMod = pTab->azModuleArg[0];
87431   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod, sqlite3Strlen30(zMod));
87432
87433   /* If the module has been registered and includes a Create method, 
87434   ** invoke it now. If the module has not been registered, return an 
87435   ** error. Otherwise, do nothing.
87436   */
87437   if( !pMod ){
87438     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
87439     rc = SQLITE_ERROR;
87440   }else{
87441     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
87442   }
87443
87444   /* Justification of ALWAYS():  The xConstructor method is required to
87445   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
87446   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
87447       rc = addToVTrans(db, sqlite3GetVTable(db, pTab));
87448   }
87449
87450   return rc;
87451 }
87452
87453 /*
87454 ** This function is used to set the schema of a virtual table.  It is only
87455 ** valid to call this function from within the xCreate() or xConnect() of a
87456 ** virtual table module.
87457 */
87458 SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
87459   Parse *pParse;
87460
87461   int rc = SQLITE_OK;
87462   Table *pTab;
87463   char *zErr = 0;
87464
87465   sqlite3_mutex_enter(db->mutex);
87466   pTab = db->pVTab;
87467   if( !pTab ){
87468     sqlite3Error(db, SQLITE_MISUSE, 0);
87469     sqlite3_mutex_leave(db->mutex);
87470     return SQLITE_MISUSE_BKPT;
87471   }
87472   assert( (pTab->tabFlags & TF_Virtual)!=0 );
87473
87474   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
87475   if( pParse==0 ){
87476     rc = SQLITE_NOMEM;
87477   }else{
87478     pParse->declareVtab = 1;
87479     pParse->db = db;
87480   
87481     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) 
87482      && pParse->pNewTable
87483      && !db->mallocFailed
87484      && !pParse->pNewTable->pSelect
87485      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
87486     ){
87487       if( !pTab->aCol ){
87488         pTab->aCol = pParse->pNewTable->aCol;
87489         pTab->nCol = pParse->pNewTable->nCol;
87490         pParse->pNewTable->nCol = 0;
87491         pParse->pNewTable->aCol = 0;
87492       }
87493       db->pVTab = 0;
87494     }else{
87495       sqlite3Error(db, SQLITE_ERROR, zErr);
87496       sqlite3DbFree(db, zErr);
87497       rc = SQLITE_ERROR;
87498     }
87499     pParse->declareVtab = 0;
87500   
87501     if( pParse->pVdbe ){
87502       sqlite3VdbeFinalize(pParse->pVdbe);
87503     }
87504     sqlite3DeleteTable(pParse->pNewTable);
87505     sqlite3StackFree(db, pParse);
87506   }
87507
87508   assert( (rc&0xff)==rc );
87509   rc = sqlite3ApiExit(db, rc);
87510   sqlite3_mutex_leave(db->mutex);
87511   return rc;
87512 }
87513
87514 /*
87515 ** This function is invoked by the vdbe to call the xDestroy method
87516 ** of the virtual table named zTab in database iDb. This occurs
87517 ** when a DROP TABLE is mentioned.
87518 **
87519 ** This call is a no-op if zTab is not a virtual table.
87520 */
87521 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
87522   int rc = SQLITE_OK;
87523   Table *pTab;
87524
87525   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
87526   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
87527     VTable *p = vtabDisconnectAll(db, pTab);
87528
87529     assert( rc==SQLITE_OK );
87530     rc = p->pMod->pModule->xDestroy(p->pVtab);
87531
87532     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
87533     if( rc==SQLITE_OK ){
87534       assert( pTab->pVTable==p && p->pNext==0 );
87535       p->pVtab = 0;
87536       pTab->pVTable = 0;
87537       sqlite3VtabUnlock(p);
87538     }
87539   }
87540
87541   return rc;
87542 }
87543
87544 /*
87545 ** This function invokes either the xRollback or xCommit method
87546 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
87547 ** called is identified by the second argument, "offset", which is
87548 ** the offset of the method to call in the sqlite3_module structure.
87549 **
87550 ** The array is cleared after invoking the callbacks. 
87551 */
87552 static void callFinaliser(sqlite3 *db, int offset){
87553   int i;
87554   if( db->aVTrans ){
87555     for(i=0; i<db->nVTrans; i++){
87556       VTable *pVTab = db->aVTrans[i];
87557       sqlite3_vtab *p = pVTab->pVtab;
87558       if( p ){
87559         int (*x)(sqlite3_vtab *);
87560         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
87561         if( x ) x(p);
87562       }
87563       sqlite3VtabUnlock(pVTab);
87564     }
87565     sqlite3DbFree(db, db->aVTrans);
87566     db->nVTrans = 0;
87567     db->aVTrans = 0;
87568   }
87569 }
87570
87571 /*
87572 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
87573 ** array. Return the error code for the first error that occurs, or
87574 ** SQLITE_OK if all xSync operations are successful.
87575 **
87576 ** Set *pzErrmsg to point to a buffer that should be released using 
87577 ** sqlite3DbFree() containing an error message, if one is available.
87578 */
87579 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, char **pzErrmsg){
87580   int i;
87581   int rc = SQLITE_OK;
87582   VTable **aVTrans = db->aVTrans;
87583
87584   db->aVTrans = 0;
87585   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
87586     int (*x)(sqlite3_vtab *);
87587     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
87588     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
87589       rc = x(pVtab);
87590       sqlite3DbFree(db, *pzErrmsg);
87591       *pzErrmsg = pVtab->zErrMsg;
87592       pVtab->zErrMsg = 0;
87593     }
87594   }
87595   db->aVTrans = aVTrans;
87596   return rc;
87597 }
87598
87599 /*
87600 ** Invoke the xRollback method of all virtual tables in the 
87601 ** sqlite3.aVTrans array. Then clear the array itself.
87602 */
87603 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
87604   callFinaliser(db, offsetof(sqlite3_module,xRollback));
87605   return SQLITE_OK;
87606 }
87607
87608 /*
87609 ** Invoke the xCommit method of all virtual tables in the 
87610 ** sqlite3.aVTrans array. Then clear the array itself.
87611 */
87612 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
87613   callFinaliser(db, offsetof(sqlite3_module,xCommit));
87614   return SQLITE_OK;
87615 }
87616
87617 /*
87618 ** If the virtual table pVtab supports the transaction interface
87619 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
87620 ** not currently open, invoke the xBegin method now.
87621 **
87622 ** If the xBegin call is successful, place the sqlite3_vtab pointer
87623 ** in the sqlite3.aVTrans array.
87624 */
87625 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
87626   int rc = SQLITE_OK;
87627   const sqlite3_module *pModule;
87628
87629   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
87630   ** than zero, then this function is being called from within a
87631   ** virtual module xSync() callback. It is illegal to write to 
87632   ** virtual module tables in this case, so return SQLITE_LOCKED.
87633   */
87634   if( sqlite3VtabInSync(db) ){
87635     return SQLITE_LOCKED;
87636   }
87637   if( !pVTab ){
87638     return SQLITE_OK;
87639   } 
87640   pModule = pVTab->pVtab->pModule;
87641
87642   if( pModule->xBegin ){
87643     int i;
87644
87645
87646     /* If pVtab is already in the aVTrans array, return early */
87647     for(i=0; i<db->nVTrans; i++){
87648       if( db->aVTrans[i]==pVTab ){
87649         return SQLITE_OK;
87650       }
87651     }
87652
87653     /* Invoke the xBegin method */
87654     rc = pModule->xBegin(pVTab->pVtab);
87655     if( rc==SQLITE_OK ){
87656       rc = addToVTrans(db, pVTab);
87657     }
87658   }
87659   return rc;
87660 }
87661
87662 /*
87663 ** The first parameter (pDef) is a function implementation.  The
87664 ** second parameter (pExpr) is the first argument to this function.
87665 ** If pExpr is a column in a virtual table, then let the virtual
87666 ** table implementation have an opportunity to overload the function.
87667 **
87668 ** This routine is used to allow virtual table implementations to
87669 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
87670 **
87671 ** Return either the pDef argument (indicating no change) or a 
87672 ** new FuncDef structure that is marked as ephemeral using the
87673 ** SQLITE_FUNC_EPHEM flag.
87674 */
87675 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
87676   sqlite3 *db,    /* Database connection for reporting malloc problems */
87677   FuncDef *pDef,  /* Function to possibly overload */
87678   int nArg,       /* Number of arguments to the function */
87679   Expr *pExpr     /* First argument to the function */
87680 ){
87681   Table *pTab;
87682   sqlite3_vtab *pVtab;
87683   sqlite3_module *pMod;
87684   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
87685   void *pArg = 0;
87686   FuncDef *pNew;
87687   int rc = 0;
87688   char *zLowerName;
87689   unsigned char *z;
87690
87691
87692   /* Check to see the left operand is a column in a virtual table */
87693   if( NEVER(pExpr==0) ) return pDef;
87694   if( pExpr->op!=TK_COLUMN ) return pDef;
87695   pTab = pExpr->pTab;
87696   if( NEVER(pTab==0) ) return pDef;
87697   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
87698   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
87699   assert( pVtab!=0 );
87700   assert( pVtab->pModule!=0 );
87701   pMod = (sqlite3_module *)pVtab->pModule;
87702   if( pMod->xFindFunction==0 ) return pDef;
87703  
87704   /* Call the xFindFunction method on the virtual table implementation
87705   ** to see if the implementation wants to overload this function 
87706   */
87707   zLowerName = sqlite3DbStrDup(db, pDef->zName);
87708   if( zLowerName ){
87709     for(z=(unsigned char*)zLowerName; *z; z++){
87710       *z = sqlite3UpperToLower[*z];
87711     }
87712     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
87713     sqlite3DbFree(db, zLowerName);
87714   }
87715   if( rc==0 ){
87716     return pDef;
87717   }
87718
87719   /* Create a new ephemeral function definition for the overloaded
87720   ** function */
87721   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
87722                              + sqlite3Strlen30(pDef->zName) + 1);
87723   if( pNew==0 ){
87724     return pDef;
87725   }
87726   *pNew = *pDef;
87727   pNew->zName = (char *)&pNew[1];
87728   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
87729   pNew->xFunc = xFunc;
87730   pNew->pUserData = pArg;
87731   pNew->flags |= SQLITE_FUNC_EPHEM;
87732   return pNew;
87733 }
87734
87735 /*
87736 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
87737 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
87738 ** array if it is missing.  If pTab is already in the array, this routine
87739 ** is a no-op.
87740 */
87741 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
87742   Parse *pToplevel = sqlite3ParseToplevel(pParse);
87743   int i, n;
87744   Table **apVtabLock;
87745
87746   assert( IsVirtual(pTab) );
87747   for(i=0; i<pToplevel->nVtabLock; i++){
87748     if( pTab==pToplevel->apVtabLock[i] ) return;
87749   }
87750   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
87751   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
87752   if( apVtabLock ){
87753     pToplevel->apVtabLock = apVtabLock;
87754     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
87755   }else{
87756     pToplevel->db->mallocFailed = 1;
87757   }
87758 }
87759
87760 #endif /* SQLITE_OMIT_VIRTUALTABLE */
87761
87762 /************** End of vtab.c ************************************************/
87763 /************** Begin file where.c *******************************************/
87764 /*
87765 ** 2001 September 15
87766 **
87767 ** The author disclaims copyright to this source code.  In place of
87768 ** a legal notice, here is a blessing:
87769 **
87770 **    May you do good and not evil.
87771 **    May you find forgiveness for yourself and forgive others.
87772 **    May you share freely, never taking more than you give.
87773 **
87774 *************************************************************************
87775 ** This module contains C code that generates VDBE code used to process
87776 ** the WHERE clause of SQL statements.  This module is responsible for
87777 ** generating the code that loops through a table looking for applicable
87778 ** rows.  Indices are selected and used to speed the search when doing
87779 ** so is applicable.  Because this module is responsible for selecting
87780 ** indices, you might also think of this module as the "query optimizer".
87781 */
87782
87783 /*
87784 ** Trace output macros
87785 */
87786 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
87787 SQLITE_PRIVATE int sqlite3WhereTrace = 0;
87788 #endif
87789 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
87790 # define WHERETRACE(X)  if(sqlite3WhereTrace) sqlite3DebugPrintf X
87791 #else
87792 # define WHERETRACE(X)
87793 #endif
87794
87795 /* Forward reference
87796 */
87797 typedef struct WhereClause WhereClause;
87798 typedef struct WhereMaskSet WhereMaskSet;
87799 typedef struct WhereOrInfo WhereOrInfo;
87800 typedef struct WhereAndInfo WhereAndInfo;
87801 typedef struct WhereCost WhereCost;
87802
87803 /*
87804 ** The query generator uses an array of instances of this structure to
87805 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
87806 ** clause subexpression is separated from the others by AND operators,
87807 ** usually, or sometimes subexpressions separated by OR.
87808 **
87809 ** All WhereTerms are collected into a single WhereClause structure.  
87810 ** The following identity holds:
87811 **
87812 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
87813 **
87814 ** When a term is of the form:
87815 **
87816 **              X <op> <expr>
87817 **
87818 ** where X is a column name and <op> is one of certain operators,
87819 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
87820 ** cursor number and column number for X.  WhereTerm.eOperator records
87821 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
87822 ** use of a bitmask encoding for the operator allows us to search
87823 ** quickly for terms that match any of several different operators.
87824 **
87825 ** A WhereTerm might also be two or more subterms connected by OR:
87826 **
87827 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
87828 **
87829 ** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
87830 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
87831 ** is collected about the
87832 **
87833 ** If a term in the WHERE clause does not match either of the two previous
87834 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
87835 ** to the original subexpression content and wtFlags is set up appropriately
87836 ** but no other fields in the WhereTerm object are meaningful.
87837 **
87838 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
87839 ** but they do so indirectly.  A single WhereMaskSet structure translates
87840 ** cursor number into bits and the translated bit is stored in the prereq
87841 ** fields.  The translation is used in order to maximize the number of
87842 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
87843 ** spread out over the non-negative integers.  For example, the cursor
87844 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
87845 ** translates these sparse cursor numbers into consecutive integers
87846 ** beginning with 0 in order to make the best possible use of the available
87847 ** bits in the Bitmask.  So, in the example above, the cursor numbers
87848 ** would be mapped into integers 0 through 7.
87849 **
87850 ** The number of terms in a join is limited by the number of bits
87851 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
87852 ** is only able to process joins with 64 or fewer tables.
87853 */
87854 typedef struct WhereTerm WhereTerm;
87855 struct WhereTerm {
87856   Expr *pExpr;            /* Pointer to the subexpression that is this term */
87857   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
87858   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
87859   union {
87860     int leftColumn;         /* Column number of X in "X <op> <expr>" */
87861     WhereOrInfo *pOrInfo;   /* Extra information if eOperator==WO_OR */
87862     WhereAndInfo *pAndInfo; /* Extra information if eOperator==WO_AND */
87863   } u;
87864   u16 eOperator;          /* A WO_xx value describing <op> */
87865   u8 wtFlags;             /* TERM_xxx bit flags.  See below */
87866   u8 nChild;              /* Number of children that must disable us */
87867   WhereClause *pWC;       /* The clause this term is part of */
87868   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
87869   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
87870 };
87871
87872 /*
87873 ** Allowed values of WhereTerm.wtFlags
87874 */
87875 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
87876 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
87877 #define TERM_CODED      0x04   /* This term is already coded */
87878 #define TERM_COPIED     0x08   /* Has a child */
87879 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
87880 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
87881 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
87882
87883 /*
87884 ** An instance of the following structure holds all information about a
87885 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
87886 */
87887 struct WhereClause {
87888   Parse *pParse;           /* The parser context */
87889   WhereMaskSet *pMaskSet;  /* Mapping of table cursor numbers to bitmasks */
87890   Bitmask vmask;           /* Bitmask identifying virtual table cursors */
87891   u8 op;                   /* Split operator.  TK_AND or TK_OR */
87892   int nTerm;               /* Number of terms */
87893   int nSlot;               /* Number of entries in a[] */
87894   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
87895 #if defined(SQLITE_SMALL_STACK)
87896   WhereTerm aStatic[1];    /* Initial static space for a[] */
87897 #else
87898   WhereTerm aStatic[8];    /* Initial static space for a[] */
87899 #endif
87900 };
87901
87902 /*
87903 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
87904 ** a dynamically allocated instance of the following structure.
87905 */
87906 struct WhereOrInfo {
87907   WhereClause wc;          /* Decomposition into subterms */
87908   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
87909 };
87910
87911 /*
87912 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
87913 ** a dynamically allocated instance of the following structure.
87914 */
87915 struct WhereAndInfo {
87916   WhereClause wc;          /* The subexpression broken out */
87917 };
87918
87919 /*
87920 ** An instance of the following structure keeps track of a mapping
87921 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
87922 **
87923 ** The VDBE cursor numbers are small integers contained in 
87924 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
87925 ** clause, the cursor numbers might not begin with 0 and they might
87926 ** contain gaps in the numbering sequence.  But we want to make maximum
87927 ** use of the bits in our bitmasks.  This structure provides a mapping
87928 ** from the sparse cursor numbers into consecutive integers beginning
87929 ** with 0.
87930 **
87931 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
87932 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
87933 **
87934 ** For example, if the WHERE clause expression used these VDBE
87935 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
87936 ** would map those cursor numbers into bits 0 through 5.
87937 **
87938 ** Note that the mapping is not necessarily ordered.  In the example
87939 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
87940 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
87941 ** does not really matter.  What is important is that sparse cursor
87942 ** numbers all get mapped into bit numbers that begin with 0 and contain
87943 ** no gaps.
87944 */
87945 struct WhereMaskSet {
87946   int n;                        /* Number of assigned cursor values */
87947   int ix[BMS];                  /* Cursor assigned to each bit */
87948 };
87949
87950 /*
87951 ** A WhereCost object records a lookup strategy and the estimated
87952 ** cost of pursuing that strategy.
87953 */
87954 struct WhereCost {
87955   WherePlan plan;    /* The lookup strategy */
87956   double rCost;      /* Overall cost of pursuing this search strategy */
87957   double nRow;       /* Estimated number of output rows */
87958   Bitmask used;      /* Bitmask of cursors used by this plan */
87959 };
87960
87961 /*
87962 ** Bitmasks for the operators that indices are able to exploit.  An
87963 ** OR-ed combination of these values can be used when searching for
87964 ** terms in the where clause.
87965 */
87966 #define WO_IN     0x001
87967 #define WO_EQ     0x002
87968 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
87969 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
87970 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
87971 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
87972 #define WO_MATCH  0x040
87973 #define WO_ISNULL 0x080
87974 #define WO_OR     0x100       /* Two or more OR-connected terms */
87975 #define WO_AND    0x200       /* Two or more AND-connected terms */
87976
87977 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
87978 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
87979
87980 /*
87981 ** Value for wsFlags returned by bestIndex() and stored in
87982 ** WhereLevel.wsFlags.  These flags determine which search
87983 ** strategies are appropriate.
87984 **
87985 ** The least significant 12 bits is reserved as a mask for WO_ values above.
87986 ** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
87987 ** But if the table is the right table of a left join, WhereLevel.wsFlags
87988 ** is set to WO_IN|WO_EQ.  The WhereLevel.wsFlags field can then be used as
87989 ** the "op" parameter to findTerm when we are resolving equality constraints.
87990 ** ISNULL constraints will then not be used on the right table of a left
87991 ** join.  Tickets #2177 and #2189.
87992 */
87993 #define WHERE_ROWID_EQ     0x00001000  /* rowid=EXPR or rowid IN (...) */
87994 #define WHERE_ROWID_RANGE  0x00002000  /* rowid<EXPR and/or rowid>EXPR */
87995 #define WHERE_COLUMN_EQ    0x00010000  /* x=EXPR or x IN (...) or x IS NULL */
87996 #define WHERE_COLUMN_RANGE 0x00020000  /* x<EXPR and/or x>EXPR */
87997 #define WHERE_COLUMN_IN    0x00040000  /* x IN (...) */
87998 #define WHERE_COLUMN_NULL  0x00080000  /* x IS NULL */
87999 #define WHERE_INDEXED      0x000f0000  /* Anything that uses an index */
88000 #define WHERE_IN_ABLE      0x000f1000  /* Able to support an IN operator */
88001 #define WHERE_TOP_LIMIT    0x00100000  /* x<EXPR or x<=EXPR constraint */
88002 #define WHERE_BTM_LIMIT    0x00200000  /* x>EXPR or x>=EXPR constraint */
88003 #define WHERE_IDX_ONLY     0x00800000  /* Use index only - omit table */
88004 #define WHERE_ORDERBY      0x01000000  /* Output will appear in correct order */
88005 #define WHERE_REVERSE      0x02000000  /* Scan in reverse order */
88006 #define WHERE_UNIQUE       0x04000000  /* Selects no more than one row */
88007 #define WHERE_VIRTUALTABLE 0x08000000  /* Use virtual-table processing */
88008 #define WHERE_MULTI_OR     0x10000000  /* OR using multiple indices */
88009
88010 /*
88011 ** Initialize a preallocated WhereClause structure.
88012 */
88013 static void whereClauseInit(
88014   WhereClause *pWC,        /* The WhereClause to be initialized */
88015   Parse *pParse,           /* The parsing context */
88016   WhereMaskSet *pMaskSet   /* Mapping from table cursor numbers to bitmasks */
88017 ){
88018   pWC->pParse = pParse;
88019   pWC->pMaskSet = pMaskSet;
88020   pWC->nTerm = 0;
88021   pWC->nSlot = ArraySize(pWC->aStatic);
88022   pWC->a = pWC->aStatic;
88023   pWC->vmask = 0;
88024 }
88025
88026 /* Forward reference */
88027 static void whereClauseClear(WhereClause*);
88028
88029 /*
88030 ** Deallocate all memory associated with a WhereOrInfo object.
88031 */
88032 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
88033   whereClauseClear(&p->wc);
88034   sqlite3DbFree(db, p);
88035 }
88036
88037 /*
88038 ** Deallocate all memory associated with a WhereAndInfo object.
88039 */
88040 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
88041   whereClauseClear(&p->wc);
88042   sqlite3DbFree(db, p);
88043 }
88044
88045 /*
88046 ** Deallocate a WhereClause structure.  The WhereClause structure
88047 ** itself is not freed.  This routine is the inverse of whereClauseInit().
88048 */
88049 static void whereClauseClear(WhereClause *pWC){
88050   int i;
88051   WhereTerm *a;
88052   sqlite3 *db = pWC->pParse->db;
88053   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
88054     if( a->wtFlags & TERM_DYNAMIC ){
88055       sqlite3ExprDelete(db, a->pExpr);
88056     }
88057     if( a->wtFlags & TERM_ORINFO ){
88058       whereOrInfoDelete(db, a->u.pOrInfo);
88059     }else if( a->wtFlags & TERM_ANDINFO ){
88060       whereAndInfoDelete(db, a->u.pAndInfo);
88061     }
88062   }
88063   if( pWC->a!=pWC->aStatic ){
88064     sqlite3DbFree(db, pWC->a);
88065   }
88066 }
88067
88068 /*
88069 ** Add a single new WhereTerm entry to the WhereClause object pWC.
88070 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
88071 ** The index in pWC->a[] of the new WhereTerm is returned on success.
88072 ** 0 is returned if the new WhereTerm could not be added due to a memory
88073 ** allocation error.  The memory allocation failure will be recorded in
88074 ** the db->mallocFailed flag so that higher-level functions can detect it.
88075 **
88076 ** This routine will increase the size of the pWC->a[] array as necessary.
88077 **
88078 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
88079 ** for freeing the expression p is assumed by the WhereClause object pWC.
88080 ** This is true even if this routine fails to allocate a new WhereTerm.
88081 **
88082 ** WARNING:  This routine might reallocate the space used to store
88083 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
88084 ** calling this routine.  Such pointers may be reinitialized by referencing
88085 ** the pWC->a[] array.
88086 */
88087 static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
88088   WhereTerm *pTerm;
88089   int idx;
88090   if( pWC->nTerm>=pWC->nSlot ){
88091     WhereTerm *pOld = pWC->a;
88092     sqlite3 *db = pWC->pParse->db;
88093     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
88094     if( pWC->a==0 ){
88095       if( wtFlags & TERM_DYNAMIC ){
88096         sqlite3ExprDelete(db, p);
88097       }
88098       pWC->a = pOld;
88099       return 0;
88100     }
88101     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
88102     if( pOld!=pWC->aStatic ){
88103       sqlite3DbFree(db, pOld);
88104     }
88105     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
88106   }
88107   pTerm = &pWC->a[idx = pWC->nTerm++];
88108   pTerm->pExpr = p;
88109   pTerm->wtFlags = wtFlags;
88110   pTerm->pWC = pWC;
88111   pTerm->iParent = -1;
88112   return idx;
88113 }
88114
88115 /*
88116 ** This routine identifies subexpressions in the WHERE clause where
88117 ** each subexpression is separated by the AND operator or some other
88118 ** operator specified in the op parameter.  The WhereClause structure
88119 ** is filled with pointers to subexpressions.  For example:
88120 **
88121 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
88122 **           \________/     \_______________/     \________________/
88123 **            slot[0]            slot[1]               slot[2]
88124 **
88125 ** The original WHERE clause in pExpr is unaltered.  All this routine
88126 ** does is make slot[] entries point to substructure within pExpr.
88127 **
88128 ** In the previous sentence and in the diagram, "slot[]" refers to
88129 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
88130 ** all terms of the WHERE clause.
88131 */
88132 static void whereSplit(WhereClause *pWC, Expr *pExpr, int op){
88133   pWC->op = (u8)op;
88134   if( pExpr==0 ) return;
88135   if( pExpr->op!=op ){
88136     whereClauseInsert(pWC, pExpr, 0);
88137   }else{
88138     whereSplit(pWC, pExpr->pLeft, op);
88139     whereSplit(pWC, pExpr->pRight, op);
88140   }
88141 }
88142
88143 /*
88144 ** Initialize an expression mask set (a WhereMaskSet object)
88145 */
88146 #define initMaskSet(P)  memset(P, 0, sizeof(*P))
88147
88148 /*
88149 ** Return the bitmask for the given cursor number.  Return 0 if
88150 ** iCursor is not in the set.
88151 */
88152 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
88153   int i;
88154   assert( pMaskSet->n<=sizeof(Bitmask)*8 );
88155   for(i=0; i<pMaskSet->n; i++){
88156     if( pMaskSet->ix[i]==iCursor ){
88157       return ((Bitmask)1)<<i;
88158     }
88159   }
88160   return 0;
88161 }
88162
88163 /*
88164 ** Create a new mask for cursor iCursor.
88165 **
88166 ** There is one cursor per table in the FROM clause.  The number of
88167 ** tables in the FROM clause is limited by a test early in the
88168 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
88169 ** array will never overflow.
88170 */
88171 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
88172   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
88173   pMaskSet->ix[pMaskSet->n++] = iCursor;
88174 }
88175
88176 /*
88177 ** This routine walks (recursively) an expression tree and generates
88178 ** a bitmask indicating which tables are used in that expression
88179 ** tree.
88180 **
88181 ** In order for this routine to work, the calling function must have
88182 ** previously invoked sqlite3ResolveExprNames() on the expression.  See
88183 ** the header comment on that routine for additional information.
88184 ** The sqlite3ResolveExprNames() routines looks for column names and
88185 ** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
88186 ** the VDBE cursor number of the table.  This routine just has to
88187 ** translate the cursor numbers into bitmask values and OR all
88188 ** the bitmasks together.
88189 */
88190 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
88191 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
88192 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
88193   Bitmask mask = 0;
88194   if( p==0 ) return 0;
88195   if( p->op==TK_COLUMN ){
88196     mask = getMask(pMaskSet, p->iTable);
88197     return mask;
88198   }
88199   mask = exprTableUsage(pMaskSet, p->pRight);
88200   mask |= exprTableUsage(pMaskSet, p->pLeft);
88201   if( ExprHasProperty(p, EP_xIsSelect) ){
88202     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
88203   }else{
88204     mask |= exprListTableUsage(pMaskSet, p->x.pList);
88205   }
88206   return mask;
88207 }
88208 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
88209   int i;
88210   Bitmask mask = 0;
88211   if( pList ){
88212     for(i=0; i<pList->nExpr; i++){
88213       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
88214     }
88215   }
88216   return mask;
88217 }
88218 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
88219   Bitmask mask = 0;
88220   while( pS ){
88221     mask |= exprListTableUsage(pMaskSet, pS->pEList);
88222     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
88223     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
88224     mask |= exprTableUsage(pMaskSet, pS->pWhere);
88225     mask |= exprTableUsage(pMaskSet, pS->pHaving);
88226     pS = pS->pPrior;
88227   }
88228   return mask;
88229 }
88230
88231 /*
88232 ** Return TRUE if the given operator is one of the operators that is
88233 ** allowed for an indexable WHERE clause term.  The allowed operators are
88234 ** "=", "<", ">", "<=", ">=", and "IN".
88235 */
88236 static int allowedOp(int op){
88237   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
88238   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
88239   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
88240   assert( TK_GE==TK_EQ+4 );
88241   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
88242 }
88243
88244 /*
88245 ** Swap two objects of type TYPE.
88246 */
88247 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
88248
88249 /*
88250 ** Commute a comparison operator.  Expressions of the form "X op Y"
88251 ** are converted into "Y op X".
88252 **
88253 ** If a collation sequence is associated with either the left or right
88254 ** side of the comparison, it remains associated with the same side after
88255 ** the commutation. So "Y collate NOCASE op X" becomes 
88256 ** "X collate NOCASE op Y". This is because any collation sequence on
88257 ** the left hand side of a comparison overrides any collation sequence 
88258 ** attached to the right. For the same reason the EP_ExpCollate flag
88259 ** is not commuted.
88260 */
88261 static void exprCommute(Parse *pParse, Expr *pExpr){
88262   u16 expRight = (pExpr->pRight->flags & EP_ExpCollate);
88263   u16 expLeft = (pExpr->pLeft->flags & EP_ExpCollate);
88264   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
88265   pExpr->pRight->pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
88266   pExpr->pLeft->pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
88267   SWAP(CollSeq*,pExpr->pRight->pColl,pExpr->pLeft->pColl);
88268   pExpr->pRight->flags = (pExpr->pRight->flags & ~EP_ExpCollate) | expLeft;
88269   pExpr->pLeft->flags = (pExpr->pLeft->flags & ~EP_ExpCollate) | expRight;
88270   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
88271   if( pExpr->op>=TK_GT ){
88272     assert( TK_LT==TK_GT+2 );
88273     assert( TK_GE==TK_LE+2 );
88274     assert( TK_GT>TK_EQ );
88275     assert( TK_GT<TK_LE );
88276     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
88277     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
88278   }
88279 }
88280
88281 /*
88282 ** Translate from TK_xx operator to WO_xx bitmask.
88283 */
88284 static u16 operatorMask(int op){
88285   u16 c;
88286   assert( allowedOp(op) );
88287   if( op==TK_IN ){
88288     c = WO_IN;
88289   }else if( op==TK_ISNULL ){
88290     c = WO_ISNULL;
88291   }else{
88292     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
88293     c = (u16)(WO_EQ<<(op-TK_EQ));
88294   }
88295   assert( op!=TK_ISNULL || c==WO_ISNULL );
88296   assert( op!=TK_IN || c==WO_IN );
88297   assert( op!=TK_EQ || c==WO_EQ );
88298   assert( op!=TK_LT || c==WO_LT );
88299   assert( op!=TK_LE || c==WO_LE );
88300   assert( op!=TK_GT || c==WO_GT );
88301   assert( op!=TK_GE || c==WO_GE );
88302   return c;
88303 }
88304
88305 /*
88306 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
88307 ** where X is a reference to the iColumn of table iCur and <op> is one of
88308 ** the WO_xx operator codes specified by the op parameter.
88309 ** Return a pointer to the term.  Return 0 if not found.
88310 */
88311 static WhereTerm *findTerm(
88312   WhereClause *pWC,     /* The WHERE clause to be searched */
88313   int iCur,             /* Cursor number of LHS */
88314   int iColumn,          /* Column number of LHS */
88315   Bitmask notReady,     /* RHS must not overlap with this mask */
88316   u32 op,               /* Mask of WO_xx values describing operator */
88317   Index *pIdx           /* Must be compatible with this index, if not NULL */
88318 ){
88319   WhereTerm *pTerm;
88320   int k;
88321   assert( iCur>=0 );
88322   op &= WO_ALL;
88323   for(pTerm=pWC->a, k=pWC->nTerm; k; k--, pTerm++){
88324     if( pTerm->leftCursor==iCur
88325        && (pTerm->prereqRight & notReady)==0
88326        && pTerm->u.leftColumn==iColumn
88327        && (pTerm->eOperator & op)!=0
88328     ){
88329       if( pIdx && pTerm->eOperator!=WO_ISNULL ){
88330         Expr *pX = pTerm->pExpr;
88331         CollSeq *pColl;
88332         char idxaff;
88333         int j;
88334         Parse *pParse = pWC->pParse;
88335
88336         idxaff = pIdx->pTable->aCol[iColumn].affinity;
88337         if( !sqlite3IndexAffinityOk(pX, idxaff) ) continue;
88338
88339         /* Figure out the collation sequence required from an index for
88340         ** it to be useful for optimising expression pX. Store this
88341         ** value in variable pColl.
88342         */
88343         assert(pX->pLeft);
88344         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
88345         assert(pColl || pParse->nErr);
88346
88347         for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
88348           if( NEVER(j>=pIdx->nColumn) ) return 0;
88349         }
88350         if( pColl && sqlite3StrICmp(pColl->zName, pIdx->azColl[j]) ) continue;
88351       }
88352       return pTerm;
88353     }
88354   }
88355   return 0;
88356 }
88357
88358 /* Forward reference */
88359 static void exprAnalyze(SrcList*, WhereClause*, int);
88360
88361 /*
88362 ** Call exprAnalyze on all terms in a WHERE clause.  
88363 **
88364 **
88365 */
88366 static void exprAnalyzeAll(
88367   SrcList *pTabList,       /* the FROM clause */
88368   WhereClause *pWC         /* the WHERE clause to be analyzed */
88369 ){
88370   int i;
88371   for(i=pWC->nTerm-1; i>=0; i--){
88372     exprAnalyze(pTabList, pWC, i);
88373   }
88374 }
88375
88376 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
88377 /*
88378 ** Check to see if the given expression is a LIKE or GLOB operator that
88379 ** can be optimized using inequality constraints.  Return TRUE if it is
88380 ** so and false if not.
88381 **
88382 ** In order for the operator to be optimizible, the RHS must be a string
88383 ** literal that does not begin with a wildcard.  
88384 */
88385 static int isLikeOrGlob(
88386   Parse *pParse,    /* Parsing and code generating context */
88387   Expr *pExpr,      /* Test this expression */
88388   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
88389   int *pisComplete, /* True if the only wildcard is % in the last character */
88390   int *pnoCase      /* True if uppercase is equivalent to lowercase */
88391 ){
88392   const char *z = 0;         /* String on RHS of LIKE operator */
88393   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
88394   ExprList *pList;           /* List of operands to the LIKE operator */
88395   int c;                     /* One character in z[] */
88396   int cnt;                   /* Number of non-wildcard prefix characters */
88397   char wc[3];                /* Wildcard characters */
88398   CollSeq *pColl;            /* Collating sequence for LHS */
88399   sqlite3 *db = pParse->db;  /* Database connection */
88400   sqlite3_value *pVal = 0;
88401   int op;                    /* Opcode of pRight */
88402
88403   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
88404     return 0;
88405   }
88406 #ifdef SQLITE_EBCDIC
88407   if( *pnoCase ) return 0;
88408 #endif
88409   pList = pExpr->x.pList;
88410   pLeft = pList->a[1].pExpr;
88411   if( pLeft->op!=TK_COLUMN || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT ){
88412     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
88413     ** be the name of an indexed column with TEXT affinity. */
88414     return 0;
88415   }
88416   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
88417   pColl = sqlite3ExprCollSeq(pParse, pLeft);
88418   if( pColl==0 ) return 0;  /* Happens when LHS has an undefined collation */
88419   if( (pColl->type!=SQLITE_COLL_BINARY || *pnoCase) &&
88420       (pColl->type!=SQLITE_COLL_NOCASE || !*pnoCase) ){
88421     /* IMP: R-09003-32046 For the GLOB operator, the column must use the
88422     ** default BINARY collating sequence.
88423     ** IMP: R-41408-28306 For the LIKE operator, if case_sensitive_like mode
88424     ** is enabled then the column must use the default BINARY collating
88425     ** sequence, or if case_sensitive_like mode is disabled then the column
88426     ** must use the built-in NOCASE collating sequence.
88427     */
88428     return 0;
88429   }
88430
88431   pRight = pList->a[0].pExpr;
88432   op = pRight->op;
88433   if( op==TK_REGISTER ){
88434     op = pRight->op2;
88435   }
88436   if( op==TK_VARIABLE ){
88437     Vdbe *pReprepare = pParse->pReprepare;
88438     pVal = sqlite3VdbeGetValue(pReprepare, pRight->iColumn, SQLITE_AFF_NONE);
88439     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
88440       z = (char *)sqlite3_value_text(pVal);
88441     }
88442     sqlite3VdbeSetVarmask(pParse->pVdbe, pRight->iColumn);
88443     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
88444   }else if( op==TK_STRING ){
88445     z = pRight->u.zToken;
88446   }
88447   if( z ){
88448     cnt = 0;
88449     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
88450       cnt++;
88451     }
88452     if( cnt!=0 && c!=0 && 255!=(u8)z[cnt-1] ){
88453       Expr *pPrefix;
88454       *pisComplete = z[cnt]==wc[0] && z[cnt+1]==0;
88455       pPrefix = sqlite3Expr(db, TK_STRING, z);
88456       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
88457       *ppPrefix = pPrefix;
88458       if( op==TK_VARIABLE ){
88459         Vdbe *v = pParse->pVdbe;
88460         sqlite3VdbeSetVarmask(v, pRight->iColumn);
88461         if( *pisComplete && pRight->u.zToken[1] ){
88462           /* If the rhs of the LIKE expression is a variable, and the current
88463           ** value of the variable means there is no need to invoke the LIKE
88464           ** function, then no OP_Variable will be added to the program.
88465           ** This causes problems for the sqlite3_bind_parameter_name()
88466           ** API. To workaround them, add a dummy OP_Variable here.
88467           */ 
88468           int r1 = sqlite3GetTempReg(pParse);
88469           sqlite3ExprCodeTarget(pParse, pRight, r1);
88470           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
88471           sqlite3ReleaseTempReg(pParse, r1);
88472         }
88473       }
88474     }else{
88475       z = 0;
88476     }
88477   }
88478
88479   sqlite3ValueFree(pVal);
88480   return (z!=0);
88481 }
88482 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
88483
88484
88485 #ifndef SQLITE_OMIT_VIRTUALTABLE
88486 /*
88487 ** Check to see if the given expression is of the form
88488 **
88489 **         column MATCH expr
88490 **
88491 ** If it is then return TRUE.  If not, return FALSE.
88492 */
88493 static int isMatchOfColumn(
88494   Expr *pExpr      /* Test this expression */
88495 ){
88496   ExprList *pList;
88497
88498   if( pExpr->op!=TK_FUNCTION ){
88499     return 0;
88500   }
88501   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
88502     return 0;
88503   }
88504   pList = pExpr->x.pList;
88505   if( pList->nExpr!=2 ){
88506     return 0;
88507   }
88508   if( pList->a[1].pExpr->op != TK_COLUMN ){
88509     return 0;
88510   }
88511   return 1;
88512 }
88513 #endif /* SQLITE_OMIT_VIRTUALTABLE */
88514
88515 /*
88516 ** If the pBase expression originated in the ON or USING clause of
88517 ** a join, then transfer the appropriate markings over to derived.
88518 */
88519 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
88520   pDerived->flags |= pBase->flags & EP_FromJoin;
88521   pDerived->iRightJoinTable = pBase->iRightJoinTable;
88522 }
88523
88524 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
88525 /*
88526 ** Analyze a term that consists of two or more OR-connected
88527 ** subterms.  So in:
88528 **
88529 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
88530 **                          ^^^^^^^^^^^^^^^^^^^^
88531 **
88532 ** This routine analyzes terms such as the middle term in the above example.
88533 ** A WhereOrTerm object is computed and attached to the term under
88534 ** analysis, regardless of the outcome of the analysis.  Hence:
88535 **
88536 **     WhereTerm.wtFlags   |=  TERM_ORINFO
88537 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
88538 **
88539 ** The term being analyzed must have two or more of OR-connected subterms.
88540 ** A single subterm might be a set of AND-connected sub-subterms.
88541 ** Examples of terms under analysis:
88542 **
88543 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
88544 **     (B)     x=expr1 OR expr2=x OR x=expr3
88545 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
88546 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
88547 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
88548 **
88549 ** CASE 1:
88550 **
88551 ** If all subterms are of the form T.C=expr for some single column of C
88552 ** a single table T (as shown in example B above) then create a new virtual
88553 ** term that is an equivalent IN expression.  In other words, if the term
88554 ** being analyzed is:
88555 **
88556 **      x = expr1  OR  expr2 = x  OR  x = expr3
88557 **
88558 ** then create a new virtual term like this:
88559 **
88560 **      x IN (expr1,expr2,expr3)
88561 **
88562 ** CASE 2:
88563 **
88564 ** If all subterms are indexable by a single table T, then set
88565 **
88566 **     WhereTerm.eOperator              =  WO_OR
88567 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
88568 **
88569 ** A subterm is "indexable" if it is of the form
88570 ** "T.C <op> <expr>" where C is any column of table T and 
88571 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
88572 ** A subterm is also indexable if it is an AND of two or more
88573 ** subsubterms at least one of which is indexable.  Indexable AND 
88574 ** subterms have their eOperator set to WO_AND and they have
88575 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
88576 **
88577 ** From another point of view, "indexable" means that the subterm could
88578 ** potentially be used with an index if an appropriate index exists.
88579 ** This analysis does not consider whether or not the index exists; that
88580 ** is something the bestIndex() routine will determine.  This analysis
88581 ** only looks at whether subterms appropriate for indexing exist.
88582 **
88583 ** All examples A through E above all satisfy case 2.  But if a term
88584 ** also statisfies case 1 (such as B) we know that the optimizer will
88585 ** always prefer case 1, so in that case we pretend that case 2 is not
88586 ** satisfied.
88587 **
88588 ** It might be the case that multiple tables are indexable.  For example,
88589 ** (E) above is indexable on tables P, Q, and R.
88590 **
88591 ** Terms that satisfy case 2 are candidates for lookup by using
88592 ** separate indices to find rowids for each subterm and composing
88593 ** the union of all rowids using a RowSet object.  This is similar
88594 ** to "bitmap indices" in other database engines.
88595 **
88596 ** OTHERWISE:
88597 **
88598 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
88599 ** zero.  This term is not useful for search.
88600 */
88601 static void exprAnalyzeOrTerm(
88602   SrcList *pSrc,            /* the FROM clause */
88603   WhereClause *pWC,         /* the complete WHERE clause */
88604   int idxTerm               /* Index of the OR-term to be analyzed */
88605 ){
88606   Parse *pParse = pWC->pParse;            /* Parser context */
88607   sqlite3 *db = pParse->db;               /* Database connection */
88608   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
88609   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
88610   WhereMaskSet *pMaskSet = pWC->pMaskSet; /* Table use masks */
88611   int i;                                  /* Loop counters */
88612   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
88613   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
88614   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
88615   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
88616   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
88617
88618   /*
88619   ** Break the OR clause into its separate subterms.  The subterms are
88620   ** stored in a WhereClause structure containing within the WhereOrInfo
88621   ** object that is attached to the original OR clause term.
88622   */
88623   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
88624   assert( pExpr->op==TK_OR );
88625   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
88626   if( pOrInfo==0 ) return;
88627   pTerm->wtFlags |= TERM_ORINFO;
88628   pOrWc = &pOrInfo->wc;
88629   whereClauseInit(pOrWc, pWC->pParse, pMaskSet);
88630   whereSplit(pOrWc, pExpr, TK_OR);
88631   exprAnalyzeAll(pSrc, pOrWc);
88632   if( db->mallocFailed ) return;
88633   assert( pOrWc->nTerm>=2 );
88634
88635   /*
88636   ** Compute the set of tables that might satisfy cases 1 or 2.
88637   */
88638   indexable = ~(Bitmask)0;
88639   chngToIN = ~(pWC->vmask);
88640   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
88641     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
88642       WhereAndInfo *pAndInfo;
88643       assert( pOrTerm->eOperator==0 );
88644       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
88645       chngToIN = 0;
88646       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
88647       if( pAndInfo ){
88648         WhereClause *pAndWC;
88649         WhereTerm *pAndTerm;
88650         int j;
88651         Bitmask b = 0;
88652         pOrTerm->u.pAndInfo = pAndInfo;
88653         pOrTerm->wtFlags |= TERM_ANDINFO;
88654         pOrTerm->eOperator = WO_AND;
88655         pAndWC = &pAndInfo->wc;
88656         whereClauseInit(pAndWC, pWC->pParse, pMaskSet);
88657         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
88658         exprAnalyzeAll(pSrc, pAndWC);
88659         testcase( db->mallocFailed );
88660         if( !db->mallocFailed ){
88661           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
88662             assert( pAndTerm->pExpr );
88663             if( allowedOp(pAndTerm->pExpr->op) ){
88664               b |= getMask(pMaskSet, pAndTerm->leftCursor);
88665             }
88666           }
88667         }
88668         indexable &= b;
88669       }
88670     }else if( pOrTerm->wtFlags & TERM_COPIED ){
88671       /* Skip this term for now.  We revisit it when we process the
88672       ** corresponding TERM_VIRTUAL term */
88673     }else{
88674       Bitmask b;
88675       b = getMask(pMaskSet, pOrTerm->leftCursor);
88676       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
88677         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
88678         b |= getMask(pMaskSet, pOther->leftCursor);
88679       }
88680       indexable &= b;
88681       if( pOrTerm->eOperator!=WO_EQ ){
88682         chngToIN = 0;
88683       }else{
88684         chngToIN &= b;
88685       }
88686     }
88687   }
88688
88689   /*
88690   ** Record the set of tables that satisfy case 2.  The set might be
88691   ** empty.
88692   */
88693   pOrInfo->indexable = indexable;
88694   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
88695
88696   /*
88697   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
88698   ** we have to do some additional checking to see if case 1 really
88699   ** is satisfied.
88700   **
88701   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
88702   ** that there is no possibility of transforming the OR clause into an
88703   ** IN operator because one or more terms in the OR clause contain
88704   ** something other than == on a column in the single table.  The 1-bit
88705   ** case means that every term of the OR clause is of the form
88706   ** "table.column=expr" for some single table.  The one bit that is set
88707   ** will correspond to the common table.  We still need to check to make
88708   ** sure the same column is used on all terms.  The 2-bit case is when
88709   ** the all terms are of the form "table1.column=table2.column".  It
88710   ** might be possible to form an IN operator with either table1.column
88711   ** or table2.column as the LHS if either is common to every term of
88712   ** the OR clause.
88713   **
88714   ** Note that terms of the form "table.column1=table.column2" (the
88715   ** same table on both sizes of the ==) cannot be optimized.
88716   */
88717   if( chngToIN ){
88718     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
88719     int iColumn = -1;         /* Column index on lhs of IN operator */
88720     int iCursor = -1;         /* Table cursor common to all terms */
88721     int j = 0;                /* Loop counter */
88722
88723     /* Search for a table and column that appears on one side or the
88724     ** other of the == operator in every subterm.  That table and column
88725     ** will be recorded in iCursor and iColumn.  There might not be any
88726     ** such table and column.  Set okToChngToIN if an appropriate table
88727     ** and column is found but leave okToChngToIN false if not found.
88728     */
88729     for(j=0; j<2 && !okToChngToIN; j++){
88730       pOrTerm = pOrWc->a;
88731       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
88732         assert( pOrTerm->eOperator==WO_EQ );
88733         pOrTerm->wtFlags &= ~TERM_OR_OK;
88734         if( pOrTerm->leftCursor==iCursor ){
88735           /* This is the 2-bit case and we are on the second iteration and
88736           ** current term is from the first iteration.  So skip this term. */
88737           assert( j==1 );
88738           continue;
88739         }
88740         if( (chngToIN & getMask(pMaskSet, pOrTerm->leftCursor))==0 ){
88741           /* This term must be of the form t1.a==t2.b where t2 is in the
88742           ** chngToIN set but t1 is not.  This term will be either preceeded
88743           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
88744           ** and use its inversion. */
88745           testcase( pOrTerm->wtFlags & TERM_COPIED );
88746           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
88747           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
88748           continue;
88749         }
88750         iColumn = pOrTerm->u.leftColumn;
88751         iCursor = pOrTerm->leftCursor;
88752         break;
88753       }
88754       if( i<0 ){
88755         /* No candidate table+column was found.  This can only occur
88756         ** on the second iteration */
88757         assert( j==1 );
88758         assert( (chngToIN&(chngToIN-1))==0 );
88759         assert( chngToIN==getMask(pMaskSet, iCursor) );
88760         break;
88761       }
88762       testcase( j==1 );
88763
88764       /* We have found a candidate table and column.  Check to see if that
88765       ** table and column is common to every term in the OR clause */
88766       okToChngToIN = 1;
88767       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
88768         assert( pOrTerm->eOperator==WO_EQ );
88769         if( pOrTerm->leftCursor!=iCursor ){
88770           pOrTerm->wtFlags &= ~TERM_OR_OK;
88771         }else if( pOrTerm->u.leftColumn!=iColumn ){
88772           okToChngToIN = 0;
88773         }else{
88774           int affLeft, affRight;
88775           /* If the right-hand side is also a column, then the affinities
88776           ** of both right and left sides must be such that no type
88777           ** conversions are required on the right.  (Ticket #2249)
88778           */
88779           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
88780           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
88781           if( affRight!=0 && affRight!=affLeft ){
88782             okToChngToIN = 0;
88783           }else{
88784             pOrTerm->wtFlags |= TERM_OR_OK;
88785           }
88786         }
88787       }
88788     }
88789
88790     /* At this point, okToChngToIN is true if original pTerm satisfies
88791     ** case 1.  In that case, construct a new virtual term that is 
88792     ** pTerm converted into an IN operator.
88793     */
88794     if( okToChngToIN ){
88795       Expr *pDup;            /* A transient duplicate expression */
88796       ExprList *pList = 0;   /* The RHS of the IN operator */
88797       Expr *pLeft = 0;       /* The LHS of the IN operator */
88798       Expr *pNew;            /* The complete IN operator */
88799
88800       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
88801         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
88802         assert( pOrTerm->eOperator==WO_EQ );
88803         assert( pOrTerm->leftCursor==iCursor );
88804         assert( pOrTerm->u.leftColumn==iColumn );
88805         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
88806         pList = sqlite3ExprListAppend(pWC->pParse, pList, pDup);
88807         pLeft = pOrTerm->pExpr->pLeft;
88808       }
88809       assert( pLeft!=0 );
88810       pDup = sqlite3ExprDup(db, pLeft, 0);
88811       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
88812       if( pNew ){
88813         int idxNew;
88814         transferJoinMarkings(pNew, pExpr);
88815         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
88816         pNew->x.pList = pList;
88817         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
88818         testcase( idxNew==0 );
88819         exprAnalyze(pSrc, pWC, idxNew);
88820         pTerm = &pWC->a[idxTerm];
88821         pWC->a[idxNew].iParent = idxTerm;
88822         pTerm->nChild = 1;
88823       }else{
88824         sqlite3ExprListDelete(db, pList);
88825       }
88826       pTerm->eOperator = 0;  /* case 1 trumps case 2 */
88827     }
88828   }
88829 }
88830 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
88831
88832
88833 /*
88834 ** The input to this routine is an WhereTerm structure with only the
88835 ** "pExpr" field filled in.  The job of this routine is to analyze the
88836 ** subexpression and populate all the other fields of the WhereTerm
88837 ** structure.
88838 **
88839 ** If the expression is of the form "<expr> <op> X" it gets commuted
88840 ** to the standard form of "X <op> <expr>".
88841 **
88842 ** If the expression is of the form "X <op> Y" where both X and Y are
88843 ** columns, then the original expression is unchanged and a new virtual
88844 ** term of the form "Y <op> X" is added to the WHERE clause and
88845 ** analyzed separately.  The original term is marked with TERM_COPIED
88846 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
88847 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
88848 ** is a commuted copy of a prior term.)  The original term has nChild=1
88849 ** and the copy has idxParent set to the index of the original term.
88850 */
88851 static void exprAnalyze(
88852   SrcList *pSrc,            /* the FROM clause */
88853   WhereClause *pWC,         /* the WHERE clause */
88854   int idxTerm               /* Index of the term to be analyzed */
88855 ){
88856   WhereTerm *pTerm;                /* The term to be analyzed */
88857   WhereMaskSet *pMaskSet;          /* Set of table index masks */
88858   Expr *pExpr;                     /* The expression to be analyzed */
88859   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
88860   Bitmask prereqAll;               /* Prerequesites of pExpr */
88861   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
88862   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
88863   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
88864   int noCase = 0;                  /* LIKE/GLOB distinguishes case */
88865   int op;                          /* Top-level operator.  pExpr->op */
88866   Parse *pParse = pWC->pParse;     /* Parsing context */
88867   sqlite3 *db = pParse->db;        /* Database connection */
88868
88869   if( db->mallocFailed ){
88870     return;
88871   }
88872   pTerm = &pWC->a[idxTerm];
88873   pMaskSet = pWC->pMaskSet;
88874   pExpr = pTerm->pExpr;
88875   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
88876   op = pExpr->op;
88877   if( op==TK_IN ){
88878     assert( pExpr->pRight==0 );
88879     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
88880       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
88881     }else{
88882       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
88883     }
88884   }else if( op==TK_ISNULL ){
88885     pTerm->prereqRight = 0;
88886   }else{
88887     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
88888   }
88889   prereqAll = exprTableUsage(pMaskSet, pExpr);
88890   if( ExprHasProperty(pExpr, EP_FromJoin) ){
88891     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
88892     prereqAll |= x;
88893     extraRight = x-1;  /* ON clause terms may not be used with an index
88894                        ** on left table of a LEFT JOIN.  Ticket #3015 */
88895   }
88896   pTerm->prereqAll = prereqAll;
88897   pTerm->leftCursor = -1;
88898   pTerm->iParent = -1;
88899   pTerm->eOperator = 0;
88900   if( allowedOp(op) && (pTerm->prereqRight & prereqLeft)==0 ){
88901     Expr *pLeft = pExpr->pLeft;
88902     Expr *pRight = pExpr->pRight;
88903     if( pLeft->op==TK_COLUMN ){
88904       pTerm->leftCursor = pLeft->iTable;
88905       pTerm->u.leftColumn = pLeft->iColumn;
88906       pTerm->eOperator = operatorMask(op);
88907     }
88908     if( pRight && pRight->op==TK_COLUMN ){
88909       WhereTerm *pNew;
88910       Expr *pDup;
88911       if( pTerm->leftCursor>=0 ){
88912         int idxNew;
88913         pDup = sqlite3ExprDup(db, pExpr, 0);
88914         if( db->mallocFailed ){
88915           sqlite3ExprDelete(db, pDup);
88916           return;
88917         }
88918         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
88919         if( idxNew==0 ) return;
88920         pNew = &pWC->a[idxNew];
88921         pNew->iParent = idxTerm;
88922         pTerm = &pWC->a[idxTerm];
88923         pTerm->nChild = 1;
88924         pTerm->wtFlags |= TERM_COPIED;
88925       }else{
88926         pDup = pExpr;
88927         pNew = pTerm;
88928       }
88929       exprCommute(pParse, pDup);
88930       pLeft = pDup->pLeft;
88931       pNew->leftCursor = pLeft->iTable;
88932       pNew->u.leftColumn = pLeft->iColumn;
88933       testcase( (prereqLeft | extraRight) != prereqLeft );
88934       pNew->prereqRight = prereqLeft | extraRight;
88935       pNew->prereqAll = prereqAll;
88936       pNew->eOperator = operatorMask(pDup->op);
88937     }
88938   }
88939
88940 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
88941   /* If a term is the BETWEEN operator, create two new virtual terms
88942   ** that define the range that the BETWEEN implements.  For example:
88943   **
88944   **      a BETWEEN b AND c
88945   **
88946   ** is converted into:
88947   **
88948   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
88949   **
88950   ** The two new terms are added onto the end of the WhereClause object.
88951   ** The new terms are "dynamic" and are children of the original BETWEEN
88952   ** term.  That means that if the BETWEEN term is coded, the children are
88953   ** skipped.  Or, if the children are satisfied by an index, the original
88954   ** BETWEEN term is skipped.
88955   */
88956   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
88957     ExprList *pList = pExpr->x.pList;
88958     int i;
88959     static const u8 ops[] = {TK_GE, TK_LE};
88960     assert( pList!=0 );
88961     assert( pList->nExpr==2 );
88962     for(i=0; i<2; i++){
88963       Expr *pNewExpr;
88964       int idxNew;
88965       pNewExpr = sqlite3PExpr(pParse, ops[i], 
88966                              sqlite3ExprDup(db, pExpr->pLeft, 0),
88967                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
88968       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
88969       testcase( idxNew==0 );
88970       exprAnalyze(pSrc, pWC, idxNew);
88971       pTerm = &pWC->a[idxTerm];
88972       pWC->a[idxNew].iParent = idxTerm;
88973     }
88974     pTerm->nChild = 2;
88975   }
88976 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
88977
88978 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
88979   /* Analyze a term that is composed of two or more subterms connected by
88980   ** an OR operator.
88981   */
88982   else if( pExpr->op==TK_OR ){
88983     assert( pWC->op==TK_AND );
88984     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
88985     pTerm = &pWC->a[idxTerm];
88986   }
88987 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
88988
88989 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
88990   /* Add constraints to reduce the search space on a LIKE or GLOB
88991   ** operator.
88992   **
88993   ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
88994   **
88995   **          x>='abc' AND x<'abd' AND x LIKE 'abc%'
88996   **
88997   ** The last character of the prefix "abc" is incremented to form the
88998   ** termination condition "abd".
88999   */
89000   if( pWC->op==TK_AND 
89001    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
89002   ){
89003     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
89004     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
89005     Expr *pNewExpr1;
89006     Expr *pNewExpr2;
89007     int idxNew1;
89008     int idxNew2;
89009
89010     pLeft = pExpr->x.pList->a[1].pExpr;
89011     pStr2 = sqlite3ExprDup(db, pStr1, 0);
89012     if( !db->mallocFailed ){
89013       u8 c, *pC;       /* Last character before the first wildcard */
89014       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
89015       c = *pC;
89016       if( noCase ){
89017         /* The point is to increment the last character before the first
89018         ** wildcard.  But if we increment '@', that will push it into the
89019         ** alphabetic range where case conversions will mess up the 
89020         ** inequality.  To avoid this, make sure to also run the full
89021         ** LIKE on all candidate expressions by clearing the isComplete flag
89022         */
89023         if( c=='A'-1 ) isComplete = 0;
89024
89025         c = sqlite3UpperToLower[c];
89026       }
89027       *pC = c + 1;
89028     }
89029     pNewExpr1 = sqlite3PExpr(pParse, TK_GE, sqlite3ExprDup(db,pLeft,0),pStr1,0);
89030     idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
89031     testcase( idxNew1==0 );
89032     exprAnalyze(pSrc, pWC, idxNew1);
89033     pNewExpr2 = sqlite3PExpr(pParse, TK_LT, sqlite3ExprDup(db,pLeft,0),pStr2,0);
89034     idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
89035     testcase( idxNew2==0 );
89036     exprAnalyze(pSrc, pWC, idxNew2);
89037     pTerm = &pWC->a[idxTerm];
89038     if( isComplete ){
89039       pWC->a[idxNew1].iParent = idxTerm;
89040       pWC->a[idxNew2].iParent = idxTerm;
89041       pTerm->nChild = 2;
89042     }
89043   }
89044 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
89045
89046 #ifndef SQLITE_OMIT_VIRTUALTABLE
89047   /* Add a WO_MATCH auxiliary term to the constraint set if the
89048   ** current expression is of the form:  column MATCH expr.
89049   ** This information is used by the xBestIndex methods of
89050   ** virtual tables.  The native query optimizer does not attempt
89051   ** to do anything with MATCH functions.
89052   */
89053   if( isMatchOfColumn(pExpr) ){
89054     int idxNew;
89055     Expr *pRight, *pLeft;
89056     WhereTerm *pNewTerm;
89057     Bitmask prereqColumn, prereqExpr;
89058
89059     pRight = pExpr->x.pList->a[0].pExpr;
89060     pLeft = pExpr->x.pList->a[1].pExpr;
89061     prereqExpr = exprTableUsage(pMaskSet, pRight);
89062     prereqColumn = exprTableUsage(pMaskSet, pLeft);
89063     if( (prereqExpr & prereqColumn)==0 ){
89064       Expr *pNewExpr;
89065       pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 
89066                               0, sqlite3ExprDup(db, pRight, 0), 0);
89067       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
89068       testcase( idxNew==0 );
89069       pNewTerm = &pWC->a[idxNew];
89070       pNewTerm->prereqRight = prereqExpr;
89071       pNewTerm->leftCursor = pLeft->iTable;
89072       pNewTerm->u.leftColumn = pLeft->iColumn;
89073       pNewTerm->eOperator = WO_MATCH;
89074       pNewTerm->iParent = idxTerm;
89075       pTerm = &pWC->a[idxTerm];
89076       pTerm->nChild = 1;
89077       pTerm->wtFlags |= TERM_COPIED;
89078       pNewTerm->prereqAll = pTerm->prereqAll;
89079     }
89080   }
89081 #endif /* SQLITE_OMIT_VIRTUALTABLE */
89082
89083   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
89084   ** an index for tables to the left of the join.
89085   */
89086   pTerm->prereqRight |= extraRight;
89087 }
89088
89089 /*
89090 ** Return TRUE if any of the expressions in pList->a[iFirst...] contain
89091 ** a reference to any table other than the iBase table.
89092 */
89093 static int referencesOtherTables(
89094   ExprList *pList,          /* Search expressions in ths list */
89095   WhereMaskSet *pMaskSet,   /* Mapping from tables to bitmaps */
89096   int iFirst,               /* Be searching with the iFirst-th expression */
89097   int iBase                 /* Ignore references to this table */
89098 ){
89099   Bitmask allowed = ~getMask(pMaskSet, iBase);
89100   while( iFirst<pList->nExpr ){
89101     if( (exprTableUsage(pMaskSet, pList->a[iFirst++].pExpr)&allowed)!=0 ){
89102       return 1;
89103     }
89104   }
89105   return 0;
89106 }
89107
89108
89109 /*
89110 ** This routine decides if pIdx can be used to satisfy the ORDER BY
89111 ** clause.  If it can, it returns 1.  If pIdx cannot satisfy the
89112 ** ORDER BY clause, this routine returns 0.
89113 **
89114 ** pOrderBy is an ORDER BY clause from a SELECT statement.  pTab is the
89115 ** left-most table in the FROM clause of that same SELECT statement and
89116 ** the table has a cursor number of "base".  pIdx is an index on pTab.
89117 **
89118 ** nEqCol is the number of columns of pIdx that are used as equality
89119 ** constraints.  Any of these columns may be missing from the ORDER BY
89120 ** clause and the match can still be a success.
89121 **
89122 ** All terms of the ORDER BY that match against the index must be either
89123 ** ASC or DESC.  (Terms of the ORDER BY clause past the end of a UNIQUE
89124 ** index do not need to satisfy this constraint.)  The *pbRev value is
89125 ** set to 1 if the ORDER BY clause is all DESC and it is set to 0 if
89126 ** the ORDER BY clause is all ASC.
89127 */
89128 static int isSortingIndex(
89129   Parse *pParse,          /* Parsing context */
89130   WhereMaskSet *pMaskSet, /* Mapping from table cursor numbers to bitmaps */
89131   Index *pIdx,            /* The index we are testing */
89132   int base,               /* Cursor number for the table to be sorted */
89133   ExprList *pOrderBy,     /* The ORDER BY clause */
89134   int nEqCol,             /* Number of index columns with == constraints */
89135   int *pbRev              /* Set to 1 if ORDER BY is DESC */
89136 ){
89137   int i, j;                       /* Loop counters */
89138   int sortOrder = 0;              /* XOR of index and ORDER BY sort direction */
89139   int nTerm;                      /* Number of ORDER BY terms */
89140   struct ExprList_item *pTerm;    /* A term of the ORDER BY clause */
89141   sqlite3 *db = pParse->db;
89142
89143   assert( pOrderBy!=0 );
89144   nTerm = pOrderBy->nExpr;
89145   assert( nTerm>0 );
89146
89147   /* Argument pIdx must either point to a 'real' named index structure, 
89148   ** or an index structure allocated on the stack by bestBtreeIndex() to
89149   ** represent the rowid index that is part of every table.  */
89150   assert( pIdx->zName || (pIdx->nColumn==1 && pIdx->aiColumn[0]==-1) );
89151
89152   /* Match terms of the ORDER BY clause against columns of
89153   ** the index.
89154   **
89155   ** Note that indices have pIdx->nColumn regular columns plus
89156   ** one additional column containing the rowid.  The rowid column
89157   ** of the index is also allowed to match against the ORDER BY
89158   ** clause.
89159   */
89160   for(i=j=0, pTerm=pOrderBy->a; j<nTerm && i<=pIdx->nColumn; i++){
89161     Expr *pExpr;       /* The expression of the ORDER BY pTerm */
89162     CollSeq *pColl;    /* The collating sequence of pExpr */
89163     int termSortOrder; /* Sort order for this term */
89164     int iColumn;       /* The i-th column of the index.  -1 for rowid */
89165     int iSortOrder;    /* 1 for DESC, 0 for ASC on the i-th index term */
89166     const char *zColl; /* Name of the collating sequence for i-th index term */
89167
89168     pExpr = pTerm->pExpr;
89169     if( pExpr->op!=TK_COLUMN || pExpr->iTable!=base ){
89170       /* Can not use an index sort on anything that is not a column in the
89171       ** left-most table of the FROM clause */
89172       break;
89173     }
89174     pColl = sqlite3ExprCollSeq(pParse, pExpr);
89175     if( !pColl ){
89176       pColl = db->pDfltColl;
89177     }
89178     if( pIdx->zName && i<pIdx->nColumn ){
89179       iColumn = pIdx->aiColumn[i];
89180       if( iColumn==pIdx->pTable->iPKey ){
89181         iColumn = -1;
89182       }
89183       iSortOrder = pIdx->aSortOrder[i];
89184       zColl = pIdx->azColl[i];
89185     }else{
89186       iColumn = -1;
89187       iSortOrder = 0;
89188       zColl = pColl->zName;
89189     }
89190     if( pExpr->iColumn!=iColumn || sqlite3StrICmp(pColl->zName, zColl) ){
89191       /* Term j of the ORDER BY clause does not match column i of the index */
89192       if( i<nEqCol ){
89193         /* If an index column that is constrained by == fails to match an
89194         ** ORDER BY term, that is OK.  Just ignore that column of the index
89195         */
89196         continue;
89197       }else if( i==pIdx->nColumn ){
89198         /* Index column i is the rowid.  All other terms match. */
89199         break;
89200       }else{
89201         /* If an index column fails to match and is not constrained by ==
89202         ** then the index cannot satisfy the ORDER BY constraint.
89203         */
89204         return 0;
89205       }
89206     }
89207     assert( pIdx->aSortOrder!=0 || iColumn==-1 );
89208     assert( pTerm->sortOrder==0 || pTerm->sortOrder==1 );
89209     assert( iSortOrder==0 || iSortOrder==1 );
89210     termSortOrder = iSortOrder ^ pTerm->sortOrder;
89211     if( i>nEqCol ){
89212       if( termSortOrder!=sortOrder ){
89213         /* Indices can only be used if all ORDER BY terms past the
89214         ** equality constraints are all either DESC or ASC. */
89215         return 0;
89216       }
89217     }else{
89218       sortOrder = termSortOrder;
89219     }
89220     j++;
89221     pTerm++;
89222     if( iColumn<0 && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
89223       /* If the indexed column is the primary key and everything matches
89224       ** so far and none of the ORDER BY terms to the right reference other
89225       ** tables in the join, then we are assured that the index can be used 
89226       ** to sort because the primary key is unique and so none of the other
89227       ** columns will make any difference
89228       */
89229       j = nTerm;
89230     }
89231   }
89232
89233   *pbRev = sortOrder!=0;
89234   if( j>=nTerm ){
89235     /* All terms of the ORDER BY clause are covered by this index so
89236     ** this index can be used for sorting. */
89237     return 1;
89238   }
89239   if( pIdx->onError!=OE_None && i==pIdx->nColumn
89240       && !referencesOtherTables(pOrderBy, pMaskSet, j, base) ){
89241     /* All terms of this index match some prefix of the ORDER BY clause
89242     ** and the index is UNIQUE and no terms on the tail of the ORDER BY
89243     ** clause reference other tables in a join.  If this is all true then
89244     ** the order by clause is superfluous. */
89245     return 1;
89246   }
89247   return 0;
89248 }
89249
89250 /*
89251 ** Prepare a crude estimate of the logarithm of the input value.
89252 ** The results need not be exact.  This is only used for estimating
89253 ** the total cost of performing operations with O(logN) or O(NlogN)
89254 ** complexity.  Because N is just a guess, it is no great tragedy if
89255 ** logN is a little off.
89256 */
89257 static double estLog(double N){
89258   double logN = 1;
89259   double x = 10;
89260   while( N>x ){
89261     logN += 1;
89262     x *= 10;
89263   }
89264   return logN;
89265 }
89266
89267 /*
89268 ** Two routines for printing the content of an sqlite3_index_info
89269 ** structure.  Used for testing and debugging only.  If neither
89270 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
89271 ** are no-ops.
89272 */
89273 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(SQLITE_DEBUG)
89274 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
89275   int i;
89276   if( !sqlite3WhereTrace ) return;
89277   for(i=0; i<p->nConstraint; i++){
89278     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
89279        i,
89280        p->aConstraint[i].iColumn,
89281        p->aConstraint[i].iTermOffset,
89282        p->aConstraint[i].op,
89283        p->aConstraint[i].usable);
89284   }
89285   for(i=0; i<p->nOrderBy; i++){
89286     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
89287        i,
89288        p->aOrderBy[i].iColumn,
89289        p->aOrderBy[i].desc);
89290   }
89291 }
89292 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
89293   int i;
89294   if( !sqlite3WhereTrace ) return;
89295   for(i=0; i<p->nConstraint; i++){
89296     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
89297        i,
89298        p->aConstraintUsage[i].argvIndex,
89299        p->aConstraintUsage[i].omit);
89300   }
89301   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
89302   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
89303   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
89304   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
89305 }
89306 #else
89307 #define TRACE_IDX_INPUTS(A)
89308 #define TRACE_IDX_OUTPUTS(A)
89309 #endif
89310
89311 /* 
89312 ** Required because bestIndex() is called by bestOrClauseIndex() 
89313 */
89314 static void bestIndex(
89315     Parse*, WhereClause*, struct SrcList_item*, Bitmask, ExprList*, WhereCost*);
89316
89317 /*
89318 ** This routine attempts to find an scanning strategy that can be used 
89319 ** to optimize an 'OR' expression that is part of a WHERE clause. 
89320 **
89321 ** The table associated with FROM clause term pSrc may be either a
89322 ** regular B-Tree table or a virtual table.
89323 */
89324 static void bestOrClauseIndex(
89325   Parse *pParse,              /* The parsing context */
89326   WhereClause *pWC,           /* The WHERE clause */
89327   struct SrcList_item *pSrc,  /* The FROM clause term to search */
89328   Bitmask notReady,           /* Mask of cursors that are not available */
89329   ExprList *pOrderBy,         /* The ORDER BY clause */
89330   WhereCost *pCost            /* Lowest cost query plan */
89331 ){
89332 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
89333   const int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
89334   const Bitmask maskSrc = getMask(pWC->pMaskSet, iCur);  /* Bitmask for pSrc */
89335   WhereTerm * const pWCEnd = &pWC->a[pWC->nTerm];        /* End of pWC->a[] */
89336   WhereTerm *pTerm;                 /* A single term of the WHERE clause */
89337
89338   /* Search the WHERE clause terms for a usable WO_OR term. */
89339   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
89340     if( pTerm->eOperator==WO_OR 
89341      && ((pTerm->prereqAll & ~maskSrc) & notReady)==0
89342      && (pTerm->u.pOrInfo->indexable & maskSrc)!=0 
89343     ){
89344       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
89345       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
89346       WhereTerm *pOrTerm;
89347       int flags = WHERE_MULTI_OR;
89348       double rTotal = 0;
89349       double nRow = 0;
89350       Bitmask used = 0;
89351
89352       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
89353         WhereCost sTermCost;
89354         WHERETRACE(("... Multi-index OR testing for term %d of %d....\n", 
89355           (pOrTerm - pOrWC->a), (pTerm - pWC->a)
89356         ));
89357         if( pOrTerm->eOperator==WO_AND ){
89358           WhereClause *pAndWC = &pOrTerm->u.pAndInfo->wc;
89359           bestIndex(pParse, pAndWC, pSrc, notReady, 0, &sTermCost);
89360         }else if( pOrTerm->leftCursor==iCur ){
89361           WhereClause tempWC;
89362           tempWC.pParse = pWC->pParse;
89363           tempWC.pMaskSet = pWC->pMaskSet;
89364           tempWC.op = TK_AND;
89365           tempWC.a = pOrTerm;
89366           tempWC.nTerm = 1;
89367           bestIndex(pParse, &tempWC, pSrc, notReady, 0, &sTermCost);
89368         }else{
89369           continue;
89370         }
89371         rTotal += sTermCost.rCost;
89372         nRow += sTermCost.nRow;
89373         used |= sTermCost.used;
89374         if( rTotal>=pCost->rCost ) break;
89375       }
89376
89377       /* If there is an ORDER BY clause, increase the scan cost to account 
89378       ** for the cost of the sort. */
89379       if( pOrderBy!=0 ){
89380         rTotal += nRow*estLog(nRow);
89381         WHERETRACE(("... sorting increases OR cost to %.9g\n", rTotal));
89382       }
89383
89384       /* If the cost of scanning using this OR term for optimization is
89385       ** less than the current cost stored in pCost, replace the contents
89386       ** of pCost. */
89387       WHERETRACE(("... multi-index OR cost=%.9g nrow=%.9g\n", rTotal, nRow));
89388       if( rTotal<pCost->rCost ){
89389         pCost->rCost = rTotal;
89390         pCost->nRow = nRow;
89391         pCost->used = used;
89392         pCost->plan.wsFlags = flags;
89393         pCost->plan.u.pTerm = pTerm;
89394       }
89395     }
89396   }
89397 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
89398 }
89399
89400 #ifndef SQLITE_OMIT_VIRTUALTABLE
89401 /*
89402 ** Allocate and populate an sqlite3_index_info structure. It is the 
89403 ** responsibility of the caller to eventually release the structure
89404 ** by passing the pointer returned by this function to sqlite3_free().
89405 */
89406 static sqlite3_index_info *allocateIndexInfo(
89407   Parse *pParse, 
89408   WhereClause *pWC,
89409   struct SrcList_item *pSrc,
89410   ExprList *pOrderBy
89411 ){
89412   int i, j;
89413   int nTerm;
89414   struct sqlite3_index_constraint *pIdxCons;
89415   struct sqlite3_index_orderby *pIdxOrderBy;
89416   struct sqlite3_index_constraint_usage *pUsage;
89417   WhereTerm *pTerm;
89418   int nOrderBy;
89419   sqlite3_index_info *pIdxInfo;
89420
89421   WHERETRACE(("Recomputing index info for %s...\n", pSrc->pTab->zName));
89422
89423   /* Count the number of possible WHERE clause constraints referring
89424   ** to this virtual table */
89425   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
89426     if( pTerm->leftCursor != pSrc->iCursor ) continue;
89427     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
89428     testcase( pTerm->eOperator==WO_IN );
89429     testcase( pTerm->eOperator==WO_ISNULL );
89430     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
89431     nTerm++;
89432   }
89433
89434   /* If the ORDER BY clause contains only columns in the current 
89435   ** virtual table then allocate space for the aOrderBy part of
89436   ** the sqlite3_index_info structure.
89437   */
89438   nOrderBy = 0;
89439   if( pOrderBy ){
89440     for(i=0; i<pOrderBy->nExpr; i++){
89441       Expr *pExpr = pOrderBy->a[i].pExpr;
89442       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
89443     }
89444     if( i==pOrderBy->nExpr ){
89445       nOrderBy = pOrderBy->nExpr;
89446     }
89447   }
89448
89449   /* Allocate the sqlite3_index_info structure
89450   */
89451   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
89452                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
89453                            + sizeof(*pIdxOrderBy)*nOrderBy );
89454   if( pIdxInfo==0 ){
89455     sqlite3ErrorMsg(pParse, "out of memory");
89456     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
89457     return 0;
89458   }
89459
89460   /* Initialize the structure.  The sqlite3_index_info structure contains
89461   ** many fields that are declared "const" to prevent xBestIndex from
89462   ** changing them.  We have to do some funky casting in order to
89463   ** initialize those fields.
89464   */
89465   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
89466   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
89467   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
89468   *(int*)&pIdxInfo->nConstraint = nTerm;
89469   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
89470   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
89471   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
89472   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
89473                                                                    pUsage;
89474
89475   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
89476     if( pTerm->leftCursor != pSrc->iCursor ) continue;
89477     assert( (pTerm->eOperator&(pTerm->eOperator-1))==0 );
89478     testcase( pTerm->eOperator==WO_IN );
89479     testcase( pTerm->eOperator==WO_ISNULL );
89480     if( pTerm->eOperator & (WO_IN|WO_ISNULL) ) continue;
89481     pIdxCons[j].iColumn = pTerm->u.leftColumn;
89482     pIdxCons[j].iTermOffset = i;
89483     pIdxCons[j].op = (u8)pTerm->eOperator;
89484     /* The direct assignment in the previous line is possible only because
89485     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
89486     ** following asserts verify this fact. */
89487     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
89488     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
89489     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
89490     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
89491     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
89492     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
89493     assert( pTerm->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
89494     j++;
89495   }
89496   for(i=0; i<nOrderBy; i++){
89497     Expr *pExpr = pOrderBy->a[i].pExpr;
89498     pIdxOrderBy[i].iColumn = pExpr->iColumn;
89499     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
89500   }
89501
89502   return pIdxInfo;
89503 }
89504
89505 /*
89506 ** The table object reference passed as the second argument to this function
89507 ** must represent a virtual table. This function invokes the xBestIndex()
89508 ** method of the virtual table with the sqlite3_index_info pointer passed
89509 ** as the argument.
89510 **
89511 ** If an error occurs, pParse is populated with an error message and a
89512 ** non-zero value is returned. Otherwise, 0 is returned and the output
89513 ** part of the sqlite3_index_info structure is left populated.
89514 **
89515 ** Whether or not an error is returned, it is the responsibility of the
89516 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
89517 ** that this is required.
89518 */
89519 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
89520   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
89521   int i;
89522   int rc;
89523
89524   WHERETRACE(("xBestIndex for %s\n", pTab->zName));
89525   TRACE_IDX_INPUTS(p);
89526   rc = pVtab->pModule->xBestIndex(pVtab, p);
89527   TRACE_IDX_OUTPUTS(p);
89528
89529   if( rc!=SQLITE_OK ){
89530     if( rc==SQLITE_NOMEM ){
89531       pParse->db->mallocFailed = 1;
89532     }else if( !pVtab->zErrMsg ){
89533       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
89534     }else{
89535       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
89536     }
89537   }
89538   sqlite3DbFree(pParse->db, pVtab->zErrMsg);
89539   pVtab->zErrMsg = 0;
89540
89541   for(i=0; i<p->nConstraint; i++){
89542     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
89543       sqlite3ErrorMsg(pParse, 
89544           "table %s: xBestIndex returned an invalid plan", pTab->zName);
89545     }
89546   }
89547
89548   return pParse->nErr;
89549 }
89550
89551
89552 /*
89553 ** Compute the best index for a virtual table.
89554 **
89555 ** The best index is computed by the xBestIndex method of the virtual
89556 ** table module.  This routine is really just a wrapper that sets up
89557 ** the sqlite3_index_info structure that is used to communicate with
89558 ** xBestIndex.
89559 **
89560 ** In a join, this routine might be called multiple times for the
89561 ** same virtual table.  The sqlite3_index_info structure is created
89562 ** and initialized on the first invocation and reused on all subsequent
89563 ** invocations.  The sqlite3_index_info structure is also used when
89564 ** code is generated to access the virtual table.  The whereInfoDelete() 
89565 ** routine takes care of freeing the sqlite3_index_info structure after
89566 ** everybody has finished with it.
89567 */
89568 static void bestVirtualIndex(
89569   Parse *pParse,                  /* The parsing context */
89570   WhereClause *pWC,               /* The WHERE clause */
89571   struct SrcList_item *pSrc,      /* The FROM clause term to search */
89572   Bitmask notReady,               /* Mask of cursors that are not available */
89573   ExprList *pOrderBy,             /* The order by clause */
89574   WhereCost *pCost,               /* Lowest cost query plan */
89575   sqlite3_index_info **ppIdxInfo  /* Index information passed to xBestIndex */
89576 ){
89577   Table *pTab = pSrc->pTab;
89578   sqlite3_index_info *pIdxInfo;
89579   struct sqlite3_index_constraint *pIdxCons;
89580   struct sqlite3_index_constraint_usage *pUsage;
89581   WhereTerm *pTerm;
89582   int i, j;
89583   int nOrderBy;
89584
89585   /* Make sure wsFlags is initialized to some sane value. Otherwise, if the 
89586   ** malloc in allocateIndexInfo() fails and this function returns leaving
89587   ** wsFlags in an uninitialized state, the caller may behave unpredictably.
89588   */
89589   memset(pCost, 0, sizeof(*pCost));
89590   pCost->plan.wsFlags = WHERE_VIRTUALTABLE;
89591
89592   /* If the sqlite3_index_info structure has not been previously
89593   ** allocated and initialized, then allocate and initialize it now.
89594   */
89595   pIdxInfo = *ppIdxInfo;
89596   if( pIdxInfo==0 ){
89597     *ppIdxInfo = pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pOrderBy);
89598   }
89599   if( pIdxInfo==0 ){
89600     return;
89601   }
89602
89603   /* At this point, the sqlite3_index_info structure that pIdxInfo points
89604   ** to will have been initialized, either during the current invocation or
89605   ** during some prior invocation.  Now we just have to customize the
89606   ** details of pIdxInfo for the current invocation and pass it to
89607   ** xBestIndex.
89608   */
89609
89610   /* The module name must be defined. Also, by this point there must
89611   ** be a pointer to an sqlite3_vtab structure. Otherwise
89612   ** sqlite3ViewGetColumnNames() would have picked up the error. 
89613   */
89614   assert( pTab->azModuleArg && pTab->azModuleArg[0] );
89615   assert( sqlite3GetVTable(pParse->db, pTab) );
89616
89617   /* Set the aConstraint[].usable fields and initialize all 
89618   ** output variables to zero.
89619   **
89620   ** aConstraint[].usable is true for constraints where the right-hand
89621   ** side contains only references to tables to the left of the current
89622   ** table.  In other words, if the constraint is of the form:
89623   **
89624   **           column = expr
89625   **
89626   ** and we are evaluating a join, then the constraint on column is 
89627   ** only valid if all tables referenced in expr occur to the left
89628   ** of the table containing column.
89629   **
89630   ** The aConstraints[] array contains entries for all constraints
89631   ** on the current table.  That way we only have to compute it once
89632   ** even though we might try to pick the best index multiple times.
89633   ** For each attempt at picking an index, the order of tables in the
89634   ** join might be different so we have to recompute the usable flag
89635   ** each time.
89636   */
89637   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
89638   pUsage = pIdxInfo->aConstraintUsage;
89639   for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
89640     j = pIdxCons->iTermOffset;
89641     pTerm = &pWC->a[j];
89642     pIdxCons->usable = (pTerm->prereqRight&notReady) ? 0 : 1;
89643   }
89644   memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
89645   if( pIdxInfo->needToFreeIdxStr ){
89646     sqlite3_free(pIdxInfo->idxStr);
89647   }
89648   pIdxInfo->idxStr = 0;
89649   pIdxInfo->idxNum = 0;
89650   pIdxInfo->needToFreeIdxStr = 0;
89651   pIdxInfo->orderByConsumed = 0;
89652   /* ((double)2) In case of SQLITE_OMIT_FLOATING_POINT... */
89653   pIdxInfo->estimatedCost = SQLITE_BIG_DBL / ((double)2);
89654   nOrderBy = pIdxInfo->nOrderBy;
89655   if( !pOrderBy ){
89656     pIdxInfo->nOrderBy = 0;
89657   }
89658
89659   if( vtabBestIndex(pParse, pTab, pIdxInfo) ){
89660     return;
89661   }
89662
89663   pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
89664   for(i=0; i<pIdxInfo->nConstraint; i++){
89665     if( pUsage[i].argvIndex>0 ){
89666       pCost->used |= pWC->a[pIdxCons[i].iTermOffset].prereqRight;
89667     }
89668   }
89669
89670   /* The cost is not allowed to be larger than SQLITE_BIG_DBL (the
89671   ** inital value of lowestCost in this loop. If it is, then the
89672   ** (cost<lowestCost) test below will never be true.
89673   ** 
89674   ** Use "(double)2" instead of "2.0" in case OMIT_FLOATING_POINT 
89675   ** is defined.
89676   */
89677   if( (SQLITE_BIG_DBL/((double)2))<pIdxInfo->estimatedCost ){
89678     pCost->rCost = (SQLITE_BIG_DBL/((double)2));
89679   }else{
89680     pCost->rCost = pIdxInfo->estimatedCost;
89681   }
89682   pCost->plan.u.pVtabIdx = pIdxInfo;
89683   if( pIdxInfo->orderByConsumed ){
89684     pCost->plan.wsFlags |= WHERE_ORDERBY;
89685   }
89686   pCost->plan.nEq = 0;
89687   pIdxInfo->nOrderBy = nOrderBy;
89688
89689   /* Try to find a more efficient access pattern by using multiple indexes
89690   ** to optimize an OR expression within the WHERE clause. 
89691   */
89692   bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
89693 }
89694 #endif /* SQLITE_OMIT_VIRTUALTABLE */
89695
89696 /*
89697 ** Argument pIdx is a pointer to an index structure that has an array of
89698 ** SQLITE_INDEX_SAMPLES evenly spaced samples of the first indexed column
89699 ** stored in Index.aSample. The domain of values stored in said column
89700 ** may be thought of as divided into (SQLITE_INDEX_SAMPLES+1) regions.
89701 ** Region 0 contains all values smaller than the first sample value. Region
89702 ** 1 contains values larger than or equal to the value of the first sample,
89703 ** but smaller than the value of the second. And so on.
89704 **
89705 ** If successful, this function determines which of the regions value 
89706 ** pVal lies in, sets *piRegion to the region index (a value between 0
89707 ** and SQLITE_INDEX_SAMPLES+1, inclusive) and returns SQLITE_OK.
89708 ** Or, if an OOM occurs while converting text values between encodings,
89709 ** SQLITE_NOMEM is returned and *piRegion is undefined.
89710 */
89711 #ifdef SQLITE_ENABLE_STAT2
89712 static int whereRangeRegion(
89713   Parse *pParse,              /* Database connection */
89714   Index *pIdx,                /* Index to consider domain of */
89715   sqlite3_value *pVal,        /* Value to consider */
89716   int *piRegion               /* OUT: Region of domain in which value lies */
89717 ){
89718   if( ALWAYS(pVal) ){
89719     IndexSample *aSample = pIdx->aSample;
89720     int i = 0;
89721     int eType = sqlite3_value_type(pVal);
89722
89723     if( eType==SQLITE_INTEGER || eType==SQLITE_FLOAT ){
89724       double r = sqlite3_value_double(pVal);
89725       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
89726         if( aSample[i].eType==SQLITE_NULL ) continue;
89727         if( aSample[i].eType>=SQLITE_TEXT || aSample[i].u.r>r ) break;
89728       }
89729     }else{ 
89730       sqlite3 *db = pParse->db;
89731       CollSeq *pColl;
89732       const u8 *z;
89733       int n;
89734
89735       /* pVal comes from sqlite3ValueFromExpr() so the type cannot be NULL */
89736       assert( eType==SQLITE_TEXT || eType==SQLITE_BLOB );
89737
89738       if( eType==SQLITE_BLOB ){
89739         z = (const u8 *)sqlite3_value_blob(pVal);
89740         pColl = db->pDfltColl;
89741         assert( pColl->enc==SQLITE_UTF8 );
89742       }else{
89743         pColl = sqlite3GetCollSeq(db, SQLITE_UTF8, 0, *pIdx->azColl);
89744         if( pColl==0 ){
89745           sqlite3ErrorMsg(pParse, "no such collation sequence: %s",
89746                           *pIdx->azColl);
89747           return SQLITE_ERROR;
89748         }
89749         z = (const u8 *)sqlite3ValueText(pVal, pColl->enc);
89750         if( !z ){
89751           return SQLITE_NOMEM;
89752         }
89753         assert( z && pColl && pColl->xCmp );
89754       }
89755       n = sqlite3ValueBytes(pVal, pColl->enc);
89756
89757       for(i=0; i<SQLITE_INDEX_SAMPLES; i++){
89758         int r;
89759         int eSampletype = aSample[i].eType;
89760         if( eSampletype==SQLITE_NULL || eSampletype<eType ) continue;
89761         if( (eSampletype!=eType) ) break;
89762 #ifndef SQLITE_OMIT_UTF16
89763         if( pColl->enc!=SQLITE_UTF8 ){
89764           int nSample;
89765           char *zSample = sqlite3Utf8to16(
89766               db, pColl->enc, aSample[i].u.z, aSample[i].nByte, &nSample
89767           );
89768           if( !zSample ){
89769             assert( db->mallocFailed );
89770             return SQLITE_NOMEM;
89771           }
89772           r = pColl->xCmp(pColl->pUser, nSample, zSample, n, z);
89773           sqlite3DbFree(db, zSample);
89774         }else
89775 #endif
89776         {
89777           r = pColl->xCmp(pColl->pUser, aSample[i].nByte, aSample[i].u.z, n, z);
89778         }
89779         if( r>0 ) break;
89780       }
89781     }
89782
89783     assert( i>=0 && i<=SQLITE_INDEX_SAMPLES );
89784     *piRegion = i;
89785   }
89786   return SQLITE_OK;
89787 }
89788 #endif   /* #ifdef SQLITE_ENABLE_STAT2 */
89789
89790 /*
89791 ** If expression pExpr represents a literal value, set *pp to point to
89792 ** an sqlite3_value structure containing the same value, with affinity
89793 ** aff applied to it, before returning. It is the responsibility of the 
89794 ** caller to eventually release this structure by passing it to 
89795 ** sqlite3ValueFree().
89796 **
89797 ** If the current parse is a recompile (sqlite3Reprepare()) and pExpr
89798 ** is an SQL variable that currently has a non-NULL value bound to it,
89799 ** create an sqlite3_value structure containing this value, again with
89800 ** affinity aff applied to it, instead.
89801 **
89802 ** If neither of the above apply, set *pp to NULL.
89803 **
89804 ** If an error occurs, return an error code. Otherwise, SQLITE_OK.
89805 */
89806 #ifdef SQLITE_ENABLE_STAT2
89807 static int valueFromExpr(
89808   Parse *pParse, 
89809   Expr *pExpr, 
89810   u8 aff, 
89811   sqlite3_value **pp
89812 ){
89813   /* The evalConstExpr() function will have already converted any TK_VARIABLE
89814   ** expression involved in an comparison into a TK_REGISTER. */
89815   assert( pExpr->op!=TK_VARIABLE );
89816   if( pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE ){
89817     int iVar = pExpr->iColumn;
89818     sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
89819     *pp = sqlite3VdbeGetValue(pParse->pReprepare, iVar, aff);
89820     return SQLITE_OK;
89821   }
89822   return sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, aff, pp);
89823 }
89824 #endif
89825
89826 /*
89827 ** This function is used to estimate the number of rows that will be visited
89828 ** by scanning an index for a range of values. The range may have an upper
89829 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
89830 ** and lower bounds are represented by pLower and pUpper respectively. For
89831 ** example, assuming that index p is on t1(a):
89832 **
89833 **   ... FROM t1 WHERE a > ? AND a < ? ...
89834 **                    |_____|   |_____|
89835 **                       |         |
89836 **                     pLower    pUpper
89837 **
89838 ** If either of the upper or lower bound is not present, then NULL is passed in
89839 ** place of the corresponding WhereTerm.
89840 **
89841 ** The nEq parameter is passed the index of the index column subject to the
89842 ** range constraint. Or, equivalently, the number of equality constraints
89843 ** optimized by the proposed index scan. For example, assuming index p is
89844 ** on t1(a, b), and the SQL query is:
89845 **
89846 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
89847 **
89848 ** then nEq should be passed the value 1 (as the range restricted column,
89849 ** b, is the second left-most column of the index). Or, if the query is:
89850 **
89851 **   ... FROM t1 WHERE a > ? AND a < ? ...
89852 **
89853 ** then nEq should be passed 0.
89854 **
89855 ** The returned value is an integer between 1 and 100, inclusive. A return
89856 ** value of 1 indicates that the proposed range scan is expected to visit
89857 ** approximately 1/100th (1%) of the rows selected by the nEq equality
89858 ** constraints (if any). A return value of 100 indicates that it is expected
89859 ** that the range scan will visit every row (100%) selected by the equality
89860 ** constraints.
89861 **
89862 ** In the absence of sqlite_stat2 ANALYZE data, each range inequality
89863 ** reduces the search space by 2/3rds.  Hence a single constraint (x>?)
89864 ** results in a return of 33 and a range constraint (x>? AND x<?) results
89865 ** in a return of 11.
89866 */
89867 static int whereRangeScanEst(
89868   Parse *pParse,       /* Parsing & code generating context */
89869   Index *p,            /* The index containing the range-compared column; "x" */
89870   int nEq,             /* index into p->aCol[] of the range-compared column */
89871   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
89872   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
89873   int *piEst           /* OUT: Return value */
89874 ){
89875   int rc = SQLITE_OK;
89876
89877 #ifdef SQLITE_ENABLE_STAT2
89878
89879   if( nEq==0 && p->aSample ){
89880     sqlite3_value *pLowerVal = 0;
89881     sqlite3_value *pUpperVal = 0;
89882     int iEst;
89883     int iLower = 0;
89884     int iUpper = SQLITE_INDEX_SAMPLES;
89885     u8 aff = p->pTable->aCol[p->aiColumn[0]].affinity;
89886
89887     if( pLower ){
89888       Expr *pExpr = pLower->pExpr->pRight;
89889       rc = valueFromExpr(pParse, pExpr, aff, &pLowerVal);
89890     }
89891     if( rc==SQLITE_OK && pUpper ){
89892       Expr *pExpr = pUpper->pExpr->pRight;
89893       rc = valueFromExpr(pParse, pExpr, aff, &pUpperVal);
89894     }
89895
89896     if( rc!=SQLITE_OK || (pLowerVal==0 && pUpperVal==0) ){
89897       sqlite3ValueFree(pLowerVal);
89898       sqlite3ValueFree(pUpperVal);
89899       goto range_est_fallback;
89900     }else if( pLowerVal==0 ){
89901       rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
89902       if( pLower ) iLower = iUpper/2;
89903     }else if( pUpperVal==0 ){
89904       rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
89905       if( pUpper ) iUpper = (iLower + SQLITE_INDEX_SAMPLES + 1)/2;
89906     }else{
89907       rc = whereRangeRegion(pParse, p, pUpperVal, &iUpper);
89908       if( rc==SQLITE_OK ){
89909         rc = whereRangeRegion(pParse, p, pLowerVal, &iLower);
89910       }
89911     }
89912
89913     iEst = iUpper - iLower;
89914     testcase( iEst==SQLITE_INDEX_SAMPLES );
89915     assert( iEst<=SQLITE_INDEX_SAMPLES );
89916     if( iEst<1 ){
89917       iEst = 1;
89918     }
89919
89920     sqlite3ValueFree(pLowerVal);
89921     sqlite3ValueFree(pUpperVal);
89922     *piEst = (iEst * 100)/SQLITE_INDEX_SAMPLES;
89923     return rc;
89924   }
89925 range_est_fallback:
89926 #else
89927   UNUSED_PARAMETER(pParse);
89928   UNUSED_PARAMETER(p);
89929   UNUSED_PARAMETER(nEq);
89930 #endif
89931   assert( pLower || pUpper );
89932   if( pLower && pUpper ){
89933     *piEst = 11;
89934   }else{
89935     *piEst = 33;
89936   }
89937   return rc;
89938 }
89939
89940
89941 /*
89942 ** Find the query plan for accessing a particular table.  Write the
89943 ** best query plan and its cost into the WhereCost object supplied as the
89944 ** last parameter.
89945 **
89946 ** The lowest cost plan wins.  The cost is an estimate of the amount of
89947 ** CPU and disk I/O need to process the request using the selected plan.
89948 ** Factors that influence cost include:
89949 **
89950 **    *  The estimated number of rows that will be retrieved.  (The
89951 **       fewer the better.)
89952 **
89953 **    *  Whether or not sorting must occur.
89954 **
89955 **    *  Whether or not there must be separate lookups in the
89956 **       index and in the main table.
89957 **
89958 ** If there was an INDEXED BY clause (pSrc->pIndex) attached to the table in
89959 ** the SQL statement, then this function only considers plans using the 
89960 ** named index. If no such plan is found, then the returned cost is
89961 ** SQLITE_BIG_DBL. If a plan is found that uses the named index, 
89962 ** then the cost is calculated in the usual way.
89963 **
89964 ** If a NOT INDEXED clause (pSrc->notIndexed!=0) was attached to the table 
89965 ** in the SELECT statement, then no indexes are considered. However, the 
89966 ** selected plan may still take advantage of the tables built-in rowid
89967 ** index.
89968 */
89969 static void bestBtreeIndex(
89970   Parse *pParse,              /* The parsing context */
89971   WhereClause *pWC,           /* The WHERE clause */
89972   struct SrcList_item *pSrc,  /* The FROM clause term to search */
89973   Bitmask notReady,           /* Mask of cursors that are not available */
89974   ExprList *pOrderBy,         /* The ORDER BY clause */
89975   WhereCost *pCost            /* Lowest cost query plan */
89976 ){
89977   int iCur = pSrc->iCursor;   /* The cursor of the table to be accessed */
89978   Index *pProbe;              /* An index we are evaluating */
89979   Index *pIdx;                /* Copy of pProbe, or zero for IPK index */
89980   int eqTermMask;             /* Current mask of valid equality operators */
89981   int idxEqTermMask;          /* Index mask of valid equality operators */
89982   Index sPk;                  /* A fake index object for the primary key */
89983   unsigned int aiRowEstPk[2]; /* The aiRowEst[] value for the sPk index */
89984   int aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
89985   int wsFlagMask;             /* Allowed flags in pCost->plan.wsFlag */
89986
89987   /* Initialize the cost to a worst-case value */
89988   memset(pCost, 0, sizeof(*pCost));
89989   pCost->rCost = SQLITE_BIG_DBL;
89990
89991   /* If the pSrc table is the right table of a LEFT JOIN then we may not
89992   ** use an index to satisfy IS NULL constraints on that table.  This is
89993   ** because columns might end up being NULL if the table does not match -
89994   ** a circumstance which the index cannot help us discover.  Ticket #2177.
89995   */
89996   if( pSrc->jointype & JT_LEFT ){
89997     idxEqTermMask = WO_EQ|WO_IN;
89998   }else{
89999     idxEqTermMask = WO_EQ|WO_IN|WO_ISNULL;
90000   }
90001
90002   if( pSrc->pIndex ){
90003     /* An INDEXED BY clause specifies a particular index to use */
90004     pIdx = pProbe = pSrc->pIndex;
90005     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
90006     eqTermMask = idxEqTermMask;
90007   }else{
90008     /* There is no INDEXED BY clause.  Create a fake Index object to
90009     ** represent the primary key */
90010     Index *pFirst;                /* Any other index on the table */
90011     memset(&sPk, 0, sizeof(Index));
90012     sPk.nColumn = 1;
90013     sPk.aiColumn = &aiColumnPk;
90014     sPk.aiRowEst = aiRowEstPk;
90015     aiRowEstPk[1] = 1;
90016     sPk.onError = OE_Replace;
90017     sPk.pTable = pSrc->pTab;
90018     pFirst = pSrc->pTab->pIndex;
90019     if( pSrc->notIndexed==0 ){
90020       sPk.pNext = pFirst;
90021     }
90022     /* The aiRowEstPk[0] is an estimate of the total number of rows in the
90023     ** table.  Get this information from the ANALYZE information if it is
90024     ** available.  If not available, assume the table 1 million rows in size.
90025     */
90026     if( pFirst ){
90027       assert( pFirst->aiRowEst!=0 ); /* Allocated together with pFirst */
90028       aiRowEstPk[0] = pFirst->aiRowEst[0];
90029     }else{
90030       aiRowEstPk[0] = 1000000;
90031     }
90032     pProbe = &sPk;
90033     wsFlagMask = ~(
90034         WHERE_COLUMN_IN|WHERE_COLUMN_EQ|WHERE_COLUMN_NULL|WHERE_COLUMN_RANGE
90035     );
90036     eqTermMask = WO_EQ|WO_IN;
90037     pIdx = 0;
90038   }
90039
90040   /* Loop over all indices looking for the best one to use
90041   */
90042   for(; pProbe; pIdx=pProbe=pProbe->pNext){
90043     const unsigned int * const aiRowEst = pProbe->aiRowEst;
90044     double cost;                /* Cost of using pProbe */
90045     double nRow;                /* Estimated number of rows in result set */
90046     int rev;                    /* True to scan in reverse order */
90047     int wsFlags = 0;
90048     Bitmask used = 0;
90049
90050     /* The following variables are populated based on the properties of
90051     ** scan being evaluated. They are then used to determine the expected
90052     ** cost and number of rows returned.
90053     **
90054     **  nEq: 
90055     **    Number of equality terms that can be implemented using the index.
90056     **
90057     **  nInMul:  
90058     **    The "in-multiplier". This is an estimate of how many seek operations 
90059     **    SQLite must perform on the index in question. For example, if the 
90060     **    WHERE clause is:
90061     **
90062     **      WHERE a IN (1, 2, 3) AND b IN (4, 5, 6)
90063     **
90064     **    SQLite must perform 9 lookups on an index on (a, b), so nInMul is 
90065     **    set to 9. Given the same schema and either of the following WHERE 
90066     **    clauses:
90067     **
90068     **      WHERE a =  1
90069     **      WHERE a >= 2
90070     **
90071     **    nInMul is set to 1.
90072     **
90073     **    If there exists a WHERE term of the form "x IN (SELECT ...)", then 
90074     **    the sub-select is assumed to return 25 rows for the purposes of 
90075     **    determining nInMul.
90076     **
90077     **  bInEst:  
90078     **    Set to true if there was at least one "x IN (SELECT ...)" term used 
90079     **    in determining the value of nInMul.
90080     **
90081     **  nBound:
90082     **    An estimate on the amount of the table that must be searched.  A
90083     **    value of 100 means the entire table is searched.  Range constraints
90084     **    might reduce this to a value less than 100 to indicate that only
90085     **    a fraction of the table needs searching.  In the absence of
90086     **    sqlite_stat2 ANALYZE data, a single inequality reduces the search
90087     **    space to 1/3rd its original size.  So an x>? constraint reduces
90088     **    nBound to 33.  Two constraints (x>? AND x<?) reduce nBound to 11.
90089     **
90090     **  bSort:   
90091     **    Boolean. True if there is an ORDER BY clause that will require an 
90092     **    external sort (i.e. scanning the index being evaluated will not 
90093     **    correctly order records).
90094     **
90095     **  bLookup: 
90096     **    Boolean. True if for each index entry visited a lookup on the 
90097     **    corresponding table b-tree is required. This is always false 
90098     **    for the rowid index. For other indexes, it is true unless all the 
90099     **    columns of the table used by the SELECT statement are present in 
90100     **    the index (such an index is sometimes described as a covering index).
90101     **    For example, given the index on (a, b), the second of the following 
90102     **    two queries requires table b-tree lookups, but the first does not.
90103     **
90104     **             SELECT a, b    FROM tbl WHERE a = 1;
90105     **             SELECT a, b, c FROM tbl WHERE a = 1;
90106     */
90107     int nEq;
90108     int bInEst = 0;
90109     int nInMul = 1;
90110     int nBound = 100;
90111     int bSort = 0;
90112     int bLookup = 0;
90113
90114     /* Determine the values of nEq and nInMul */
90115     for(nEq=0; nEq<pProbe->nColumn; nEq++){
90116       WhereTerm *pTerm;           /* A single term of the WHERE clause */
90117       int j = pProbe->aiColumn[nEq];
90118       pTerm = findTerm(pWC, iCur, j, notReady, eqTermMask, pIdx);
90119       if( pTerm==0 ) break;
90120       wsFlags |= (WHERE_COLUMN_EQ|WHERE_ROWID_EQ);
90121       if( pTerm->eOperator & WO_IN ){
90122         Expr *pExpr = pTerm->pExpr;
90123         wsFlags |= WHERE_COLUMN_IN;
90124         if( ExprHasProperty(pExpr, EP_xIsSelect) ){
90125           nInMul *= 25;
90126           bInEst = 1;
90127         }else if( pExpr->x.pList ){
90128           nInMul *= pExpr->x.pList->nExpr + 1;
90129         }
90130       }else if( pTerm->eOperator & WO_ISNULL ){
90131         wsFlags |= WHERE_COLUMN_NULL;
90132       }
90133       used |= pTerm->prereqRight;
90134     }
90135
90136     /* Determine the value of nBound. */
90137     if( nEq<pProbe->nColumn ){
90138       int j = pProbe->aiColumn[nEq];
90139       if( findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE|WO_GT|WO_GE, pIdx) ){
90140         WhereTerm *pTop = findTerm(pWC, iCur, j, notReady, WO_LT|WO_LE, pIdx);
90141         WhereTerm *pBtm = findTerm(pWC, iCur, j, notReady, WO_GT|WO_GE, pIdx);
90142         whereRangeScanEst(pParse, pProbe, nEq, pBtm, pTop, &nBound);
90143         if( pTop ){
90144           wsFlags |= WHERE_TOP_LIMIT;
90145           used |= pTop->prereqRight;
90146         }
90147         if( pBtm ){
90148           wsFlags |= WHERE_BTM_LIMIT;
90149           used |= pBtm->prereqRight;
90150         }
90151         wsFlags |= (WHERE_COLUMN_RANGE|WHERE_ROWID_RANGE);
90152       }
90153     }else if( pProbe->onError!=OE_None ){
90154       testcase( wsFlags & WHERE_COLUMN_IN );
90155       testcase( wsFlags & WHERE_COLUMN_NULL );
90156       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0 ){
90157         wsFlags |= WHERE_UNIQUE;
90158       }
90159     }
90160
90161     /* If there is an ORDER BY clause and the index being considered will
90162     ** naturally scan rows in the required order, set the appropriate flags
90163     ** in wsFlags. Otherwise, if there is an ORDER BY clause but the index
90164     ** will scan rows in a different order, set the bSort variable.  */
90165     if( pOrderBy ){
90166       if( (wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_NULL))==0
90167         && isSortingIndex(pParse,pWC->pMaskSet,pProbe,iCur,pOrderBy,nEq,&rev)
90168       ){
90169         wsFlags |= WHERE_ROWID_RANGE|WHERE_COLUMN_RANGE|WHERE_ORDERBY;
90170         wsFlags |= (rev ? WHERE_REVERSE : 0);
90171       }else{
90172         bSort = 1;
90173       }
90174     }
90175
90176     /* If currently calculating the cost of using an index (not the IPK
90177     ** index), determine if all required column data may be obtained without 
90178     ** seeking to entries in the main table (i.e. if the index is a covering
90179     ** index for this query). If it is, set the WHERE_IDX_ONLY flag in
90180     ** wsFlags. Otherwise, set the bLookup variable to true.  */
90181     if( pIdx && wsFlags ){
90182       Bitmask m = pSrc->colUsed;
90183       int j;
90184       for(j=0; j<pIdx->nColumn; j++){
90185         int x = pIdx->aiColumn[j];
90186         if( x<BMS-1 ){
90187           m &= ~(((Bitmask)1)<<x);
90188         }
90189       }
90190       if( m==0 ){
90191         wsFlags |= WHERE_IDX_ONLY;
90192       }else{
90193         bLookup = 1;
90194       }
90195     }
90196
90197     /**** Begin adding up the cost of using this index (Needs improvements)
90198     **
90199     ** Estimate the number of rows of output.  For an IN operator,
90200     ** do not let the estimate exceed half the rows in the table.
90201     */
90202     nRow = (double)(aiRowEst[nEq] * nInMul);
90203     if( bInEst && nRow*2>aiRowEst[0] ){
90204       nRow = aiRowEst[0]/2;
90205       nInMul = (int)(nRow / aiRowEst[nEq]);
90206     }
90207
90208     /* Assume constant cost to access a row and logarithmic cost to
90209     ** do a binary search.  Hence, the initial cost is the number of output
90210     ** rows plus log2(table-size) times the number of binary searches.
90211     */
90212     cost = nRow + nInMul*estLog(aiRowEst[0]);
90213
90214     /* Adjust the number of rows and the cost downward to reflect rows
90215     ** that are excluded by range constraints.
90216     */
90217     nRow = (nRow * (double)nBound) / (double)100;
90218     cost = (cost * (double)nBound) / (double)100;
90219
90220     /* Add in the estimated cost of sorting the result
90221     */
90222     if( bSort ){
90223       cost += cost*estLog(cost);
90224     }
90225
90226     /* If all information can be taken directly from the index, we avoid
90227     ** doing table lookups.  This reduces the cost by half.  (Not really -
90228     ** this needs to be fixed.)
90229     */
90230     if( pIdx && bLookup==0 ){
90231       cost /= (double)2;
90232     }
90233     /**** Cost of using this index has now been computed ****/
90234
90235     WHERETRACE((
90236       "tbl=%s idx=%s nEq=%d nInMul=%d nBound=%d bSort=%d bLookup=%d"
90237       " wsFlags=%d   (nRow=%.2f cost=%.2f)\n",
90238       pSrc->pTab->zName, (pIdx ? pIdx->zName : "ipk"), 
90239       nEq, nInMul, nBound, bSort, bLookup, wsFlags, nRow, cost
90240     ));
90241
90242     /* If this index is the best we have seen so far, then record this
90243     ** index and its cost in the pCost structure.
90244     */
90245     if( (!pIdx || wsFlags) && cost<pCost->rCost ){
90246       pCost->rCost = cost;
90247       pCost->nRow = nRow;
90248       pCost->used = used;
90249       pCost->plan.wsFlags = (wsFlags&wsFlagMask);
90250       pCost->plan.nEq = nEq;
90251       pCost->plan.u.pIdx = pIdx;
90252     }
90253
90254     /* If there was an INDEXED BY clause, then only that one index is
90255     ** considered. */
90256     if( pSrc->pIndex ) break;
90257
90258     /* Reset masks for the next index in the loop */
90259     wsFlagMask = ~(WHERE_ROWID_EQ|WHERE_ROWID_RANGE);
90260     eqTermMask = idxEqTermMask;
90261   }
90262
90263   /* If there is no ORDER BY clause and the SQLITE_ReverseOrder flag
90264   ** is set, then reverse the order that the index will be scanned
90265   ** in. This is used for application testing, to help find cases
90266   ** where application behaviour depends on the (undefined) order that
90267   ** SQLite outputs rows in in the absence of an ORDER BY clause.  */
90268   if( !pOrderBy && pParse->db->flags & SQLITE_ReverseOrder ){
90269     pCost->plan.wsFlags |= WHERE_REVERSE;
90270   }
90271
90272   assert( pOrderBy || (pCost->plan.wsFlags&WHERE_ORDERBY)==0 );
90273   assert( pCost->plan.u.pIdx==0 || (pCost->plan.wsFlags&WHERE_ROWID_EQ)==0 );
90274   assert( pSrc->pIndex==0 
90275        || pCost->plan.u.pIdx==0 
90276        || pCost->plan.u.pIdx==pSrc->pIndex 
90277   );
90278
90279   WHERETRACE(("best index is: %s\n", 
90280     (pCost->plan.u.pIdx ? pCost->plan.u.pIdx->zName : "ipk")
90281   ));
90282   
90283   bestOrClauseIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
90284   pCost->plan.wsFlags |= eqTermMask;
90285 }
90286
90287 /*
90288 ** Find the query plan for accessing table pSrc->pTab. Write the
90289 ** best query plan and its cost into the WhereCost object supplied 
90290 ** as the last parameter. This function may calculate the cost of
90291 ** both real and virtual table scans.
90292 */
90293 static void bestIndex(
90294   Parse *pParse,              /* The parsing context */
90295   WhereClause *pWC,           /* The WHERE clause */
90296   struct SrcList_item *pSrc,  /* The FROM clause term to search */
90297   Bitmask notReady,           /* Mask of cursors that are not available */
90298   ExprList *pOrderBy,         /* The ORDER BY clause */
90299   WhereCost *pCost            /* Lowest cost query plan */
90300 ){
90301 #ifndef SQLITE_OMIT_VIRTUALTABLE
90302   if( IsVirtual(pSrc->pTab) ){
90303     sqlite3_index_info *p = 0;
90304     bestVirtualIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost, &p);
90305     if( p->needToFreeIdxStr ){
90306       sqlite3_free(p->idxStr);
90307     }
90308     sqlite3DbFree(pParse->db, p);
90309   }else
90310 #endif
90311   {
90312     bestBtreeIndex(pParse, pWC, pSrc, notReady, pOrderBy, pCost);
90313   }
90314 }
90315
90316 /*
90317 ** Disable a term in the WHERE clause.  Except, do not disable the term
90318 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
90319 ** or USING clause of that join.
90320 **
90321 ** Consider the term t2.z='ok' in the following queries:
90322 **
90323 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
90324 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
90325 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
90326 **
90327 ** The t2.z='ok' is disabled in the in (2) because it originates
90328 ** in the ON clause.  The term is disabled in (3) because it is not part
90329 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
90330 **
90331 ** Disabling a term causes that term to not be tested in the inner loop
90332 ** of the join.  Disabling is an optimization.  When terms are satisfied
90333 ** by indices, we disable them to prevent redundant tests in the inner
90334 ** loop.  We would get the correct results if nothing were ever disabled,
90335 ** but joins might run a little slower.  The trick is to disable as much
90336 ** as we can without disabling too much.  If we disabled in (1), we'd get
90337 ** the wrong answer.  See ticket #813.
90338 */
90339 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
90340   if( pTerm
90341       && ALWAYS((pTerm->wtFlags & TERM_CODED)==0)
90342       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
90343   ){
90344     pTerm->wtFlags |= TERM_CODED;
90345     if( pTerm->iParent>=0 ){
90346       WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
90347       if( (--pOther->nChild)==0 ){
90348         disableTerm(pLevel, pOther);
90349       }
90350     }
90351   }
90352 }
90353
90354 /*
90355 ** Code an OP_Affinity opcode to apply the column affinity string zAff
90356 ** to the n registers starting at base. 
90357 **
90358 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
90359 ** beginning and end of zAff are ignored.  If all entries in zAff are
90360 ** SQLITE_AFF_NONE, then no code gets generated.
90361 **
90362 ** This routine makes its own copy of zAff so that the caller is free
90363 ** to modify zAff after this routine returns.
90364 */
90365 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
90366   Vdbe *v = pParse->pVdbe;
90367   if( zAff==0 ){
90368     assert( pParse->db->mallocFailed );
90369     return;
90370   }
90371   assert( v!=0 );
90372
90373   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
90374   ** and end of the affinity string.
90375   */
90376   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
90377     n--;
90378     base++;
90379     zAff++;
90380   }
90381   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
90382     n--;
90383   }
90384
90385   /* Code the OP_Affinity opcode if there is anything left to do. */
90386   if( n>0 ){
90387     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
90388     sqlite3VdbeChangeP4(v, -1, zAff, n);
90389     sqlite3ExprCacheAffinityChange(pParse, base, n);
90390   }
90391 }
90392
90393
90394 /*
90395 ** Generate code for a single equality term of the WHERE clause.  An equality
90396 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
90397 ** coded.
90398 **
90399 ** The current value for the constraint is left in register iReg.
90400 **
90401 ** For a constraint of the form X=expr, the expression is evaluated and its
90402 ** result is left on the stack.  For constraints of the form X IN (...)
90403 ** this routine sets up a loop that will iterate over all values of X.
90404 */
90405 static int codeEqualityTerm(
90406   Parse *pParse,      /* The parsing context */
90407   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
90408   WhereLevel *pLevel, /* When level of the FROM clause we are working on */
90409   int iTarget         /* Attempt to leave results in this register */
90410 ){
90411   Expr *pX = pTerm->pExpr;
90412   Vdbe *v = pParse->pVdbe;
90413   int iReg;                  /* Register holding results */
90414
90415   assert( iTarget>0 );
90416   if( pX->op==TK_EQ ){
90417     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
90418   }else if( pX->op==TK_ISNULL ){
90419     iReg = iTarget;
90420     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
90421 #ifndef SQLITE_OMIT_SUBQUERY
90422   }else{
90423     int eType;
90424     int iTab;
90425     struct InLoop *pIn;
90426
90427     assert( pX->op==TK_IN );
90428     iReg = iTarget;
90429     eType = sqlite3FindInIndex(pParse, pX, 0);
90430     iTab = pX->iTable;
90431     sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
90432     assert( pLevel->plan.wsFlags & WHERE_IN_ABLE );
90433     if( pLevel->u.in.nIn==0 ){
90434       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
90435     }
90436     pLevel->u.in.nIn++;
90437     pLevel->u.in.aInLoop =
90438        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
90439                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
90440     pIn = pLevel->u.in.aInLoop;
90441     if( pIn ){
90442       pIn += pLevel->u.in.nIn - 1;
90443       pIn->iCur = iTab;
90444       if( eType==IN_INDEX_ROWID ){
90445         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
90446       }else{
90447         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
90448       }
90449       sqlite3VdbeAddOp1(v, OP_IsNull, iReg);
90450     }else{
90451       pLevel->u.in.nIn = 0;
90452     }
90453 #endif
90454   }
90455   disableTerm(pLevel, pTerm);
90456   return iReg;
90457 }
90458
90459 /*
90460 ** Generate code that will evaluate all == and IN constraints for an
90461 ** index.
90462 **
90463 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
90464 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
90465 ** The index has as many as three equality constraints, but in this
90466 ** example, the third "c" value is an inequality.  So only two 
90467 ** constraints are coded.  This routine will generate code to evaluate
90468 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
90469 ** in consecutive registers and the index of the first register is returned.
90470 **
90471 ** In the example above nEq==2.  But this subroutine works for any value
90472 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
90473 ** The only thing it does is allocate the pLevel->iMem memory cell and
90474 ** compute the affinity string.
90475 **
90476 ** This routine always allocates at least one memory cell and returns
90477 ** the index of that memory cell. The code that
90478 ** calls this routine will use that memory cell to store the termination
90479 ** key value of the loop.  If one or more IN operators appear, then
90480 ** this routine allocates an additional nEq memory cells for internal
90481 ** use.
90482 **
90483 ** Before returning, *pzAff is set to point to a buffer containing a
90484 ** copy of the column affinity string of the index allocated using
90485 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
90486 ** with equality constraints that use NONE affinity are set to
90487 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
90488 **
90489 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
90490 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
90491 **
90492 ** In the example above, the index on t1(a) has TEXT affinity. But since
90493 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
90494 ** no conversion should be attempted before using a t2.b value as part of
90495 ** a key to search the index. Hence the first byte in the returned affinity
90496 ** string in this example would be set to SQLITE_AFF_NONE.
90497 */
90498 static int codeAllEqualityTerms(
90499   Parse *pParse,        /* Parsing context */
90500   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
90501   WhereClause *pWC,     /* The WHERE clause */
90502   Bitmask notReady,     /* Which parts of FROM have not yet been coded */
90503   int nExtraReg,        /* Number of extra registers to allocate */
90504   char **pzAff          /* OUT: Set to point to affinity string */
90505 ){
90506   int nEq = pLevel->plan.nEq;   /* The number of == or IN constraints to code */
90507   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
90508   Index *pIdx;                  /* The index being used for this loop */
90509   int iCur = pLevel->iTabCur;   /* The cursor of the table */
90510   WhereTerm *pTerm;             /* A single constraint term */
90511   int j;                        /* Loop counter */
90512   int regBase;                  /* Base register */
90513   int nReg;                     /* Number of registers to allocate */
90514   char *zAff;                   /* Affinity string to return */
90515
90516   /* This module is only called on query plans that use an index. */
90517   assert( pLevel->plan.wsFlags & WHERE_INDEXED );
90518   pIdx = pLevel->plan.u.pIdx;
90519
90520   /* Figure out how many memory cells we will need then allocate them.
90521   */
90522   regBase = pParse->nMem + 1;
90523   nReg = pLevel->plan.nEq + nExtraReg;
90524   pParse->nMem += nReg;
90525
90526   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
90527   if( !zAff ){
90528     pParse->db->mallocFailed = 1;
90529   }
90530
90531   /* Evaluate the equality constraints
90532   */
90533   assert( pIdx->nColumn>=nEq );
90534   for(j=0; j<nEq; j++){
90535     int r1;
90536     int k = pIdx->aiColumn[j];
90537     pTerm = findTerm(pWC, iCur, k, notReady, pLevel->plan.wsFlags, pIdx);
90538     if( NEVER(pTerm==0) ) break;
90539     assert( (pTerm->wtFlags & TERM_CODED)==0 );
90540     r1 = codeEqualityTerm(pParse, pTerm, pLevel, regBase+j);
90541     if( r1!=regBase+j ){
90542       if( nReg==1 ){
90543         sqlite3ReleaseTempReg(pParse, regBase);
90544         regBase = r1;
90545       }else{
90546         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
90547       }
90548     }
90549     testcase( pTerm->eOperator & WO_ISNULL );
90550     testcase( pTerm->eOperator & WO_IN );
90551     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
90552       Expr *pRight = pTerm->pExpr->pRight;
90553       sqlite3ExprCodeIsNullJump(v, pRight, regBase+j, pLevel->addrBrk);
90554       if( zAff ){
90555         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
90556           zAff[j] = SQLITE_AFF_NONE;
90557         }
90558         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
90559           zAff[j] = SQLITE_AFF_NONE;
90560         }
90561       }
90562     }
90563   }
90564   *pzAff = zAff;
90565   return regBase;
90566 }
90567
90568 /*
90569 ** Generate code for the start of the iLevel-th loop in the WHERE clause
90570 ** implementation described by pWInfo.
90571 */
90572 static Bitmask codeOneLoopStart(
90573   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
90574   int iLevel,          /* Which level of pWInfo->a[] should be coded */
90575   u16 wctrlFlags,      /* One of the WHERE_* flags defined in sqliteInt.h */
90576   Bitmask notReady     /* Which tables are currently available */
90577 ){
90578   int j, k;            /* Loop counters */
90579   int iCur;            /* The VDBE cursor for the table */
90580   int addrNxt;         /* Where to jump to continue with the next IN case */
90581   int omitTable;       /* True if we use the index only */
90582   int bRev;            /* True if we need to scan in reverse order */
90583   WhereLevel *pLevel;  /* The where level to be coded */
90584   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
90585   WhereTerm *pTerm;               /* A WHERE clause term */
90586   Parse *pParse;                  /* Parsing context */
90587   Vdbe *v;                        /* The prepared stmt under constructions */
90588   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
90589   int addrBrk;                    /* Jump here to break out of the loop */
90590   int addrCont;                   /* Jump here to continue with next cycle */
90591   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
90592   int iReleaseReg = 0;      /* Temp register to free before returning */
90593
90594   pParse = pWInfo->pParse;
90595   v = pParse->pVdbe;
90596   pWC = pWInfo->pWC;
90597   pLevel = &pWInfo->a[iLevel];
90598   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
90599   iCur = pTabItem->iCursor;
90600   bRev = (pLevel->plan.wsFlags & WHERE_REVERSE)!=0;
90601   omitTable = (pLevel->plan.wsFlags & WHERE_IDX_ONLY)!=0 
90602            && (wctrlFlags & WHERE_FORCE_TABLE)==0;
90603
90604   /* Create labels for the "break" and "continue" instructions
90605   ** for the current loop.  Jump to addrBrk to break out of a loop.
90606   ** Jump to cont to go immediately to the next iteration of the
90607   ** loop.
90608   **
90609   ** When there is an IN operator, we also have a "addrNxt" label that
90610   ** means to continue with the next IN value combination.  When
90611   ** there are no IN operators in the constraints, the "addrNxt" label
90612   ** is the same as "addrBrk".
90613   */
90614   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
90615   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
90616
90617   /* If this is the right table of a LEFT OUTER JOIN, allocate and
90618   ** initialize a memory cell that records if this table matches any
90619   ** row of the left table of the join.
90620   */
90621   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
90622     pLevel->iLeftJoin = ++pParse->nMem;
90623     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
90624     VdbeComment((v, "init LEFT JOIN no-match flag"));
90625   }
90626
90627 #ifndef SQLITE_OMIT_VIRTUALTABLE
90628   if(  (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
90629     /* Case 0:  The table is a virtual-table.  Use the VFilter and VNext
90630     **          to access the data.
90631     */
90632     int iReg;   /* P3 Value for OP_VFilter */
90633     sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
90634     int nConstraint = pVtabIdx->nConstraint;
90635     struct sqlite3_index_constraint_usage *aUsage =
90636                                                 pVtabIdx->aConstraintUsage;
90637     const struct sqlite3_index_constraint *aConstraint =
90638                                                 pVtabIdx->aConstraint;
90639
90640     sqlite3ExprCachePush(pParse);
90641     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
90642     for(j=1; j<=nConstraint; j++){
90643       for(k=0; k<nConstraint; k++){
90644         if( aUsage[k].argvIndex==j ){
90645           int iTerm = aConstraint[k].iTermOffset;
90646           sqlite3ExprCode(pParse, pWC->a[iTerm].pExpr->pRight, iReg+j+1);
90647           break;
90648         }
90649       }
90650       if( k==nConstraint ) break;
90651     }
90652     sqlite3VdbeAddOp2(v, OP_Integer, pVtabIdx->idxNum, iReg);
90653     sqlite3VdbeAddOp2(v, OP_Integer, j-1, iReg+1);
90654     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrBrk, iReg, pVtabIdx->idxStr,
90655                       pVtabIdx->needToFreeIdxStr ? P4_MPRINTF : P4_STATIC);
90656     pVtabIdx->needToFreeIdxStr = 0;
90657     for(j=0; j<nConstraint; j++){
90658       if( aUsage[j].omit ){
90659         int iTerm = aConstraint[j].iTermOffset;
90660         disableTerm(pLevel, &pWC->a[iTerm]);
90661       }
90662     }
90663     pLevel->op = OP_VNext;
90664     pLevel->p1 = iCur;
90665     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
90666     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
90667     sqlite3ExprCachePop(pParse, 1);
90668   }else
90669 #endif /* SQLITE_OMIT_VIRTUALTABLE */
90670
90671   if( pLevel->plan.wsFlags & WHERE_ROWID_EQ ){
90672     /* Case 1:  We can directly reference a single row using an
90673     **          equality comparison against the ROWID field.  Or
90674     **          we reference multiple rows using a "rowid IN (...)"
90675     **          construct.
90676     */
90677     iReleaseReg = sqlite3GetTempReg(pParse);
90678     pTerm = findTerm(pWC, iCur, -1, notReady, WO_EQ|WO_IN, 0);
90679     assert( pTerm!=0 );
90680     assert( pTerm->pExpr!=0 );
90681     assert( pTerm->leftCursor==iCur );
90682     assert( omitTable==0 );
90683     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, iReleaseReg);
90684     addrNxt = pLevel->addrNxt;
90685     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt);
90686     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
90687     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
90688     VdbeComment((v, "pk"));
90689     pLevel->op = OP_Noop;
90690   }else if( pLevel->plan.wsFlags & WHERE_ROWID_RANGE ){
90691     /* Case 2:  We have an inequality comparison against the ROWID field.
90692     */
90693     int testOp = OP_Noop;
90694     int start;
90695     int memEndValue = 0;
90696     WhereTerm *pStart, *pEnd;
90697
90698     assert( omitTable==0 );
90699     pStart = findTerm(pWC, iCur, -1, notReady, WO_GT|WO_GE, 0);
90700     pEnd = findTerm(pWC, iCur, -1, notReady, WO_LT|WO_LE, 0);
90701     if( bRev ){
90702       pTerm = pStart;
90703       pStart = pEnd;
90704       pEnd = pTerm;
90705     }
90706     if( pStart ){
90707       Expr *pX;             /* The expression that defines the start bound */
90708       int r1, rTemp;        /* Registers for holding the start boundary */
90709
90710       /* The following constant maps TK_xx codes into corresponding 
90711       ** seek opcodes.  It depends on a particular ordering of TK_xx
90712       */
90713       const u8 aMoveOp[] = {
90714            /* TK_GT */  OP_SeekGt,
90715            /* TK_LE */  OP_SeekLe,
90716            /* TK_LT */  OP_SeekLt,
90717            /* TK_GE */  OP_SeekGe
90718       };
90719       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
90720       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
90721       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
90722
90723       pX = pStart->pExpr;
90724       assert( pX!=0 );
90725       assert( pStart->leftCursor==iCur );
90726       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
90727       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
90728       VdbeComment((v, "pk"));
90729       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
90730       sqlite3ReleaseTempReg(pParse, rTemp);
90731       disableTerm(pLevel, pStart);
90732     }else{
90733       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
90734     }
90735     if( pEnd ){
90736       Expr *pX;
90737       pX = pEnd->pExpr;
90738       assert( pX!=0 );
90739       assert( pEnd->leftCursor==iCur );
90740       memEndValue = ++pParse->nMem;
90741       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
90742       if( pX->op==TK_LT || pX->op==TK_GT ){
90743         testOp = bRev ? OP_Le : OP_Ge;
90744       }else{
90745         testOp = bRev ? OP_Lt : OP_Gt;
90746       }
90747       disableTerm(pLevel, pEnd);
90748     }
90749     start = sqlite3VdbeCurrentAddr(v);
90750     pLevel->op = bRev ? OP_Prev : OP_Next;
90751     pLevel->p1 = iCur;
90752     pLevel->p2 = start;
90753     pLevel->p5 = (pStart==0 && pEnd==0) ?1:0;
90754     if( testOp!=OP_Noop ){
90755       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
90756       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
90757       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
90758       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
90759       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
90760     }
90761   }else if( pLevel->plan.wsFlags & (WHERE_COLUMN_RANGE|WHERE_COLUMN_EQ) ){
90762     /* Case 3: A scan using an index.
90763     **
90764     **         The WHERE clause may contain zero or more equality 
90765     **         terms ("==" or "IN" operators) that refer to the N
90766     **         left-most columns of the index. It may also contain
90767     **         inequality constraints (>, <, >= or <=) on the indexed
90768     **         column that immediately follows the N equalities. Only 
90769     **         the right-most column can be an inequality - the rest must
90770     **         use the "==" and "IN" operators. For example, if the 
90771     **         index is on (x,y,z), then the following clauses are all 
90772     **         optimized:
90773     **
90774     **            x=5
90775     **            x=5 AND y=10
90776     **            x=5 AND y<10
90777     **            x=5 AND y>5 AND y<10
90778     **            x=5 AND y=5 AND z<=10
90779     **
90780     **         The z<10 term of the following cannot be used, only
90781     **         the x=5 term:
90782     **
90783     **            x=5 AND z<10
90784     **
90785     **         N may be zero if there are inequality constraints.
90786     **         If there are no inequality constraints, then N is at
90787     **         least one.
90788     **
90789     **         This case is also used when there are no WHERE clause
90790     **         constraints but an index is selected anyway, in order
90791     **         to force the output order to conform to an ORDER BY.
90792     */  
90793     int aStartOp[] = {
90794       0,
90795       0,
90796       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
90797       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
90798       OP_SeekGt,           /* 4: (start_constraints  && !startEq && !bRev) */
90799       OP_SeekLt,           /* 5: (start_constraints  && !startEq &&  bRev) */
90800       OP_SeekGe,           /* 6: (start_constraints  &&  startEq && !bRev) */
90801       OP_SeekLe            /* 7: (start_constraints  &&  startEq &&  bRev) */
90802     };
90803     int aEndOp[] = {
90804       OP_Noop,             /* 0: (!end_constraints) */
90805       OP_IdxGE,            /* 1: (end_constraints && !bRev) */
90806       OP_IdxLT             /* 2: (end_constraints && bRev) */
90807     };
90808     int nEq = pLevel->plan.nEq;
90809     int isMinQuery = 0;          /* If this is an optimized SELECT min(x).. */
90810     int regBase;                 /* Base register holding constraint values */
90811     int r1;                      /* Temp register */
90812     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
90813     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
90814     int startEq;                 /* True if range start uses ==, >= or <= */
90815     int endEq;                   /* True if range end uses ==, >= or <= */
90816     int start_constraints;       /* Start of range is constrained */
90817     int nConstraint;             /* Number of constraint terms */
90818     Index *pIdx;         /* The index we will be using */
90819     int iIdxCur;         /* The VDBE cursor for the index */
90820     int nExtraReg = 0;   /* Number of extra registers needed */
90821     int op;              /* Instruction opcode */
90822     char *zAff;
90823
90824     pIdx = pLevel->plan.u.pIdx;
90825     iIdxCur = pLevel->iIdxCur;
90826     k = pIdx->aiColumn[nEq];     /* Column for inequality constraints */
90827
90828     /* If this loop satisfies a sort order (pOrderBy) request that 
90829     ** was passed to this function to implement a "SELECT min(x) ..." 
90830     ** query, then the caller will only allow the loop to run for
90831     ** a single iteration. This means that the first row returned
90832     ** should not have a NULL value stored in 'x'. If column 'x' is
90833     ** the first one after the nEq equality constraints in the index,
90834     ** this requires some special handling.
90835     */
90836     if( (wctrlFlags&WHERE_ORDERBY_MIN)!=0
90837      && (pLevel->plan.wsFlags&WHERE_ORDERBY)
90838      && (pIdx->nColumn>nEq)
90839     ){
90840       /* assert( pOrderBy->nExpr==1 ); */
90841       /* assert( pOrderBy->a[0].pExpr->iColumn==pIdx->aiColumn[nEq] ); */
90842       isMinQuery = 1;
90843       nExtraReg = 1;
90844     }
90845
90846     /* Find any inequality constraint terms for the start and end 
90847     ** of the range. 
90848     */
90849     if( pLevel->plan.wsFlags & WHERE_TOP_LIMIT ){
90850       pRangeEnd = findTerm(pWC, iCur, k, notReady, (WO_LT|WO_LE), pIdx);
90851       nExtraReg = 1;
90852     }
90853     if( pLevel->plan.wsFlags & WHERE_BTM_LIMIT ){
90854       pRangeStart = findTerm(pWC, iCur, k, notReady, (WO_GT|WO_GE), pIdx);
90855       nExtraReg = 1;
90856     }
90857
90858     /* Generate code to evaluate all constraint terms using == or IN
90859     ** and store the values of those terms in an array of registers
90860     ** starting at regBase.
90861     */
90862     regBase = codeAllEqualityTerms(
90863         pParse, pLevel, pWC, notReady, nExtraReg, &zAff
90864     );
90865     addrNxt = pLevel->addrNxt;
90866
90867     /* If we are doing a reverse order scan on an ascending index, or
90868     ** a forward order scan on a descending index, interchange the 
90869     ** start and end terms (pRangeStart and pRangeEnd).
90870     */
90871     if( bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC) ){
90872       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
90873     }
90874
90875     testcase( pRangeStart && pRangeStart->eOperator & WO_LE );
90876     testcase( pRangeStart && pRangeStart->eOperator & WO_GE );
90877     testcase( pRangeEnd && pRangeEnd->eOperator & WO_LE );
90878     testcase( pRangeEnd && pRangeEnd->eOperator & WO_GE );
90879     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
90880     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
90881     start_constraints = pRangeStart || nEq>0;
90882
90883     /* Seek the index cursor to the start of the range. */
90884     nConstraint = nEq;
90885     if( pRangeStart ){
90886       Expr *pRight = pRangeStart->pExpr->pRight;
90887       sqlite3ExprCode(pParse, pRight, regBase+nEq);
90888       sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
90889       if( zAff ){
90890         if( sqlite3CompareAffinity(pRight, zAff[nConstraint])==SQLITE_AFF_NONE){
90891           /* Since the comparison is to be performed with no conversions
90892           ** applied to the operands, set the affinity to apply to pRight to 
90893           ** SQLITE_AFF_NONE.  */
90894           zAff[nConstraint] = SQLITE_AFF_NONE;
90895         }
90896         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[nConstraint]) ){
90897           zAff[nConstraint] = SQLITE_AFF_NONE;
90898         }
90899       }  
90900       nConstraint++;
90901     }else if( isMinQuery ){
90902       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
90903       nConstraint++;
90904       startEq = 0;
90905       start_constraints = 1;
90906     }
90907     codeApplyAffinity(pParse, regBase, nConstraint, zAff);
90908     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
90909     assert( op!=0 );
90910     testcase( op==OP_Rewind );
90911     testcase( op==OP_Last );
90912     testcase( op==OP_SeekGt );
90913     testcase( op==OP_SeekGe );
90914     testcase( op==OP_SeekLe );
90915     testcase( op==OP_SeekLt );
90916     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
90917
90918     /* Load the value for the inequality constraint at the end of the
90919     ** range (if any).
90920     */
90921     nConstraint = nEq;
90922     if( pRangeEnd ){
90923       Expr *pRight = pRangeEnd->pExpr->pRight;
90924       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
90925       sqlite3ExprCode(pParse, pRight, regBase+nEq);
90926       sqlite3ExprCodeIsNullJump(v, pRight, regBase+nEq, addrNxt);
90927       if( zAff ){
90928         if( sqlite3CompareAffinity(pRight, zAff[nConstraint])==SQLITE_AFF_NONE){
90929           /* Since the comparison is to be performed with no conversions
90930           ** applied to the operands, set the affinity to apply to pRight to 
90931           ** SQLITE_AFF_NONE.  */
90932           zAff[nConstraint] = SQLITE_AFF_NONE;
90933         }
90934         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[nConstraint]) ){
90935           zAff[nConstraint] = SQLITE_AFF_NONE;
90936         }
90937       }  
90938       codeApplyAffinity(pParse, regBase, nEq+1, zAff);
90939       nConstraint++;
90940     }
90941     sqlite3DbFree(pParse->db, zAff);
90942
90943     /* Top of the loop body */
90944     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
90945
90946     /* Check if the index cursor is past the end of the range. */
90947     op = aEndOp[(pRangeEnd || nEq) * (1 + bRev)];
90948     testcase( op==OP_Noop );
90949     testcase( op==OP_IdxGE );
90950     testcase( op==OP_IdxLT );
90951     if( op!=OP_Noop ){
90952       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
90953       sqlite3VdbeChangeP5(v, endEq!=bRev ?1:0);
90954     }
90955
90956     /* If there are inequality constraints, check that the value
90957     ** of the table column that the inequality contrains is not NULL.
90958     ** If it is, jump to the next iteration of the loop.
90959     */
90960     r1 = sqlite3GetTempReg(pParse);
90961     testcase( pLevel->plan.wsFlags & WHERE_BTM_LIMIT );
90962     testcase( pLevel->plan.wsFlags & WHERE_TOP_LIMIT );
90963     if( pLevel->plan.wsFlags & (WHERE_BTM_LIMIT|WHERE_TOP_LIMIT) ){
90964       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, nEq, r1);
90965       sqlite3VdbeAddOp2(v, OP_IsNull, r1, addrCont);
90966     }
90967     sqlite3ReleaseTempReg(pParse, r1);
90968
90969     /* Seek the table cursor, if required */
90970     disableTerm(pLevel, pRangeStart);
90971     disableTerm(pLevel, pRangeEnd);
90972     if( !omitTable ){
90973       iRowidReg = iReleaseReg = sqlite3GetTempReg(pParse);
90974       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
90975       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
90976       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
90977     }
90978
90979     /* Record the instruction used to terminate the loop. Disable 
90980     ** WHERE clause terms made redundant by the index range scan.
90981     */
90982     pLevel->op = bRev ? OP_Prev : OP_Next;
90983     pLevel->p1 = iIdxCur;
90984   }else
90985
90986 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
90987   if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
90988     /* Case 4:  Two or more separately indexed terms connected by OR
90989     **
90990     ** Example:
90991     **
90992     **   CREATE TABLE t1(a,b,c,d);
90993     **   CREATE INDEX i1 ON t1(a);
90994     **   CREATE INDEX i2 ON t1(b);
90995     **   CREATE INDEX i3 ON t1(c);
90996     **
90997     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
90998     **
90999     ** In the example, there are three indexed terms connected by OR.
91000     ** The top of the loop looks like this:
91001     **
91002     **          Null       1                # Zero the rowset in reg 1
91003     **
91004     ** Then, for each indexed term, the following. The arguments to
91005     ** RowSetTest are such that the rowid of the current row is inserted
91006     ** into the RowSet. If it is already present, control skips the
91007     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
91008     **
91009     **        sqlite3WhereBegin(<term>)
91010     **          RowSetTest                  # Insert rowid into rowset
91011     **          Gosub      2 A
91012     **        sqlite3WhereEnd()
91013     **
91014     ** Following the above, code to terminate the loop. Label A, the target
91015     ** of the Gosub above, jumps to the instruction right after the Goto.
91016     **
91017     **          Null       1                # Zero the rowset in reg 1
91018     **          Goto       B                # The loop is finished.
91019     **
91020     **       A: <loop body>                 # Return data, whatever.
91021     **
91022     **          Return     2                # Jump back to the Gosub
91023     **
91024     **       B: <after the loop>
91025     **
91026     */
91027     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
91028     WhereTerm *pFinal;     /* Final subterm within the OR-clause. */
91029     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
91030
91031     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
91032     int regRowset = 0;                        /* Register for RowSet object */
91033     int regRowid = 0;                         /* Register holding rowid */
91034     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
91035     int iRetInit;                             /* Address of regReturn init */
91036     int untestedTerms = 0;             /* Some terms not completely tested */
91037     int ii;
91038    
91039     pTerm = pLevel->plan.u.pTerm;
91040     assert( pTerm!=0 );
91041     assert( pTerm->eOperator==WO_OR );
91042     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
91043     pOrWc = &pTerm->u.pOrInfo->wc;
91044     pFinal = &pOrWc->a[pOrWc->nTerm-1];
91045     pLevel->op = OP_Return;
91046     pLevel->p1 = regReturn;
91047
91048     /* Set up a new SrcList ni pOrTab containing the table being scanned
91049     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
91050     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
91051     */
91052     if( pWInfo->nLevel>1 ){
91053       int nNotReady;                 /* The number of notReady tables */
91054       struct SrcList_item *origSrc;     /* Original list of tables */
91055       nNotReady = pWInfo->nLevel - iLevel - 1;
91056       pOrTab = sqlite3StackAllocRaw(pParse->db,
91057                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
91058       if( pOrTab==0 ) return notReady;
91059       pOrTab->nAlloc = (i16)(nNotReady + 1);
91060       pOrTab->nSrc = pOrTab->nAlloc;
91061       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
91062       origSrc = pWInfo->pTabList->a;
91063       for(k=1; k<=nNotReady; k++){
91064         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
91065       }
91066     }else{
91067       pOrTab = pWInfo->pTabList;
91068     }
91069
91070     /* Initialize the rowset register to contain NULL. An SQL NULL is 
91071     ** equivalent to an empty rowset.
91072     **
91073     ** Also initialize regReturn to contain the address of the instruction 
91074     ** immediately following the OP_Return at the bottom of the loop. This
91075     ** is required in a few obscure LEFT JOIN cases where control jumps
91076     ** over the top of the loop into the body of it. In this case the 
91077     ** correct response for the end-of-loop code (the OP_Return) is to 
91078     ** fall through to the next instruction, just as an OP_Next does if
91079     ** called on an uninitialized cursor.
91080     */
91081     if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
91082       regRowset = ++pParse->nMem;
91083       regRowid = ++pParse->nMem;
91084       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
91085     }
91086     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
91087
91088     for(ii=0; ii<pOrWc->nTerm; ii++){
91089       WhereTerm *pOrTerm = &pOrWc->a[ii];
91090       if( pOrTerm->leftCursor==iCur || pOrTerm->eOperator==WO_AND ){
91091         WhereInfo *pSubWInfo;          /* Info for single OR-term scan */
91092         /* Loop through table entries that match term pOrTerm. */
91093         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrTerm->pExpr, 0,
91094                         WHERE_OMIT_OPEN | WHERE_OMIT_CLOSE |
91095                         WHERE_FORCE_TABLE | WHERE_ONETABLE_ONLY);
91096         if( pSubWInfo ){
91097           if( (wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
91098             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
91099             int r;
91100             r = sqlite3ExprCodeGetColumn(pParse, pTabItem->pTab, -1, iCur, 
91101                                          regRowid);
91102             sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset,
91103                                  sqlite3VdbeCurrentAddr(v)+2, r, iSet);
91104           }
91105           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
91106
91107           /* The pSubWInfo->untestedTerms flag means that this OR term
91108           ** contained one or more AND term from a notReady table.  The
91109           ** terms from the notReady table could not be tested and will
91110           ** need to be tested later.
91111           */
91112           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
91113
91114           /* Finish the loop through table entries that match term pOrTerm. */
91115           sqlite3WhereEnd(pSubWInfo);
91116         }
91117       }
91118     }
91119     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
91120     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
91121     sqlite3VdbeResolveLabel(v, iLoopBody);
91122
91123     if( pWInfo->nLevel>1 ) sqlite3StackFree(pParse->db, pOrTab);
91124     if( !untestedTerms ) disableTerm(pLevel, pTerm);
91125   }else
91126 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
91127
91128   {
91129     /* Case 5:  There is no usable index.  We must do a complete
91130     **          scan of the entire table.
91131     */
91132     static const u8 aStep[] = { OP_Next, OP_Prev };
91133     static const u8 aStart[] = { OP_Rewind, OP_Last };
91134     assert( bRev==0 || bRev==1 );
91135     assert( omitTable==0 );
91136     pLevel->op = aStep[bRev];
91137     pLevel->p1 = iCur;
91138     pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
91139     pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
91140   }
91141   notReady &= ~getMask(pWC->pMaskSet, iCur);
91142
91143   /* Insert code to test every subexpression that can be completely
91144   ** computed using the current set of tables.
91145   */
91146   k = 0;
91147   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
91148     Expr *pE;
91149     testcase( pTerm->wtFlags & TERM_VIRTUAL );
91150     testcase( pTerm->wtFlags & TERM_CODED );
91151     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
91152     if( (pTerm->prereqAll & notReady)!=0 ){
91153       testcase( pWInfo->untestedTerms==0
91154                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
91155       pWInfo->untestedTerms = 1;
91156       continue;
91157     }
91158     pE = pTerm->pExpr;
91159     assert( pE!=0 );
91160     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
91161       continue;
91162     }
91163     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
91164     k = 1;
91165     pTerm->wtFlags |= TERM_CODED;
91166   }
91167
91168   /* For a LEFT OUTER JOIN, generate code that will record the fact that
91169   ** at least one row of the right table has matched the left table.  
91170   */
91171   if( pLevel->iLeftJoin ){
91172     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
91173     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
91174     VdbeComment((v, "record LEFT JOIN hit"));
91175     sqlite3ExprCacheClear(pParse);
91176     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
91177       testcase( pTerm->wtFlags & TERM_VIRTUAL );
91178       testcase( pTerm->wtFlags & TERM_CODED );
91179       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
91180       if( (pTerm->prereqAll & notReady)!=0 ){
91181         assert( pWInfo->untestedTerms );
91182         continue;
91183       }
91184       assert( pTerm->pExpr );
91185       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
91186       pTerm->wtFlags |= TERM_CODED;
91187     }
91188   }
91189   sqlite3ReleaseTempReg(pParse, iReleaseReg);
91190
91191   return notReady;
91192 }
91193
91194 #if defined(SQLITE_TEST)
91195 /*
91196 ** The following variable holds a text description of query plan generated
91197 ** by the most recent call to sqlite3WhereBegin().  Each call to WhereBegin
91198 ** overwrites the previous.  This information is used for testing and
91199 ** analysis only.
91200 */
91201 SQLITE_API char sqlite3_query_plan[BMS*2*40];  /* Text of the join */
91202 static int nQPlan = 0;              /* Next free slow in _query_plan[] */
91203
91204 #endif /* SQLITE_TEST */
91205
91206
91207 /*
91208 ** Free a WhereInfo structure
91209 */
91210 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
91211   if( pWInfo ){
91212     int i;
91213     for(i=0; i<pWInfo->nLevel; i++){
91214       sqlite3_index_info *pInfo = pWInfo->a[i].pIdxInfo;
91215       if( pInfo ){
91216         /* assert( pInfo->needToFreeIdxStr==0 || db->mallocFailed ); */
91217         if( pInfo->needToFreeIdxStr ){
91218           sqlite3_free(pInfo->idxStr);
91219         }
91220         sqlite3DbFree(db, pInfo);
91221       }
91222     }
91223     whereClauseClear(pWInfo->pWC);
91224     sqlite3DbFree(db, pWInfo);
91225   }
91226 }
91227
91228
91229 /*
91230 ** Generate the beginning of the loop used for WHERE clause processing.
91231 ** The return value is a pointer to an opaque structure that contains
91232 ** information needed to terminate the loop.  Later, the calling routine
91233 ** should invoke sqlite3WhereEnd() with the return value of this function
91234 ** in order to complete the WHERE clause processing.
91235 **
91236 ** If an error occurs, this routine returns NULL.
91237 **
91238 ** The basic idea is to do a nested loop, one loop for each table in
91239 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
91240 ** same as a SELECT with only a single table in the FROM clause.)  For
91241 ** example, if the SQL is this:
91242 **
91243 **       SELECT * FROM t1, t2, t3 WHERE ...;
91244 **
91245 ** Then the code generated is conceptually like the following:
91246 **
91247 **      foreach row1 in t1 do       \    Code generated
91248 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
91249 **          foreach row3 in t3 do   /
91250 **            ...
91251 **          end                     \    Code generated
91252 **        end                        |-- by sqlite3WhereEnd()
91253 **      end                         /
91254 **
91255 ** Note that the loops might not be nested in the order in which they
91256 ** appear in the FROM clause if a different order is better able to make
91257 ** use of indices.  Note also that when the IN operator appears in
91258 ** the WHERE clause, it might result in additional nested loops for
91259 ** scanning through all values on the right-hand side of the IN.
91260 **
91261 ** There are Btree cursors associated with each table.  t1 uses cursor
91262 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
91263 ** And so forth.  This routine generates code to open those VDBE cursors
91264 ** and sqlite3WhereEnd() generates the code to close them.
91265 **
91266 ** The code that sqlite3WhereBegin() generates leaves the cursors named
91267 ** in pTabList pointing at their appropriate entries.  The [...] code
91268 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
91269 ** data from the various tables of the loop.
91270 **
91271 ** If the WHERE clause is empty, the foreach loops must each scan their
91272 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
91273 ** the tables have indices and there are terms in the WHERE clause that
91274 ** refer to those indices, a complete table scan can be avoided and the
91275 ** code will run much faster.  Most of the work of this routine is checking
91276 ** to see if there are indices that can be used to speed up the loop.
91277 **
91278 ** Terms of the WHERE clause are also used to limit which rows actually
91279 ** make it to the "..." in the middle of the loop.  After each "foreach",
91280 ** terms of the WHERE clause that use only terms in that loop and outer
91281 ** loops are evaluated and if false a jump is made around all subsequent
91282 ** inner loops (or around the "..." if the test occurs within the inner-
91283 ** most loop)
91284 **
91285 ** OUTER JOINS
91286 **
91287 ** An outer join of tables t1 and t2 is conceptally coded as follows:
91288 **
91289 **    foreach row1 in t1 do
91290 **      flag = 0
91291 **      foreach row2 in t2 do
91292 **        start:
91293 **          ...
91294 **          flag = 1
91295 **      end
91296 **      if flag==0 then
91297 **        move the row2 cursor to a null row
91298 **        goto start
91299 **      fi
91300 **    end
91301 **
91302 ** ORDER BY CLAUSE PROCESSING
91303 **
91304 ** *ppOrderBy is a pointer to the ORDER BY clause of a SELECT statement,
91305 ** if there is one.  If there is no ORDER BY clause or if this routine
91306 ** is called from an UPDATE or DELETE statement, then ppOrderBy is NULL.
91307 **
91308 ** If an index can be used so that the natural output order of the table
91309 ** scan is correct for the ORDER BY clause, then that index is used and
91310 ** *ppOrderBy is set to NULL.  This is an optimization that prevents an
91311 ** unnecessary sort of the result set if an index appropriate for the
91312 ** ORDER BY clause already exists.
91313 **
91314 ** If the where clause loops cannot be arranged to provide the correct
91315 ** output order, then the *ppOrderBy is unchanged.
91316 */
91317 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
91318   Parse *pParse,        /* The parser context */
91319   SrcList *pTabList,    /* A list of all tables to be scanned */
91320   Expr *pWhere,         /* The WHERE clause */
91321   ExprList **ppOrderBy, /* An ORDER BY clause, or NULL */
91322   u16 wctrlFlags        /* One of the WHERE_* flags defined in sqliteInt.h */
91323 ){
91324   int i;                     /* Loop counter */
91325   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
91326   int nTabList;              /* Number of elements in pTabList */
91327   WhereInfo *pWInfo;         /* Will become the return value of this function */
91328   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
91329   Bitmask notReady;          /* Cursors that are not yet positioned */
91330   WhereMaskSet *pMaskSet;    /* The expression mask set */
91331   WhereClause *pWC;               /* Decomposition of the WHERE clause */
91332   struct SrcList_item *pTabItem;  /* A single entry from pTabList */
91333   WhereLevel *pLevel;             /* A single level in the pWInfo list */
91334   int iFrom;                      /* First unused FROM clause element */
91335   int andFlags;              /* AND-ed combination of all pWC->a[].wtFlags */
91336   sqlite3 *db;               /* Database connection */
91337
91338   /* The number of tables in the FROM clause is limited by the number of
91339   ** bits in a Bitmask 
91340   */
91341   if( pTabList->nSrc>BMS ){
91342     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
91343     return 0;
91344   }
91345
91346   /* This function normally generates a nested loop for all tables in 
91347   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
91348   ** only generate code for the first table in pTabList and assume that
91349   ** any cursors associated with subsequent tables are uninitialized.
91350   */
91351   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
91352
91353   /* Allocate and initialize the WhereInfo structure that will become the
91354   ** return value. A single allocation is used to store the WhereInfo
91355   ** struct, the contents of WhereInfo.a[], the WhereClause structure
91356   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
91357   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
91358   ** some architectures. Hence the ROUND8() below.
91359   */
91360   db = pParse->db;
91361   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
91362   pWInfo = sqlite3DbMallocZero(db, 
91363       nByteWInfo + 
91364       sizeof(WhereClause) +
91365       sizeof(WhereMaskSet)
91366   );
91367   if( db->mallocFailed ){
91368     goto whereBeginError;
91369   }
91370   pWInfo->nLevel = nTabList;
91371   pWInfo->pParse = pParse;
91372   pWInfo->pTabList = pTabList;
91373   pWInfo->iBreak = sqlite3VdbeMakeLabel(v);
91374   pWInfo->pWC = pWC = (WhereClause *)&((u8 *)pWInfo)[nByteWInfo];
91375   pWInfo->wctrlFlags = wctrlFlags;
91376   pMaskSet = (WhereMaskSet*)&pWC[1];
91377
91378   /* Split the WHERE clause into separate subexpressions where each
91379   ** subexpression is separated by an AND operator.
91380   */
91381   initMaskSet(pMaskSet);
91382   whereClauseInit(pWC, pParse, pMaskSet);
91383   sqlite3ExprCodeConstants(pParse, pWhere);
91384   whereSplit(pWC, pWhere, TK_AND);
91385     
91386   /* Special case: a WHERE clause that is constant.  Evaluate the
91387   ** expression and either jump over all of the code or fall thru.
91388   */
91389   if( pWhere && (nTabList==0 || sqlite3ExprIsConstantNotJoin(pWhere)) ){
91390     sqlite3ExprIfFalse(pParse, pWhere, pWInfo->iBreak, SQLITE_JUMPIFNULL);
91391     pWhere = 0;
91392   }
91393
91394   /* Assign a bit from the bitmask to every term in the FROM clause.
91395   **
91396   ** When assigning bitmask values to FROM clause cursors, it must be
91397   ** the case that if X is the bitmask for the N-th FROM clause term then
91398   ** the bitmask for all FROM clause terms to the left of the N-th term
91399   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
91400   ** its Expr.iRightJoinTable value to find the bitmask of the right table
91401   ** of the join.  Subtracting one from the right table bitmask gives a
91402   ** bitmask for all tables to the left of the join.  Knowing the bitmask
91403   ** for all tables to the left of a left join is important.  Ticket #3015.
91404   **
91405   ** Configure the WhereClause.vmask variable so that bits that correspond
91406   ** to virtual table cursors are set. This is used to selectively disable 
91407   ** the OR-to-IN transformation in exprAnalyzeOrTerm(). It is not helpful 
91408   ** with virtual tables.
91409   **
91410   ** Note that bitmasks are created for all pTabList->nSrc tables in
91411   ** pTabList, not just the first nTabList tables.  nTabList is normally
91412   ** equal to pTabList->nSrc but might be shortened to 1 if the
91413   ** WHERE_ONETABLE_ONLY flag is set.
91414   */
91415   assert( pWC->vmask==0 && pMaskSet->n==0 );
91416   for(i=0; i<pTabList->nSrc; i++){
91417     createMask(pMaskSet, pTabList->a[i].iCursor);
91418 #ifndef SQLITE_OMIT_VIRTUALTABLE
91419     if( ALWAYS(pTabList->a[i].pTab) && IsVirtual(pTabList->a[i].pTab) ){
91420       pWC->vmask |= ((Bitmask)1 << i);
91421     }
91422 #endif
91423   }
91424 #ifndef NDEBUG
91425   {
91426     Bitmask toTheLeft = 0;
91427     for(i=0; i<pTabList->nSrc; i++){
91428       Bitmask m = getMask(pMaskSet, pTabList->a[i].iCursor);
91429       assert( (m-1)==toTheLeft );
91430       toTheLeft |= m;
91431     }
91432   }
91433 #endif
91434
91435   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
91436   ** add new virtual terms onto the end of the WHERE clause.  We do not
91437   ** want to analyze these virtual terms, so start analyzing at the end
91438   ** and work forward so that the added virtual terms are never processed.
91439   */
91440   exprAnalyzeAll(pTabList, pWC);
91441   if( db->mallocFailed ){
91442     goto whereBeginError;
91443   }
91444
91445   /* Chose the best index to use for each table in the FROM clause.
91446   **
91447   ** This loop fills in the following fields:
91448   **
91449   **   pWInfo->a[].pIdx      The index to use for this level of the loop.
91450   **   pWInfo->a[].wsFlags   WHERE_xxx flags associated with pIdx
91451   **   pWInfo->a[].nEq       The number of == and IN constraints
91452   **   pWInfo->a[].iFrom     Which term of the FROM clause is being coded
91453   **   pWInfo->a[].iTabCur   The VDBE cursor for the database table
91454   **   pWInfo->a[].iIdxCur   The VDBE cursor for the index
91455   **   pWInfo->a[].pTerm     When wsFlags==WO_OR, the OR-clause term
91456   **
91457   ** This loop also figures out the nesting order of tables in the FROM
91458   ** clause.
91459   */
91460   notReady = ~(Bitmask)0;
91461   pTabItem = pTabList->a;
91462   pLevel = pWInfo->a;
91463   andFlags = ~0;
91464   WHERETRACE(("*** Optimizer Start ***\n"));
91465   for(i=iFrom=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
91466     WhereCost bestPlan;         /* Most efficient plan seen so far */
91467     Index *pIdx;                /* Index for FROM table at pTabItem */
91468     int j;                      /* For looping over FROM tables */
91469     int bestJ = -1;             /* The value of j */
91470     Bitmask m;                  /* Bitmask value for j or bestJ */
91471     int isOptimal;              /* Iterator for optimal/non-optimal search */
91472
91473     memset(&bestPlan, 0, sizeof(bestPlan));
91474     bestPlan.rCost = SQLITE_BIG_DBL;
91475
91476     /* Loop through the remaining entries in the FROM clause to find the
91477     ** next nested loop. The FROM clause entries may be iterated through
91478     ** either once or twice. 
91479     **
91480     ** The first iteration, which is always performed, searches for the
91481     ** FROM clause entry that permits the lowest-cost, "optimal" scan. In
91482     ** this context an optimal scan is one that uses the same strategy
91483     ** for the given FROM clause entry as would be selected if the entry
91484     ** were used as the innermost nested loop.  In other words, a table
91485     ** is chosen such that the cost of running that table cannot be reduced
91486     ** by waiting for other tables to run first.
91487     **
91488     ** The second iteration is only performed if no optimal scan strategies
91489     ** were found by the first. This iteration is used to search for the
91490     ** lowest cost scan overall.
91491     **
91492     ** Previous versions of SQLite performed only the second iteration -
91493     ** the next outermost loop was always that with the lowest overall
91494     ** cost. However, this meant that SQLite could select the wrong plan
91495     ** for scripts such as the following:
91496     **   
91497     **   CREATE TABLE t1(a, b); 
91498     **   CREATE TABLE t2(c, d);
91499     **   SELECT * FROM t2, t1 WHERE t2.rowid = t1.a;
91500     **
91501     ** The best strategy is to iterate through table t1 first. However it
91502     ** is not possible to determine this with a simple greedy algorithm.
91503     ** However, since the cost of a linear scan through table t2 is the same 
91504     ** as the cost of a linear scan through table t1, a simple greedy 
91505     ** algorithm may choose to use t2 for the outer loop, which is a much
91506     ** costlier approach.
91507     */
91508     for(isOptimal=1; isOptimal>=0 && bestJ<0; isOptimal--){
91509       Bitmask mask = (isOptimal ? 0 : notReady);
91510       assert( (nTabList-iFrom)>1 || isOptimal );
91511       for(j=iFrom, pTabItem=&pTabList->a[j]; j<nTabList; j++, pTabItem++){
91512         int doNotReorder;    /* True if this table should not be reordered */
91513         WhereCost sCost;     /* Cost information from best[Virtual]Index() */
91514         ExprList *pOrderBy;  /* ORDER BY clause for index to optimize */
91515   
91516         doNotReorder =  (pTabItem->jointype & (JT_LEFT|JT_CROSS))!=0;
91517         if( j!=iFrom && doNotReorder ) break;
91518         m = getMask(pMaskSet, pTabItem->iCursor);
91519         if( (m & notReady)==0 ){
91520           if( j==iFrom ) iFrom++;
91521           continue;
91522         }
91523         pOrderBy = ((i==0 && ppOrderBy )?*ppOrderBy:0);
91524   
91525         assert( pTabItem->pTab );
91526 #ifndef SQLITE_OMIT_VIRTUALTABLE
91527         if( IsVirtual(pTabItem->pTab) ){
91528           sqlite3_index_info **pp = &pWInfo->a[j].pIdxInfo;
91529           bestVirtualIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost, pp);
91530         }else 
91531 #endif
91532         {
91533           bestBtreeIndex(pParse, pWC, pTabItem, mask, pOrderBy, &sCost);
91534         }
91535         assert( isOptimal || (sCost.used&notReady)==0 );
91536
91537         if( (sCost.used&notReady)==0
91538          && (j==iFrom || sCost.rCost<bestPlan.rCost) 
91539         ){
91540           bestPlan = sCost;
91541           bestJ = j;
91542         }
91543         if( doNotReorder ) break;
91544       }
91545     }
91546     assert( bestJ>=0 );
91547     assert( notReady & getMask(pMaskSet, pTabList->a[bestJ].iCursor) );
91548     WHERETRACE(("*** Optimizer selects table %d for loop %d\n", bestJ,
91549            pLevel-pWInfo->a));
91550     if( (bestPlan.plan.wsFlags & WHERE_ORDERBY)!=0 ){
91551       *ppOrderBy = 0;
91552     }
91553     andFlags &= bestPlan.plan.wsFlags;
91554     pLevel->plan = bestPlan.plan;
91555     if( bestPlan.plan.wsFlags & WHERE_INDEXED ){
91556       pLevel->iIdxCur = pParse->nTab++;
91557     }else{
91558       pLevel->iIdxCur = -1;
91559     }
91560     notReady &= ~getMask(pMaskSet, pTabList->a[bestJ].iCursor);
91561     pLevel->iFrom = (u8)bestJ;
91562
91563     /* Check that if the table scanned by this loop iteration had an
91564     ** INDEXED BY clause attached to it, that the named index is being
91565     ** used for the scan. If not, then query compilation has failed.
91566     ** Return an error.
91567     */
91568     pIdx = pTabList->a[bestJ].pIndex;
91569     if( pIdx ){
91570       if( (bestPlan.plan.wsFlags & WHERE_INDEXED)==0 ){
91571         sqlite3ErrorMsg(pParse, "cannot use index: %s", pIdx->zName);
91572         goto whereBeginError;
91573       }else{
91574         /* If an INDEXED BY clause is used, the bestIndex() function is
91575         ** guaranteed to find the index specified in the INDEXED BY clause
91576         ** if it find an index at all. */
91577         assert( bestPlan.plan.u.pIdx==pIdx );
91578       }
91579     }
91580   }
91581   WHERETRACE(("*** Optimizer Finished ***\n"));
91582   if( pParse->nErr || db->mallocFailed ){
91583     goto whereBeginError;
91584   }
91585
91586   /* If the total query only selects a single row, then the ORDER BY
91587   ** clause is irrelevant.
91588   */
91589   if( (andFlags & WHERE_UNIQUE)!=0 && ppOrderBy ){
91590     *ppOrderBy = 0;
91591   }
91592
91593   /* If the caller is an UPDATE or DELETE statement that is requesting
91594   ** to use a one-pass algorithm, determine if this is appropriate.
91595   ** The one-pass algorithm only works if the WHERE clause constraints
91596   ** the statement to update a single row.
91597   */
91598   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
91599   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 && (andFlags & WHERE_UNIQUE)!=0 ){
91600     pWInfo->okOnePass = 1;
91601     pWInfo->a[0].plan.wsFlags &= ~WHERE_IDX_ONLY;
91602   }
91603
91604   /* Open all tables in the pTabList and any indices selected for
91605   ** searching those tables.
91606   */
91607   sqlite3CodeVerifySchema(pParse, -1); /* Insert the cookie verifier Goto */
91608   for(i=0, pLevel=pWInfo->a; i<nTabList; i++, pLevel++){
91609     Table *pTab;     /* Table to open */
91610     int iDb;         /* Index of database containing table/index */
91611
91612 #ifndef SQLITE_OMIT_EXPLAIN
91613     if( pParse->explain==2 ){
91614       char *zMsg;
91615       struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
91616       zMsg = sqlite3MPrintf(db, "TABLE %s", pItem->zName);
91617       if( pItem->zAlias ){
91618         zMsg = sqlite3MAppendf(db, zMsg, "%s AS %s", zMsg, pItem->zAlias);
91619       }
91620       if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
91621         zMsg = sqlite3MAppendf(db, zMsg, "%s WITH INDEX %s",
91622            zMsg, pLevel->plan.u.pIdx->zName);
91623       }else if( pLevel->plan.wsFlags & WHERE_MULTI_OR ){
91624         zMsg = sqlite3MAppendf(db, zMsg, "%s VIA MULTI-INDEX UNION", zMsg);
91625       }else if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
91626         zMsg = sqlite3MAppendf(db, zMsg, "%s USING PRIMARY KEY", zMsg);
91627       }
91628 #ifndef SQLITE_OMIT_VIRTUALTABLE
91629       else if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
91630         sqlite3_index_info *pVtabIdx = pLevel->plan.u.pVtabIdx;
91631         zMsg = sqlite3MAppendf(db, zMsg, "%s VIRTUAL TABLE INDEX %d:%s", zMsg,
91632                     pVtabIdx->idxNum, pVtabIdx->idxStr);
91633       }
91634 #endif
91635       if( pLevel->plan.wsFlags & WHERE_ORDERBY ){
91636         zMsg = sqlite3MAppendf(db, zMsg, "%s ORDER BY", zMsg);
91637       }
91638       sqlite3VdbeAddOp4(v, OP_Explain, i, pLevel->iFrom, 0, zMsg, P4_DYNAMIC);
91639     }
91640 #endif /* SQLITE_OMIT_EXPLAIN */
91641     pTabItem = &pTabList->a[pLevel->iFrom];
91642     pTab = pTabItem->pTab;
91643     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
91644     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
91645 #ifndef SQLITE_OMIT_VIRTUALTABLE
91646     if( (pLevel->plan.wsFlags & WHERE_VIRTUALTABLE)!=0 ){
91647       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
91648       int iCur = pTabItem->iCursor;
91649       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
91650     }else
91651 #endif
91652     if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
91653          && (wctrlFlags & WHERE_OMIT_OPEN)==0 ){
91654       int op = pWInfo->okOnePass ? OP_OpenWrite : OP_OpenRead;
91655       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
91656       if( !pWInfo->okOnePass && pTab->nCol<BMS ){
91657         Bitmask b = pTabItem->colUsed;
91658         int n = 0;
91659         for(; b; b=b>>1, n++){}
91660         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, 
91661                             SQLITE_INT_TO_PTR(n), P4_INT32);
91662         assert( n<=pTab->nCol );
91663       }
91664     }else{
91665       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
91666     }
91667     pLevel->iTabCur = pTabItem->iCursor;
91668     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
91669       Index *pIx = pLevel->plan.u.pIdx;
91670       KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIx);
91671       int iIdxCur = pLevel->iIdxCur;
91672       assert( pIx->pSchema==pTab->pSchema );
91673       assert( iIdxCur>=0 );
91674       sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIx->tnum, iDb,
91675                         (char*)pKey, P4_KEYINFO_HANDOFF);
91676       VdbeComment((v, "%s", pIx->zName));
91677     }
91678     sqlite3CodeVerifySchema(pParse, iDb);
91679   }
91680   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
91681
91682   /* Generate the code to do the search.  Each iteration of the for
91683   ** loop below generates code for a single nested loop of the VM
91684   ** program.
91685   */
91686   notReady = ~(Bitmask)0;
91687   for(i=0; i<nTabList; i++){
91688     notReady = codeOneLoopStart(pWInfo, i, wctrlFlags, notReady);
91689     pWInfo->iContinue = pWInfo->a[i].addrCont;
91690   }
91691
91692 #ifdef SQLITE_TEST  /* For testing and debugging use only */
91693   /* Record in the query plan information about the current table
91694   ** and the index used to access it (if any).  If the table itself
91695   ** is not used, its name is just '{}'.  If no index is used
91696   ** the index is listed as "{}".  If the primary key is used the
91697   ** index name is '*'.
91698   */
91699   for(i=0; i<nTabList; i++){
91700     char *z;
91701     int n;
91702     pLevel = &pWInfo->a[i];
91703     pTabItem = &pTabList->a[pLevel->iFrom];
91704     z = pTabItem->zAlias;
91705     if( z==0 ) z = pTabItem->pTab->zName;
91706     n = sqlite3Strlen30(z);
91707     if( n+nQPlan < sizeof(sqlite3_query_plan)-10 ){
91708       if( pLevel->plan.wsFlags & WHERE_IDX_ONLY ){
91709         memcpy(&sqlite3_query_plan[nQPlan], "{}", 2);
91710         nQPlan += 2;
91711       }else{
91712         memcpy(&sqlite3_query_plan[nQPlan], z, n);
91713         nQPlan += n;
91714       }
91715       sqlite3_query_plan[nQPlan++] = ' ';
91716     }
91717     testcase( pLevel->plan.wsFlags & WHERE_ROWID_EQ );
91718     testcase( pLevel->plan.wsFlags & WHERE_ROWID_RANGE );
91719     if( pLevel->plan.wsFlags & (WHERE_ROWID_EQ|WHERE_ROWID_RANGE) ){
91720       memcpy(&sqlite3_query_plan[nQPlan], "* ", 2);
91721       nQPlan += 2;
91722     }else if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
91723       n = sqlite3Strlen30(pLevel->plan.u.pIdx->zName);
91724       if( n+nQPlan < sizeof(sqlite3_query_plan)-2 ){
91725         memcpy(&sqlite3_query_plan[nQPlan], pLevel->plan.u.pIdx->zName, n);
91726         nQPlan += n;
91727         sqlite3_query_plan[nQPlan++] = ' ';
91728       }
91729     }else{
91730       memcpy(&sqlite3_query_plan[nQPlan], "{} ", 3);
91731       nQPlan += 3;
91732     }
91733   }
91734   while( nQPlan>0 && sqlite3_query_plan[nQPlan-1]==' ' ){
91735     sqlite3_query_plan[--nQPlan] = 0;
91736   }
91737   sqlite3_query_plan[nQPlan] = 0;
91738   nQPlan = 0;
91739 #endif /* SQLITE_TEST // Testing and debugging use only */
91740
91741   /* Record the continuation address in the WhereInfo structure.  Then
91742   ** clean up and return.
91743   */
91744   return pWInfo;
91745
91746   /* Jump here if malloc fails */
91747 whereBeginError:
91748   whereInfoFree(db, pWInfo);
91749   return 0;
91750 }
91751
91752 /*
91753 ** Generate the end of the WHERE loop.  See comments on 
91754 ** sqlite3WhereBegin() for additional information.
91755 */
91756 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
91757   Parse *pParse = pWInfo->pParse;
91758   Vdbe *v = pParse->pVdbe;
91759   int i;
91760   WhereLevel *pLevel;
91761   SrcList *pTabList = pWInfo->pTabList;
91762   sqlite3 *db = pParse->db;
91763
91764   /* Generate loop termination code.
91765   */
91766   sqlite3ExprCacheClear(pParse);
91767   for(i=pWInfo->nLevel-1; i>=0; i--){
91768     pLevel = &pWInfo->a[i];
91769     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
91770     if( pLevel->op!=OP_Noop ){
91771       sqlite3VdbeAddOp2(v, pLevel->op, pLevel->p1, pLevel->p2);
91772       sqlite3VdbeChangeP5(v, pLevel->p5);
91773     }
91774     if( pLevel->plan.wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
91775       struct InLoop *pIn;
91776       int j;
91777       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
91778       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
91779         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
91780         sqlite3VdbeAddOp2(v, OP_Next, pIn->iCur, pIn->addrInTop);
91781         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
91782       }
91783       sqlite3DbFree(db, pLevel->u.in.aInLoop);
91784     }
91785     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
91786     if( pLevel->iLeftJoin ){
91787       int addr;
91788       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin);
91789       assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
91790            || (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 );
91791       if( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
91792         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
91793       }
91794       if( pLevel->iIdxCur>=0 ){
91795         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
91796       }
91797       if( pLevel->op==OP_Return ){
91798         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
91799       }else{
91800         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
91801       }
91802       sqlite3VdbeJumpHere(v, addr);
91803     }
91804   }
91805
91806   /* The "break" point is here, just past the end of the outer loop.
91807   ** Set it.
91808   */
91809   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
91810
91811   /* Close all of the cursors that were opened by sqlite3WhereBegin.
91812   */
91813   assert( pWInfo->nLevel==1 || pWInfo->nLevel==pTabList->nSrc );
91814   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
91815     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
91816     Table *pTab = pTabItem->pTab;
91817     assert( pTab!=0 );
91818     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ) continue;
91819     if( (pWInfo->wctrlFlags & WHERE_OMIT_CLOSE)==0 ){
91820       if( !pWInfo->okOnePass && (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0 ){
91821         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
91822       }
91823       if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 ){
91824         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
91825       }
91826     }
91827
91828     /* If this scan uses an index, make code substitutions to read data
91829     ** from the index in preference to the table. Sometimes, this means
91830     ** the table need never be read from. This is a performance boost,
91831     ** as the vdbe level waits until the table is read before actually
91832     ** seeking the table cursor to the record corresponding to the current
91833     ** position in the index.
91834     ** 
91835     ** Calls to the code generator in between sqlite3WhereBegin and
91836     ** sqlite3WhereEnd will have created code that references the table
91837     ** directly.  This loop scans all that code looking for opcodes
91838     ** that reference the table and converts them into opcodes that
91839     ** reference the index.
91840     */
91841     if( (pLevel->plan.wsFlags & WHERE_INDEXED)!=0 && !db->mallocFailed){
91842       int k, j, last;
91843       VdbeOp *pOp;
91844       Index *pIdx = pLevel->plan.u.pIdx;
91845
91846       assert( pIdx!=0 );
91847       pOp = sqlite3VdbeGetOp(v, pWInfo->iTop);
91848       last = sqlite3VdbeCurrentAddr(v);
91849       for(k=pWInfo->iTop; k<last; k++, pOp++){
91850         if( pOp->p1!=pLevel->iTabCur ) continue;
91851         if( pOp->opcode==OP_Column ){
91852           for(j=0; j<pIdx->nColumn; j++){
91853             if( pOp->p2==pIdx->aiColumn[j] ){
91854               pOp->p2 = j;
91855               pOp->p1 = pLevel->iIdxCur;
91856               break;
91857             }
91858           }
91859           assert( (pLevel->plan.wsFlags & WHERE_IDX_ONLY)==0
91860                || j<pIdx->nColumn );
91861         }else if( pOp->opcode==OP_Rowid ){
91862           pOp->p1 = pLevel->iIdxCur;
91863           pOp->opcode = OP_IdxRowid;
91864         }
91865       }
91866     }
91867   }
91868
91869   /* Final cleanup
91870   */
91871   whereInfoFree(db, pWInfo);
91872   return;
91873 }
91874
91875 /************** End of where.c ***********************************************/
91876 /************** Begin file parse.c *******************************************/
91877 /* Driver template for the LEMON parser generator.
91878 ** The author disclaims copyright to this source code.
91879 **
91880 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
91881 ** The only modifications are the addition of a couple of NEVER()
91882 ** macros to disable tests that are needed in the case of a general
91883 ** LALR(1) grammar but which are always false in the
91884 ** specific grammar used by SQLite.
91885 */
91886 /* First off, code is included that follows the "include" declaration
91887 ** in the input grammar file. */
91888
91889
91890 /*
91891 ** Disable all error recovery processing in the parser push-down
91892 ** automaton.
91893 */
91894 #define YYNOERRORRECOVERY 1
91895
91896 /*
91897 ** Make yytestcase() the same as testcase()
91898 */
91899 #define yytestcase(X) testcase(X)
91900
91901 /*
91902 ** An instance of this structure holds information about the
91903 ** LIMIT clause of a SELECT statement.
91904 */
91905 struct LimitVal {
91906   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
91907   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
91908 };
91909
91910 /*
91911 ** An instance of this structure is used to store the LIKE,
91912 ** GLOB, NOT LIKE, and NOT GLOB operators.
91913 */
91914 struct LikeOp {
91915   Token eOperator;  /* "like" or "glob" or "regexp" */
91916   int not;         /* True if the NOT keyword is present */
91917 };
91918
91919 /*
91920 ** An instance of the following structure describes the event of a
91921 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
91922 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
91923 **
91924 **      UPDATE ON (a,b,c)
91925 **
91926 ** Then the "b" IdList records the list "a,b,c".
91927 */
91928 struct TrigEvent { int a; IdList * b; };
91929
91930 /*
91931 ** An instance of this structure holds the ATTACH key and the key type.
91932 */
91933 struct AttachKey { int type;  Token key; };
91934
91935
91936   /* This is a utility routine used to set the ExprSpan.zStart and
91937   ** ExprSpan.zEnd values of pOut so that the span covers the complete
91938   ** range of text beginning with pStart and going to the end of pEnd.
91939   */
91940   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
91941     pOut->zStart = pStart->z;
91942     pOut->zEnd = &pEnd->z[pEnd->n];
91943   }
91944
91945   /* Construct a new Expr object from a single identifier.  Use the
91946   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
91947   ** that created the expression.
91948   */
91949   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
91950     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
91951     pOut->zStart = pValue->z;
91952     pOut->zEnd = &pValue->z[pValue->n];
91953   }
91954
91955   /* This routine constructs a binary expression node out of two ExprSpan
91956   ** objects and uses the result to populate a new ExprSpan object.
91957   */
91958   static void spanBinaryExpr(
91959     ExprSpan *pOut,     /* Write the result here */
91960     Parse *pParse,      /* The parsing context.  Errors accumulate here */
91961     int op,             /* The binary operation */
91962     ExprSpan *pLeft,    /* The left operand */
91963     ExprSpan *pRight    /* The right operand */
91964   ){
91965     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
91966     pOut->zStart = pLeft->zStart;
91967     pOut->zEnd = pRight->zEnd;
91968   }
91969
91970   /* Construct an expression node for a unary postfix operator
91971   */
91972   static void spanUnaryPostfix(
91973     ExprSpan *pOut,        /* Write the new expression node here */
91974     Parse *pParse,         /* Parsing context to record errors */
91975     int op,                /* The operator */
91976     ExprSpan *pOperand,    /* The operand */
91977     Token *pPostOp         /* The operand token for setting the span */
91978   ){
91979     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
91980     pOut->zStart = pOperand->zStart;
91981     pOut->zEnd = &pPostOp->z[pPostOp->n];
91982   }                           
91983
91984   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
91985   ** unary TK_ISNULL or TK_NOTNULL expression. */
91986   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
91987     sqlite3 *db = pParse->db;
91988     if( db->mallocFailed==0 && pY->op==TK_NULL ){
91989       pA->op = (u8)op;
91990       sqlite3ExprDelete(db, pA->pRight);
91991       pA->pRight = 0;
91992     }
91993   }
91994
91995   /* Construct an expression node for a unary prefix operator
91996   */
91997   static void spanUnaryPrefix(
91998     ExprSpan *pOut,        /* Write the new expression node here */
91999     Parse *pParse,         /* Parsing context to record errors */
92000     int op,                /* The operator */
92001     ExprSpan *pOperand,    /* The operand */
92002     Token *pPreOp         /* The operand token for setting the span */
92003   ){
92004     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
92005     pOut->zStart = pPreOp->z;
92006     pOut->zEnd = pOperand->zEnd;
92007   }
92008 /* Next is all token values, in a form suitable for use by makeheaders.
92009 ** This section will be null unless lemon is run with the -m switch.
92010 */
92011 /* 
92012 ** These constants (all generated automatically by the parser generator)
92013 ** specify the various kinds of tokens (terminals) that the parser
92014 ** understands. 
92015 **
92016 ** Each symbol here is a terminal symbol in the grammar.
92017 */
92018 /* Make sure the INTERFACE macro is defined.
92019 */
92020 #ifndef INTERFACE
92021 # define INTERFACE 1
92022 #endif
92023 /* The next thing included is series of defines which control
92024 ** various aspects of the generated parser.
92025 **    YYCODETYPE         is the data type used for storing terminal
92026 **                       and nonterminal numbers.  "unsigned char" is
92027 **                       used if there are fewer than 250 terminals
92028 **                       and nonterminals.  "int" is used otherwise.
92029 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
92030 **                       to no legal terminal or nonterminal number.  This
92031 **                       number is used to fill in empty slots of the hash 
92032 **                       table.
92033 **    YYFALLBACK         If defined, this indicates that one or more tokens
92034 **                       have fall-back values which should be used if the
92035 **                       original value of the token will not parse.
92036 **    YYACTIONTYPE       is the data type used for storing terminal
92037 **                       and nonterminal numbers.  "unsigned char" is
92038 **                       used if there are fewer than 250 rules and
92039 **                       states combined.  "int" is used otherwise.
92040 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
92041 **                       directly to the parser from the tokenizer.
92042 **    YYMINORTYPE        is the data type used for all minor tokens.
92043 **                       This is typically a union of many types, one of
92044 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
92045 **                       for base tokens is called "yy0".
92046 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
92047 **                       zero the stack is dynamically sized using realloc()
92048 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
92049 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
92050 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
92051 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
92052 **    YYNSTATE           the combined number of states.
92053 **    YYNRULE            the number of rules in the grammar
92054 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
92055 **                       defined, then do no error processing.
92056 */
92057 #define YYCODETYPE unsigned char
92058 #define YYNOCODE 254
92059 #define YYACTIONTYPE unsigned short int
92060 #define YYWILDCARD 67
92061 #define sqlite3ParserTOKENTYPE Token
92062 typedef union {
92063   int yyinit;
92064   sqlite3ParserTOKENTYPE yy0;
92065   Select* yy3;
92066   ExprList* yy14;
92067   SrcList* yy65;
92068   struct LikeOp yy96;
92069   Expr* yy132;
92070   u8 yy186;
92071   int yy328;
92072   ExprSpan yy346;
92073   struct TrigEvent yy378;
92074   IdList* yy408;
92075   struct {int value; int mask;} yy429;
92076   TriggerStep* yy473;
92077   struct LimitVal yy476;
92078 } YYMINORTYPE;
92079 #ifndef YYSTACKDEPTH
92080 #define YYSTACKDEPTH 100
92081 #endif
92082 #define sqlite3ParserARG_SDECL Parse *pParse;
92083 #define sqlite3ParserARG_PDECL ,Parse *pParse
92084 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
92085 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
92086 #define YYNSTATE 631
92087 #define YYNRULE 330
92088 #define YYFALLBACK 1
92089 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
92090 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
92091 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
92092
92093 /* The yyzerominor constant is used to initialize instances of
92094 ** YYMINORTYPE objects to zero. */
92095 static const YYMINORTYPE yyzerominor = { 0 };
92096
92097 /* Define the yytestcase() macro to be a no-op if is not already defined
92098 ** otherwise.
92099 **
92100 ** Applications can choose to define yytestcase() in the %include section
92101 ** to a macro that can assist in verifying code coverage.  For production
92102 ** code the yytestcase() macro should be turned off.  But it is useful
92103 ** for testing.
92104 */
92105 #ifndef yytestcase
92106 # define yytestcase(X)
92107 #endif
92108
92109
92110 /* Next are the tables used to determine what action to take based on the
92111 ** current state and lookahead token.  These tables are used to implement
92112 ** functions that take a state number and lookahead value and return an
92113 ** action integer.  
92114 **
92115 ** Suppose the action integer is N.  Then the action is determined as
92116 ** follows
92117 **
92118 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
92119 **                                      token onto the stack and goto state N.
92120 **
92121 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
92122 **
92123 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
92124 **
92125 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
92126 **
92127 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
92128 **                                      slots in the yy_action[] table.
92129 **
92130 ** The action table is constructed as a single large table named yy_action[].
92131 ** Given state S and lookahead X, the action is computed as
92132 **
92133 **      yy_action[ yy_shift_ofst[S] + X ]
92134 **
92135 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
92136 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
92137 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
92138 ** and that yy_default[S] should be used instead.  
92139 **
92140 ** The formula above is for computing the action when the lookahead is
92141 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
92142 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
92143 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
92144 ** YY_SHIFT_USE_DFLT.
92145 **
92146 ** The following are the tables generated in this section:
92147 **
92148 **  yy_action[]        A single table containing all actions.
92149 **  yy_lookahead[]     A table containing the lookahead for each entry in
92150 **                     yy_action.  Used to detect hash collisions.
92151 **  yy_shift_ofst[]    For each state, the offset into yy_action for
92152 **                     shifting terminals.
92153 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
92154 **                     shifting non-terminals after a reduce.
92155 **  yy_default[]       Default action for each state.
92156 */
92157 #define YY_ACTTAB_COUNT (1550)
92158 static const YYACTIONTYPE yy_action[] = {
92159  /*     0 */   313,   49,  556,   46,  147,  172,  628,  598,   55,   55,
92160  /*    10 */    55,   55,  302,   53,   53,   53,   53,   52,   52,   51,
92161  /*    20 */    51,   51,   50,  238,  603,   66,  624,  623,  604,  598,
92162  /*    30 */   591,  585,   48,   53,   53,   53,   53,   52,   52,   51,
92163  /*    40 */    51,   51,   50,  238,   51,   51,   51,   50,  238,   56,
92164  /*    50 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
92165  /*    60 */    55,   55,  609,   53,   53,   53,   53,   52,   52,   51,
92166  /*    70 */    51,   51,   50,  238,  313,  598,  672,  330,  411,  217,
92167  /*    80 */    32,   53,   53,   53,   53,   52,   52,   51,   51,   51,
92168  /*    90 */    50,  238,  330,  414,  621,  620,  166,  598,  673,  382,
92169  /*   100 */   379,  378,  602,   73,  591,  585,  307,  424,  166,   58,
92170  /*   110 */   377,  382,  379,  378,  516,  515,  624,  623,  254,  200,
92171  /*   120 */   199,  198,  377,   56,   57,   47,  583,  582,  584,  584,
92172  /*   130 */    54,   54,   55,   55,   55,   55,  581,   53,   53,   53,
92173  /*   140 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  270,
92174  /*   150 */   226,  422,  283,  133,  177,  139,  284,  385,  279,  384,
92175  /*   160 */   169,  197,  251,  282,  253,  226,  411,  275,  440,  167,
92176  /*   170 */   139,  284,  385,  279,  384,  169,  571,  236,  591,  585,
92177  /*   180 */   240,  414,  275,  622,  621,  620,  674,  437,  441,  442,
92178  /*   190 */   602,   88,  352,  266,  439,  268,  438,   56,   57,   47,
92179  /*   200 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
92180  /*   210 */   465,   53,   53,   53,   53,   52,   52,   51,   51,   51,
92181  /*   220 */    50,  238,  313,  471,   52,   52,   51,   51,   51,   50,
92182  /*   230 */   238,  234,  166,  491,  567,  382,  379,  378,    1,  440,
92183  /*   240 */   252,  176,  624,  623,  608,   67,  377,  513,  622,  443,
92184  /*   250 */   237,  577,  591,  585,  622,  172,  466,  598,  554,  441,
92185  /*   260 */   340,  409,  526,  580,  580,  349,  596,  553,  194,  482,
92186  /*   270 */   175,   56,   57,   47,  583,  582,  584,  584,   54,   54,
92187  /*   280 */    55,   55,   55,   55,  562,   53,   53,   53,   53,   52,
92188  /*   290 */    52,   51,   51,   51,   50,  238,  313,  594,  594,  594,
92189  /*   300 */   561,  578,  469,   65,  259,  351,  258,  411,  624,  623,
92190  /*   310 */   621,  620,  332,  576,  575,  240,  560,  568,  520,  411,
92191  /*   320 */   341,  237,  414,  624,  623,  598,  591,  585,  542,  519,
92192  /*   330 */   171,  602,   95,   68,  414,  624,  623,  624,  623,   38,
92193  /*   340 */   877,  506,  507,  602,   88,   56,   57,   47,  583,  582,
92194  /*   350 */   584,  584,   54,   54,   55,   55,   55,   55,  532,   53,
92195  /*   360 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
92196  /*   370 */   313,  411,  579,  398,  531,  237,  621,  620,  388,  625,
92197  /*   380 */   500,  206,  167,  396,  233,  312,  414,  387,  569,  492,
92198  /*   390 */   216,  621,  620,  566,  622,  602,   74,  533,  210,  491,
92199  /*   400 */   591,  585,  548,  621,  620,  621,  620,  300,  598,  466,
92200  /*   410 */   481,   67,  603,   35,  622,  601,  604,  547,    6,   56,
92201  /*   420 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
92202  /*   430 */    55,   55,  601,   53,   53,   53,   53,   52,   52,   51,
92203  /*   440 */    51,   51,   50,  238,  313,  411,  184,  409,  528,  580,
92204  /*   450 */   580,  551,  962,  186,  419,    2,  353,  259,  351,  258,
92205  /*   460 */   414,  409,  411,  580,  580,   44,  411,  544,  240,  602,
92206  /*   470 */    94,  190,    7,   62,  591,  585,  598,  414,  350,  607,
92207  /*   480 */   493,  414,  409,  317,  580,  580,  602,   95,  496,  565,
92208  /*   490 */   602,   80,  203,   56,   57,   47,  583,  582,  584,  584,
92209  /*   500 */    54,   54,   55,   55,   55,   55,  535,   53,   53,   53,
92210  /*   510 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  202,
92211  /*   520 */   564,  293,  511,   49,  562,   46,  147,  411,  394,  183,
92212  /*   530 */   563,  549,  505,  549,  174,  409,  322,  580,  580,   39,
92213  /*   540 */   561,   37,  414,  624,  623,  192,  473,  383,  591,  585,
92214  /*   550 */   474,  602,   80,  601,  504,  544,  560,  364,  402,  210,
92215  /*   560 */   421,  952,  361,  952,  365,  201,  144,   56,   57,   47,
92216  /*   570 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
92217  /*   580 */   559,   53,   53,   53,   53,   52,   52,   51,   51,   51,
92218  /*   590 */    50,  238,  313,  601,  232,  264,  272,  321,  374,  484,
92219  /*   600 */   510,  146,  342,  146,  328,  425,  485,  407,  576,  575,
92220  /*   610 */   622,  621,  620,   49,  168,   46,  147,  353,  546,  491,
92221  /*   620 */   204,  240,  591,  585,  421,  951,  549,  951,  549,  168,
92222  /*   630 */   429,   67,  390,  343,  622,  434,  307,  423,  338,  360,
92223  /*   640 */   391,   56,   57,   47,  583,  582,  584,  584,   54,   54,
92224  /*   650 */    55,   55,   55,   55,  601,   53,   53,   53,   53,   52,
92225  /*   660 */    52,   51,   51,   51,   50,  238,  313,   34,  318,  425,
92226  /*   670 */   237,   21,  359,  273,  411,  167,  411,  276,  411,  540,
92227  /*   680 */   411,  422,   13,  318,  619,  618,  617,  622,  275,  414,
92228  /*   690 */   336,  414,  622,  414,  622,  414,  591,  585,  602,   69,
92229  /*   700 */   602,   97,  602,  100,  602,   98,  631,  629,  334,  475,
92230  /*   710 */   475,  367,  319,  148,  327,   56,   57,   47,  583,  582,
92231  /*   720 */   584,  584,   54,   54,   55,   55,   55,   55,  411,   53,
92232  /*   730 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
92233  /*   740 */   313,  411,  331,  414,  411,   49,  276,   46,  147,  569,
92234  /*   750 */   406,  216,  602,  106,  573,  573,  414,  354,  524,  414,
92235  /*   760 */   411,  622,  411,  224,    4,  602,  104,  605,  602,  108,
92236  /*   770 */   591,  585,  622,   20,  375,  414,  167,  414,  215,  144,
92237  /*   780 */   470,  239,  167,  225,  602,  109,  602,  134,   18,   56,
92238  /*   790 */    57,   47,  583,  582,  584,  584,   54,   54,   55,   55,
92239  /*   800 */    55,   55,  411,   53,   53,   53,   53,   52,   52,   51,
92240  /*   810 */    51,   51,   50,  238,  313,  411,  276,  414,   12,  459,
92241  /*   820 */   276,  171,  411,   16,  223,  189,  602,  135,  354,  170,
92242  /*   830 */   414,  622,  630,    2,  411,  622,  540,  414,  143,  602,
92243  /*   840 */    61,  359,  132,  622,  591,  585,  602,  105,  458,  414,
92244  /*   850 */    23,  622,  446,  326,   23,  538,  622,  325,  602,  103,
92245  /*   860 */   427,  530,  309,   56,   57,   47,  583,  582,  584,  584,
92246  /*   870 */    54,   54,   55,   55,   55,   55,  411,   53,   53,   53,
92247  /*   880 */    53,   52,   52,   51,   51,   51,   50,  238,  313,  411,
92248  /*   890 */   264,  414,  411,  276,  359,  219,  157,  214,  357,  366,
92249  /*   900 */   602,   96,  522,  521,  414,  622,  358,  414,  622,  622,
92250  /*   910 */   411,  613,  612,  602,  102,  142,  602,   77,  591,  585,
92251  /*   920 */   529,  540,  231,  426,  308,  414,  622,  622,  468,  521,
92252  /*   930 */   324,  601,  257,  263,  602,   99,  622,   56,   45,   47,
92253  /*   940 */   583,  582,  584,  584,   54,   54,   55,   55,   55,   55,
92254  /*   950 */   411,   53,   53,   53,   53,   52,   52,   51,   51,   51,
92255  /*   960 */    50,  238,  313,  264,  264,  414,  411,  213,  209,  544,
92256  /*   970 */   544,  207,  611,   28,  602,  138,   50,  238,  622,  622,
92257  /*   980 */   381,  414,  503,  140,  323,  222,  274,  622,  590,  589,
92258  /*   990 */   602,  137,  591,  585,  629,  334,  606,   30,  622,  571,
92259  /*  1000 */   236,  601,  601,  130,  496,  601,  453,  451,  288,  286,
92260  /*  1010 */   587,  586,   57,   47,  583,  582,  584,  584,   54,   54,
92261  /*  1020 */    55,   55,   55,   55,  411,   53,   53,   53,   53,   52,
92262  /*  1030 */    52,   51,   51,   51,   50,  238,  313,  588,  411,  414,
92263  /*  1040 */   411,  264,  410,  129,  595,  400,   27,  376,  602,  136,
92264  /*  1050 */   128,  165,  479,  414,  282,  414,  622,  622,  411,  622,
92265  /*  1060 */   622,  411,  602,   76,  602,   93,  591,  585,  188,  372,
92266  /*  1070 */   368,  125,  476,  414,  261,  160,  414,  171,  124,  472,
92267  /*  1080 */   123,   15,  602,   92,  450,  602,   75,   47,  583,  582,
92268  /*  1090 */   584,  584,   54,   54,   55,   55,   55,   55,  464,   53,
92269  /*  1100 */    53,   53,   53,   52,   52,   51,   51,   51,   50,  238,
92270  /*  1110 */    43,  405,  264,    3,  558,  264,  545,  415,  623,  159,
92271  /*  1120 */   541,  158,  539,  278,   25,  461,  121,  622,  408,  622,
92272  /*  1130 */   622,  622,   24,   43,  405,  622,    3,  622,  622,  120,
92273  /*  1140 */   415,  623,   11,  456,  411,  156,  452,  403,  509,  277,
92274  /*  1150 */   118,  408,  489,  113,  205,  449,  271,  567,  221,  414,
92275  /*  1160 */   269,  267,  155,  622,  622,  111,  411,  622,  602,   95,
92276  /*  1170 */   403,  622,  411,  110,   10,  622,  622,   40,   41,  534,
92277  /*  1180 */   567,  414,   64,  264,   42,  413,  412,  414,  601,  596,
92278  /*  1190 */   602,   91,  445,  436,  150,  435,  602,   90,  622,  265,
92279  /*  1200 */    40,   41,  337,  242,  411,  191,  333,   42,  413,  412,
92280  /*  1210 */   398,  420,  596,  316,  622,  399,  260,  107,  230,  414,
92281  /*  1220 */   594,  594,  594,  593,  592,   14,  220,  411,  602,  101,
92282  /*  1230 */   240,  622,   43,  405,  362,    3,  149,  315,  626,  415,
92283  /*  1240 */   623,  127,  414,  594,  594,  594,  593,  592,   14,  622,
92284  /*  1250 */   408,  602,   89,  411,  181,   33,  405,  463,    3,  411,
92285  /*  1260 */   264,  462,  415,  623,  616,  615,  614,  355,  414,  403,
92286  /*  1270 */   417,  416,  622,  408,  414,  622,  622,  602,   87,  567,
92287  /*  1280 */   418,  627,  622,  602,   86,    8,  241,  180,  126,  255,
92288  /*  1290 */   600,  178,  403,  240,  208,  455,  395,  294,  444,   40,
92289  /*  1300 */    41,  297,  567,  248,  622,  296,   42,  413,  412,  247,
92290  /*  1310 */   622,  596,  244,  622,   30,   60,   31,  243,  430,  624,
92291  /*  1320 */   623,  292,   40,   41,  622,  295,  145,  622,  601,   42,
92292  /*  1330 */   413,  412,  622,  622,  596,  393,  622,  397,  599,   59,
92293  /*  1340 */   235,  622,  594,  594,  594,  593,  592,   14,  218,  291,
92294  /*  1350 */   622,   36,  344,  305,  304,  303,  179,  301,  411,  567,
92295  /*  1360 */   454,  557,  173,  185,  622,  594,  594,  594,  593,  592,
92296  /*  1370 */    14,  411,   29,  414,  151,  289,  246,  523,  411,  196,
92297  /*  1380 */   195,  335,  602,   85,  411,  245,  414,  526,  392,  543,
92298  /*  1390 */   411,  596,  287,  414,  285,  602,   72,  537,  153,  414,
92299  /*  1400 */   466,  411,  602,   71,  154,  414,  411,  152,  602,   84,
92300  /*  1410 */   386,  536,  329,  411,  602,   83,  414,  518,  280,  411,
92301  /*  1420 */   513,  414,  594,  594,  594,  602,   82,  517,  414,  311,
92302  /*  1430 */   602,   81,  411,  514,  414,  512,  131,  602,   70,  229,
92303  /*  1440 */   228,  227,  494,  602,   17,  411,  488,  414,  259,  346,
92304  /*  1450 */   249,  389,  487,  486,  314,  164,  602,   79,  310,  240,
92305  /*  1460 */   414,  373,  480,  163,  262,  371,  414,  162,  369,  602,
92306  /*  1470 */    78,  212,  478,   26,  477,  602,    9,  161,  467,  363,
92307  /*  1480 */   141,  122,  339,  187,  119,  457,  348,  347,  117,  116,
92308  /*  1490 */   115,  112,  114,  448,  182,   22,  320,  433,  432,  431,
92309  /*  1500 */    19,  428,  610,  597,  574,  193,  572,   63,  298,  404,
92310  /*  1510 */   555,  552,  290,  281,  510,  460,  498,  499,  495,  447,
92311  /*  1520 */   356,  497,  256,  380,  306,  570,    5,  250,  345,  238,
92312  /*  1530 */   299,  550,  527,  490,  508,  525,  502,  401,  501,  963,
92313  /*  1540 */   211,  963,  483,  963,  963,  963,  963,  963,  963,  370,
92314 };
92315 static const YYCODETYPE yy_lookahead[] = {
92316  /*     0 */    19,  222,  223,  224,  225,   24,    1,   26,   77,   78,
92317  /*    10 */    79,   80,   15,   82,   83,   84,   85,   86,   87,   88,
92318  /*    20 */    89,   90,   91,   92,  113,   22,   26,   27,  117,   26,
92319  /*    30 */    49,   50,   81,   82,   83,   84,   85,   86,   87,   88,
92320  /*    40 */    89,   90,   91,   92,   88,   89,   90,   91,   92,   68,
92321  /*    50 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
92322  /*    60 */    79,   80,   23,   82,   83,   84,   85,   86,   87,   88,
92323  /*    70 */    89,   90,   91,   92,   19,   94,  118,   19,  150,   22,
92324  /*    80 */    25,   82,   83,   84,   85,   86,   87,   88,   89,   90,
92325  /*    90 */    91,   92,   19,  165,   94,   95,   96,   94,  118,   99,
92326  /*   100 */   100,  101,  174,  175,   49,   50,   22,   23,   96,   54,
92327  /*   110 */   110,   99,  100,  101,    7,    8,   26,   27,   16,  105,
92328  /*   120 */   106,  107,  110,   68,   69,   70,   71,   72,   73,   74,
92329  /*   130 */    75,   76,   77,   78,   79,   80,  113,   82,   83,   84,
92330  /*   140 */    85,   86,   87,   88,   89,   90,   91,   92,   19,   16,
92331  /*   150 */    92,   67,   98,   24,   96,   97,   98,   99,  100,  101,
92332  /*   160 */   102,   25,   60,  109,   62,   92,  150,  109,  150,   25,
92333  /*   170 */    97,   98,   99,  100,  101,  102,   86,   87,   49,   50,
92334  /*   180 */   116,  165,  109,  165,   94,   95,  118,   97,  170,  171,
92335  /*   190 */   174,  175,  128,   60,  104,   62,  106,   68,   69,   70,
92336  /*   200 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
92337  /*   210 */    11,   82,   83,   84,   85,   86,   87,   88,   89,   90,
92338  /*   220 */    91,   92,   19,   21,   86,   87,   88,   89,   90,   91,
92339  /*   230 */    92,  215,   96,  150,   66,   99,  100,  101,   22,  150,
92340  /*   240 */   138,  118,   26,   27,  161,  162,  110,  103,  165,  231,
92341  /*   250 */   232,   23,   49,   50,  165,   24,   57,   26,   32,  170,
92342  /*   260 */   171,  112,   94,  114,  115,   63,   98,   41,  185,  186,
92343  /*   270 */   118,   68,   69,   70,   71,   72,   73,   74,   75,   76,
92344  /*   280 */    77,   78,   79,   80,   12,   82,   83,   84,   85,   86,
92345  /*   290 */    87,   88,   89,   90,   91,   92,   19,  129,  130,  131,
92346  /*   300 */    28,   23,  100,   25,  105,  106,  107,  150,   26,   27,
92347  /*   310 */    94,   95,  169,  170,  171,  116,   44,   23,   46,  150,
92348  /*   320 */   231,  232,  165,   26,   27,   94,   49,   50,   23,   57,
92349  /*   330 */    25,  174,  175,   22,  165,   26,   27,   26,   27,  136,
92350  /*   340 */   138,   97,   98,  174,  175,   68,   69,   70,   71,   72,
92351  /*   350 */    73,   74,   75,   76,   77,   78,   79,   80,   23,   82,
92352  /*   360 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
92353  /*   370 */    19,  150,   23,  216,   23,  232,   94,   95,  221,  150,
92354  /*   380 */    23,  160,   25,  214,  215,  163,  165,   88,  166,  167,
92355  /*   390 */   168,   94,   95,   23,  165,  174,  175,   88,  160,  150,
92356  /*   400 */    49,   50,  120,   94,   95,   94,   95,  158,   26,   57,
92357  /*   410 */   161,  162,  113,  136,  165,  194,  117,  120,   22,   68,
92358  /*   420 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
92359  /*   430 */    79,   80,  194,   82,   83,   84,   85,   86,   87,   88,
92360  /*   440 */    89,   90,   91,   92,   19,  150,   23,  112,   23,  114,
92361  /*   450 */   115,   25,  142,  143,  144,  145,  218,  105,  106,  107,
92362  /*   460 */   165,  112,  150,  114,  115,   22,  150,  166,  116,  174,
92363  /*   470 */   175,   22,   76,  235,   49,   50,   94,  165,  240,  172,
92364  /*   480 */   173,  165,  112,  155,  114,  115,  174,  175,  181,   11,
92365  /*   490 */   174,  175,   22,   68,   69,   70,   71,   72,   73,   74,
92366  /*   500 */    75,   76,   77,   78,   79,   80,  205,   82,   83,   84,
92367  /*   510 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  160,
92368  /*   520 */    23,  226,   23,  222,   12,  224,  225,  150,  216,   23,
92369  /*   530 */    23,   25,   36,   25,   25,  112,  220,  114,  115,  135,
92370  /*   540 */    28,  137,  165,   26,   27,  119,   30,   51,   49,   50,
92371  /*   550 */    34,  174,  175,  194,   58,  166,   44,  229,   46,  160,
92372  /*   560 */    22,   23,  234,   25,   48,  206,  207,   68,   69,   70,
92373  /*   570 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
92374  /*   580 */    23,   82,   83,   84,   85,   86,   87,   88,   89,   90,
92375  /*   590 */    91,   92,   19,  194,  205,  150,   23,  220,   19,  181,
92376  /*   600 */   182,   95,   97,   95,  108,   67,  188,  169,  170,  171,
92377  /*   610 */   165,   94,   95,  222,   50,  224,  225,  218,  120,  150,
92378  /*   620 */   160,  116,   49,   50,   22,   23,  120,   25,  120,   50,
92379  /*   630 */   161,  162,   19,  128,  165,  244,   22,   23,  193,  240,
92380  /*   640 */    27,   68,   69,   70,   71,   72,   73,   74,   75,   76,
92381  /*   650 */    77,   78,   79,   80,  194,   82,   83,   84,   85,   86,
92382  /*   660 */    87,   88,   89,   90,   91,   92,   19,   25,  104,   67,
92383  /*   670 */   232,   24,  150,   23,  150,   25,  150,  150,  150,  150,
92384  /*   680 */   150,   67,   25,  104,    7,    8,    9,  165,  109,  165,
92385  /*   690 */   245,  165,  165,  165,  165,  165,   49,   50,  174,  175,
92386  /*   700 */   174,  175,  174,  175,  174,  175,    0,    1,    2,  105,
92387  /*   710 */   106,  107,  248,  249,  187,   68,   69,   70,   71,   72,
92388  /*   720 */    73,   74,   75,   76,   77,   78,   79,   80,  150,   82,
92389  /*   730 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
92390  /*   740 */    19,  150,  213,  165,  150,  222,  150,  224,  225,  166,
92391  /*   750 */   167,  168,  174,  175,  129,  130,  165,  150,  165,  165,
92392  /*   760 */   150,  165,  150,  241,   35,  174,  175,  174,  174,  175,
92393  /*   770 */    49,   50,  165,   52,   23,  165,   25,  165,  206,  207,
92394  /*   780 */    23,  197,   25,  187,  174,  175,  174,  175,  204,   68,
92395  /*   790 */    69,   70,   71,   72,   73,   74,   75,   76,   77,   78,
92396  /*   800 */    79,   80,  150,   82,   83,   84,   85,   86,   87,   88,
92397  /*   810 */    89,   90,   91,   92,   19,  150,  150,  165,   35,   23,
92398  /*   820 */   150,   25,  150,   22,  217,   24,  174,  175,  150,   35,
92399  /*   830 */   165,  165,  144,  145,  150,  165,  150,  165,  118,  174,
92400  /*   840 */   175,  150,   22,  165,   49,   50,  174,  175,   23,  165,
92401  /*   850 */    25,  165,   23,  187,   25,   27,  165,  187,  174,  175,
92402  /*   860 */    23,   23,   25,   68,   69,   70,   71,   72,   73,   74,
92403  /*   870 */    75,   76,   77,   78,   79,   80,  150,   82,   83,   84,
92404  /*   880 */    85,   86,   87,   88,   89,   90,   91,   92,   19,  150,
92405  /*   890 */   150,  165,  150,  150,  150,  217,   25,  160,   19,  213,
92406  /*   900 */   174,  175,  190,  191,  165,  165,   27,  165,  165,  165,
92407  /*   910 */   150,  150,  150,  174,  175,   39,  174,  175,   49,   50,
92408  /*   920 */    23,  150,   52,  250,  251,  165,  165,  165,  190,  191,
92409  /*   930 */   187,  194,  241,  193,  174,  175,  165,   68,   69,   70,
92410  /*   940 */    71,   72,   73,   74,   75,   76,   77,   78,   79,   80,
92411  /*   950 */   150,   82,   83,   84,   85,   86,   87,   88,   89,   90,
92412  /*   960 */    91,   92,   19,  150,  150,  165,  150,  160,  160,  166,
92413  /*   970 */   166,  160,  150,   22,  174,  175,   91,   92,  165,  165,
92414  /*   980 */    52,  165,   29,  150,  213,  241,   23,  165,   49,   50,
92415  /*   990 */   174,  175,   49,   50,    1,    2,  173,  126,  165,   86,
92416  /*  1000 */    87,  194,  194,   22,  181,  194,  193,  193,  205,  205,
92417  /*  1010 */    71,   72,   69,   70,   71,   72,   73,   74,   75,   76,
92418  /*  1020 */    77,   78,   79,   80,  150,   82,   83,   84,   85,   86,
92419  /*  1030 */    87,   88,   89,   90,   91,   92,   19,   98,  150,  165,
92420  /*  1040 */   150,  150,  150,   22,  150,  150,   22,   52,  174,  175,
92421  /*  1050 */    22,  102,   20,  165,  109,  165,  165,  165,  150,  165,
92422  /*  1060 */   165,  150,  174,  175,  174,  175,   49,   50,   24,   19,
92423  /*  1070 */    43,  104,   59,  165,  138,  104,  165,   25,   53,   53,
92424  /*  1080 */    22,    5,  174,  175,  193,  174,  175,   70,   71,   72,
92425  /*  1090 */    73,   74,   75,   76,   77,   78,   79,   80,    1,   82,
92426  /*  1100 */    83,   84,   85,   86,   87,   88,   89,   90,   91,   92,
92427  /*  1110 */    19,   20,  150,   22,  150,  150,  150,   26,   27,  118,
92428  /*  1120 */   150,   35,  150,  150,   76,   27,  108,  165,   37,  165,
92429  /*  1130 */   165,  165,   76,   19,   20,  165,   22,  165,  165,  127,
92430  /*  1140 */    26,   27,   22,    1,  150,   16,   20,   56,  150,  150,
92431  /*  1150 */   119,   37,  150,  119,  160,  193,  150,   66,  193,  165,
92432  /*  1160 */   150,  150,  121,  165,  165,  108,  150,  165,  174,  175,
92433  /*  1170 */    56,  165,  150,  127,   22,  165,  165,   86,   87,   88,
92434  /*  1180 */    66,  165,   16,  150,   93,   94,   95,  165,  194,   98,
92435  /*  1190 */   174,  175,  128,   23,   15,   23,  174,  175,  165,  150,
92436  /*  1200 */    86,   87,   65,  140,  150,   22,    3,   93,   94,   95,
92437  /*  1210 */   216,    4,   98,  252,  165,  221,  150,  164,  180,  165,
92438  /*  1220 */   129,  130,  131,  132,  133,  134,  193,  150,  174,  175,
92439  /*  1230 */   116,  165,   19,   20,  150,   22,  249,  252,  149,   26,
92440  /*  1240 */    27,  180,  165,  129,  130,  131,  132,  133,  134,  165,
92441  /*  1250 */    37,  174,  175,  150,    6,   19,   20,  150,   22,  150,
92442  /*  1260 */   150,  150,   26,   27,  149,  149,   13,  150,  165,   56,
92443  /*  1270 */   149,  159,  165,   37,  165,  165,  165,  174,  175,   66,
92444  /*  1280 */   146,  147,  165,  174,  175,   25,  152,  151,  154,  150,
92445  /*  1290 */   194,  151,   56,  116,  160,  150,  123,  202,  150,   86,
92446  /*  1300 */    87,  199,   66,  193,  165,  200,   93,   94,   95,  150,
92447  /*  1310 */   165,   98,  150,  165,  126,   22,  124,  150,  150,   26,
92448  /*  1320 */    27,  150,   86,   87,  165,  201,  150,  165,  194,   93,
92449  /*  1330 */    94,   95,  165,  165,   98,  150,  165,  122,  203,  125,
92450  /*  1340 */   227,  165,  129,  130,  131,  132,  133,  134,    5,  150,
92451  /*  1350 */   165,  135,  218,   10,   11,   12,   13,   14,  150,   66,
92452  /*  1360 */    17,  157,  118,  157,  165,  129,  130,  131,  132,  133,
92453  /*  1370 */   134,  150,  104,  165,   31,  210,   33,  176,  150,   86,
92454  /*  1380 */    87,  247,  174,  175,  150,   42,  165,   94,  121,  211,
92455  /*  1390 */   150,   98,  210,  165,  210,  174,  175,  211,   55,  165,
92456  /*  1400 */    57,  150,  174,  175,   61,  165,  150,   64,  174,  175,
92457  /*  1410 */   104,  211,   47,  150,  174,  175,  165,  176,  176,  150,
92458  /*  1420 */   103,  165,  129,  130,  131,  174,  175,  184,  165,  179,
92459  /*  1430 */   174,  175,  150,  178,  165,  176,   22,  174,  175,  230,
92460  /*  1440 */    92,  230,  184,  174,  175,  150,  176,  165,  105,  106,
92461  /*  1450 */   107,  150,  176,  176,  111,  156,  174,  175,  179,  116,
92462  /*  1460 */   165,   18,  157,  156,  238,  157,  165,  156,   45,  174,
92463  /*  1470 */   175,  157,  157,  135,  239,  174,  175,  156,  189,  157,
92464  /*  1480 */    68,  189,  139,  219,   22,  199,  157,   18,  192,  192,
92465  /*  1490 */   192,  189,  192,  199,  219,  243,  157,   40,  157,  157,
92466  /*  1500 */   243,   38,  153,  166,  233,  196,  233,  246,  198,  228,
92467  /*  1510 */   177,  177,  209,  177,  182,  199,  166,  177,  166,  199,
92468  /*  1520 */   242,  177,  242,  178,  148,  166,  196,  209,  209,   92,
92469  /*  1530 */   195,  208,  174,  186,  183,  174,  183,  191,  183,  253,
92470  /*  1540 */   236,  253,  186,  253,  253,  253,  253,  253,  253,  237,
92471 };
92472 #define YY_SHIFT_USE_DFLT (-90)
92473 #define YY_SHIFT_COUNT (418)
92474 #define YY_SHIFT_MIN   (-89)
92475 #define YY_SHIFT_MAX   (1469)
92476 static const short yy_shift_ofst[] = {
92477  /*     0 */   993, 1114, 1343, 1114, 1213, 1213,   90,   90,    0,  -19,
92478  /*    10 */  1213, 1213, 1213, 1213, 1213,  352,  517,  721, 1091, 1213,
92479  /*    20 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
92480  /*    30 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
92481  /*    40 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1236, 1213, 1213,
92482  /*    50 */  1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213, 1213,
92483  /*    60 */  1213,  -49,  199,  517,  517,  913,  913,  382, 1177,   55,
92484  /*    70 */   647,  573,  499,  425,  351,  277,  203,  129,  795,  795,
92485  /*    80 */   795,  795,  795,  795,  795,  795,  795,  795,  795,  795,
92486  /*    90 */   795,  795,  795,  795,  795,  795,  869,  795,  943, 1017,
92487  /*   100 */  1017,  -69,  -69,  -69,  -69,   -1,   -1,   58,  138,  -44,
92488  /*   110 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
92489  /*   120 */   517,  517,  517,  517,  517,  517,  202,  579,  517,  517,
92490  /*   130 */   517,  517,  517,  382,  885, 1437,  -90,  -90,  -90, 1293,
92491  /*   140 */    73,  272,  272,  309,  311,  297,  282,  216,  602,  538,
92492  /*   150 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
92493  /*   160 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
92494  /*   170 */   517,  517,  517,  517,  517,  517,  517,  517,  517,  517,
92495  /*   180 */   517,  517,  505,  231,  231,  231,  706,   64, 1177, 1177,
92496  /*   190 */  1177,  -90,  -90,  -90,  136,  168,  168,   12,  496,  496,
92497  /*   200 */   496,  506,  423,  512,  370,  349,  335,  149,  149,  149,
92498  /*   210 */   149,  604,  516,  149,  149,  508,    3,  299,  677,  871,
92499  /*   220 */   613,  613,  879,  871,  879,  144,  382,  226,  382,  226,
92500  /*   230 */   564,  226,  613,  226,  226,  404,  625,  625,  382,  426,
92501  /*   240 */   -89,  801, 1463, 1244, 1244, 1457, 1457, 1244, 1462, 1412,
92502  /*   250 */  1188, 1469, 1469, 1469, 1469, 1244, 1188, 1462, 1412, 1412,
92503  /*   260 */  1244, 1443, 1338, 1423, 1244, 1244, 1443, 1244, 1443, 1244,
92504  /*   270 */  1443, 1414, 1306, 1306, 1306, 1365, 1348, 1348, 1414, 1306,
92505  /*   280 */  1317, 1306, 1365, 1306, 1306, 1267, 1268, 1267, 1268, 1267,
92506  /*   290 */  1268, 1244, 1244, 1216, 1214, 1215, 1192, 1173, 1188, 1177,
92507  /*   300 */  1260, 1253, 1253, 1248, 1248, 1248, 1248,  -90,  -90,  -90,
92508  /*   310 */   -90,  -90,  -90,  939,  102,  614,   84,  133,   14,  837,
92509  /*   320 */   396,  829,  825,  796,  757,  751,  650,  357,  244,  107,
92510  /*   330 */    54,  305,  278, 1207, 1203, 1183, 1063, 1179, 1137, 1166,
92511  /*   340 */  1172, 1170, 1064, 1152, 1046, 1057, 1034, 1126, 1041, 1129,
92512  /*   350 */  1142, 1031, 1120, 1012, 1056, 1048, 1018, 1098, 1086, 1001,
92513  /*   360 */  1097, 1076, 1058,  971,  936, 1026, 1052, 1025, 1013, 1027,
92514  /*   370 */   967, 1044, 1032, 1050,  945,  949, 1028,  995, 1024, 1021,
92515  /*   380 */   963,  981,  928,  953,  951,  870,  876,  897,  838,  720,
92516  /*   390 */   828,  794,  820,  498,  642,  783,  657,  729,  642,  557,
92517  /*   400 */   507,  509,  497,  470,  478,  449,  294,  228,  443,   23,
92518  /*   410 */   152,  123,   68,  -20,  -42,   57,   39,   -3,    5,
92519 };
92520 #define YY_REDUCE_USE_DFLT (-222)
92521 #define YY_REDUCE_COUNT (312)
92522 #define YY_REDUCE_MIN   (-221)
92523 #define YY_REDUCE_MAX   (1376)
92524 static const short yy_reduce_ofst[] = {
92525  /*     0 */   310,  994, 1134,  221,  169,  157,   89,   18,   83,  301,
92526  /*    10 */   377,  316,  312,   16,  295,  238,  249,  391, 1301, 1295,
92527  /*    20 */  1282, 1269, 1263, 1256, 1251, 1240, 1234, 1228, 1221, 1208,
92528  /*    30 */  1109, 1103, 1077, 1054, 1022, 1016,  911,  908,  890,  888,
92529  /*    40 */   874,  816,  800,  760,  742,  739,  726,  684,  672,  665,
92530  /*    50 */   652,  612,  610,  594,  591,  578,  530,  528,  526,  524,
92531  /*    60 */   -72, -221,  399,  469,  445,  438,  143,  222,  359,  523,
92532  /*    70 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
92533  /*    80 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
92534  /*    90 */   523,  523,  523,  523,  523,  523,  523,  523,  523,  523,
92535  /*   100 */   523,  523,  523,  523,  523,  523,  523,  307,  523,  523,
92536  /*   110 */  1110,  678, 1033,  965,  962,  891,  814,  813,  744,  771,
92537  /*   120 */   691,  607,  522,  743,  686,  740,  328,  418,  670,  666,
92538  /*   130 */   596,  527,  529,  583,  523,  523,  523,  523,  523,  593,
92539  /*   140 */   823,  738,  712,  892, 1199, 1185, 1176, 1171,  673,  673,
92540  /*   150 */  1168, 1167, 1162, 1159, 1148, 1145, 1139, 1117, 1111, 1107,
92541  /*   160 */  1084, 1066, 1049, 1011, 1010, 1006, 1002,  999,  998,  973,
92542  /*   170 */   972,  970,  966,  964,  895,  894,  892,  833,  822,  762,
92543  /*   180 */   761,  229,  811,  804,  803,  389,  688,  808,  807,  737,
92544  /*   190 */   460,  464,  572,  584, 1356, 1361, 1358, 1347, 1355, 1353,
92545  /*   200 */  1351, 1323, 1335, 1346, 1335, 1335, 1335, 1335, 1335, 1335,
92546  /*   210 */  1335, 1312, 1304, 1335, 1335, 1323, 1359, 1330, 1376, 1320,
92547  /*   220 */  1319, 1318, 1280, 1316, 1278, 1345, 1352, 1344, 1350, 1340,
92548  /*   230 */  1332, 1336, 1303, 1334, 1333, 1281, 1273, 1271, 1337, 1310,
92549  /*   240 */  1309, 1349, 1261, 1342, 1341, 1257, 1252, 1339, 1275, 1302,
92550  /*   250 */  1294, 1300, 1298, 1297, 1296, 1329, 1286, 1264, 1292, 1289,
92551  /*   260 */  1322, 1321, 1235, 1226, 1315, 1314, 1311, 1308, 1307, 1305,
92552  /*   270 */  1299, 1279, 1277, 1276, 1270, 1258, 1211, 1209, 1250, 1259,
92553  /*   280 */  1255, 1242, 1243, 1241, 1201, 1200, 1184, 1186, 1182, 1178,
92554  /*   290 */  1165, 1206, 1204, 1113, 1135, 1095, 1124, 1105, 1102, 1096,
92555  /*   300 */  1112, 1140, 1136, 1121, 1116, 1115, 1089,  985,  961,  987,
92556  /*   310 */  1061, 1038, 1053,
92557 };
92558 static const YYACTIONTYPE yy_default[] = {
92559  /*     0 */   636,  872,  961,  961,  961,  872,  901,  901,  961,  760,
92560  /*    10 */   961,  961,  961,  961,  870,  961,  961,  935,  961,  961,
92561  /*    20 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
92562  /*    30 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
92563  /*    40 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
92564  /*    50 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
92565  /*    60 */   961,  844,  961,  961,  961,  901,  901,  675,  764,  795,
92566  /*    70 */   961,  961,  961,  961,  961,  961,  961,  961,  934,  936,
92567  /*    80 */   810,  809,  803,  802,  914,  775,  800,  793,  786,  797,
92568  /*    90 */   873,  866,  867,  865,  869,  874,  961,  796,  832,  850,
92569  /*   100 */   831,  849,  856,  848,  834,  843,  833,  667,  835,  836,
92570  /*   110 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
92571  /*   120 */   961,  961,  961,  961,  961,  961,  662,  729,  961,  961,
92572  /*   130 */   961,  961,  961,  961,  837,  838,  853,  852,  851,  961,
92573  /*   140 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
92574  /*   150 */   961,  941,  939,  961,  885,  961,  961,  961,  961,  961,
92575  /*   160 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
92576  /*   170 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
92577  /*   180 */   961,  642,  961,  760,  760,  760,  636,  961,  961,  961,
92578  /*   190 */   961,  953,  764,  754,  720,  961,  961,  961,  961,  961,
92579  /*   200 */   961,  961,  961,  961,  961,  961,  961,  805,  743,  924,
92580  /*   210 */   926,  961,  907,  741,  664,  762,  677,  752,  644,  799,
92581  /*   220 */   777,  777,  919,  799,  919,  701,  961,  789,  961,  789,
92582  /*   230 */   698,  789,  777,  789,  789,  868,  961,  961,  961,  761,
92583  /*   240 */   752,  961,  946,  768,  768,  938,  938,  768,  811,  733,
92584  /*   250 */   799,  740,  740,  740,  740,  768,  799,  811,  733,  733,
92585  /*   260 */   768,  659,  913,  911,  768,  768,  659,  768,  659,  768,
92586  /*   270 */   659,  878,  731,  731,  731,  716,  882,  882,  878,  731,
92587  /*   280 */   701,  731,  716,  731,  731,  781,  776,  781,  776,  781,
92588  /*   290 */   776,  768,  768,  961,  794,  782,  792,  790,  799,  961,
92589  /*   300 */   719,  652,  652,  641,  641,  641,  641,  958,  958,  953,
92590  /*   310 */   703,  703,  685,  961,  961,  961,  961,  961,  961,  961,
92591  /*   320 */   887,  961,  961,  961,  961,  961,  961,  961,  961,  961,
92592  /*   330 */   961,  961,  961,  961,  637,  948,  961,  961,  945,  961,
92593  /*   340 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
92594  /*   350 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  917,
92595  /*   360 */   961,  961,  961,  961,  961,  961,  910,  909,  961,  961,
92596  /*   370 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
92597  /*   380 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  961,
92598  /*   390 */   961,  961,  961,  961,  791,  961,  783,  961,  871,  961,
92599  /*   400 */   961,  961,  961,  961,  961,  961,  961,  961,  961,  746,
92600  /*   410 */   820,  961,  819,  823,  818,  669,  961,  650,  961,  633,
92601  /*   420 */   638,  957,  960,  959,  956,  955,  954,  949,  947,  944,
92602  /*   430 */   943,  942,  940,  937,  933,  891,  889,  896,  895,  894,
92603  /*   440 */   893,  892,  890,  888,  886,  806,  804,  801,  798,  932,
92604  /*   450 */   884,  742,  739,  738,  658,  950,  916,  925,  923,  812,
92605  /*   460 */   922,  921,  920,  918,  915,  902,  808,  807,  734,  876,
92606  /*   470 */   875,  661,  906,  905,  904,  908,  912,  903,  770,  660,
92607  /*   480 */   657,  666,  723,  722,  730,  728,  727,  726,  725,  724,
92608  /*   490 */   721,  668,  676,  687,  715,  700,  699,  881,  883,  880,
92609  /*   500 */   879,  708,  707,  713,  712,  711,  710,  709,  706,  705,
92610  /*   510 */   704,  697,  696,  702,  695,  718,  717,  714,  694,  737,
92611  /*   520 */   736,  735,  732,  693,  692,  691,  823,  690,  689,  829,
92612  /*   530 */   828,  816,  860,  757,  756,  755,  767,  766,  779,  778,
92613  /*   540 */   814,  813,  780,  765,  759,  758,  774,  773,  772,  771,
92614  /*   550 */   763,  753,  785,  788,  787,  784,  845,  862,  769,  859,
92615  /*   560 */   931,  930,  929,  928,  927,  864,  863,  830,  827,  680,
92616  /*   570 */   681,  900,  898,  899,  897,  683,  682,  679,  678,  861,
92617  /*   580 */   748,  747,  857,  854,  846,  841,  858,  855,  847,  842,
92618  /*   590 */   840,  839,  825,  824,  822,  821,  817,  826,  671,  749,
92619  /*   600 */   745,  744,  815,  751,  750,  688,  686,  684,  665,  663,
92620  /*   610 */   656,  654,  653,  655,  651,  649,  648,  647,  646,  645,
92621  /*   620 */   674,  673,  672,  670,  669,  643,  640,  639,  635,  634,
92622  /*   630 */   632,
92623 };
92624
92625 /* The next table maps tokens into fallback tokens.  If a construct
92626 ** like the following:
92627 ** 
92628 **      %fallback ID X Y Z.
92629 **
92630 ** appears in the grammar, then ID becomes a fallback token for X, Y,
92631 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
92632 ** but it does not parse, the type of the token is changed to ID and
92633 ** the parse is retried before an error is thrown.
92634 */
92635 #ifdef YYFALLBACK
92636 static const YYCODETYPE yyFallback[] = {
92637     0,  /*          $ => nothing */
92638     0,  /*       SEMI => nothing */
92639    26,  /*    EXPLAIN => ID */
92640    26,  /*      QUERY => ID */
92641    26,  /*       PLAN => ID */
92642    26,  /*      BEGIN => ID */
92643     0,  /* TRANSACTION => nothing */
92644    26,  /*   DEFERRED => ID */
92645    26,  /*  IMMEDIATE => ID */
92646    26,  /*  EXCLUSIVE => ID */
92647     0,  /*     COMMIT => nothing */
92648    26,  /*        END => ID */
92649    26,  /*   ROLLBACK => ID */
92650    26,  /*  SAVEPOINT => ID */
92651    26,  /*    RELEASE => ID */
92652     0,  /*         TO => nothing */
92653     0,  /*      TABLE => nothing */
92654     0,  /*     CREATE => nothing */
92655    26,  /*         IF => ID */
92656     0,  /*        NOT => nothing */
92657     0,  /*     EXISTS => nothing */
92658    26,  /*       TEMP => ID */
92659     0,  /*         LP => nothing */
92660     0,  /*         RP => nothing */
92661     0,  /*         AS => nothing */
92662     0,  /*      COMMA => nothing */
92663     0,  /*         ID => nothing */
92664     0,  /*    INDEXED => nothing */
92665    26,  /*      ABORT => ID */
92666    26,  /*     ACTION => ID */
92667    26,  /*      AFTER => ID */
92668    26,  /*    ANALYZE => ID */
92669    26,  /*        ASC => ID */
92670    26,  /*     ATTACH => ID */
92671    26,  /*     BEFORE => ID */
92672    26,  /*         BY => ID */
92673    26,  /*    CASCADE => ID */
92674    26,  /*       CAST => ID */
92675    26,  /*   COLUMNKW => ID */
92676    26,  /*   CONFLICT => ID */
92677    26,  /*   DATABASE => ID */
92678    26,  /*       DESC => ID */
92679    26,  /*     DETACH => ID */
92680    26,  /*       EACH => ID */
92681    26,  /*       FAIL => ID */
92682    26,  /*        FOR => ID */
92683    26,  /*     IGNORE => ID */
92684    26,  /*  INITIALLY => ID */
92685    26,  /*    INSTEAD => ID */
92686    26,  /*    LIKE_KW => ID */
92687    26,  /*      MATCH => ID */
92688    26,  /*         NO => ID */
92689    26,  /*        KEY => ID */
92690    26,  /*         OF => ID */
92691    26,  /*     OFFSET => ID */
92692    26,  /*     PRAGMA => ID */
92693    26,  /*      RAISE => ID */
92694    26,  /*    REPLACE => ID */
92695    26,  /*   RESTRICT => ID */
92696    26,  /*        ROW => ID */
92697    26,  /*    TRIGGER => ID */
92698    26,  /*     VACUUM => ID */
92699    26,  /*       VIEW => ID */
92700    26,  /*    VIRTUAL => ID */
92701    26,  /*    REINDEX => ID */
92702    26,  /*     RENAME => ID */
92703    26,  /*   CTIME_KW => ID */
92704 };
92705 #endif /* YYFALLBACK */
92706
92707 /* The following structure represents a single element of the
92708 ** parser's stack.  Information stored includes:
92709 **
92710 **   +  The state number for the parser at this level of the stack.
92711 **
92712 **   +  The value of the token stored at this level of the stack.
92713 **      (In other words, the "major" token.)
92714 **
92715 **   +  The semantic value stored at this level of the stack.  This is
92716 **      the information used by the action routines in the grammar.
92717 **      It is sometimes called the "minor" token.
92718 */
92719 struct yyStackEntry {
92720   YYACTIONTYPE stateno;  /* The state-number */
92721   YYCODETYPE major;      /* The major token value.  This is the code
92722                          ** number for the token at this stack level */
92723   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
92724                          ** is the value of the token  */
92725 };
92726 typedef struct yyStackEntry yyStackEntry;
92727
92728 /* The state of the parser is completely contained in an instance of
92729 ** the following structure */
92730 struct yyParser {
92731   int yyidx;                    /* Index of top element in stack */
92732 #ifdef YYTRACKMAXSTACKDEPTH
92733   int yyidxMax;                 /* Maximum value of yyidx */
92734 #endif
92735   int yyerrcnt;                 /* Shifts left before out of the error */
92736   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
92737 #if YYSTACKDEPTH<=0
92738   int yystksz;                  /* Current side of the stack */
92739   yyStackEntry *yystack;        /* The parser's stack */
92740 #else
92741   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
92742 #endif
92743 };
92744 typedef struct yyParser yyParser;
92745
92746 #ifndef NDEBUG
92747 static FILE *yyTraceFILE = 0;
92748 static char *yyTracePrompt = 0;
92749 #endif /* NDEBUG */
92750
92751 #ifndef NDEBUG
92752 /* 
92753 ** Turn parser tracing on by giving a stream to which to write the trace
92754 ** and a prompt to preface each trace message.  Tracing is turned off
92755 ** by making either argument NULL 
92756 **
92757 ** Inputs:
92758 ** <ul>
92759 ** <li> A FILE* to which trace output should be written.
92760 **      If NULL, then tracing is turned off.
92761 ** <li> A prefix string written at the beginning of every
92762 **      line of trace output.  If NULL, then tracing is
92763 **      turned off.
92764 ** </ul>
92765 **
92766 ** Outputs:
92767 ** None.
92768 */
92769 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
92770   yyTraceFILE = TraceFILE;
92771   yyTracePrompt = zTracePrompt;
92772   if( yyTraceFILE==0 ) yyTracePrompt = 0;
92773   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
92774 }
92775 #endif /* NDEBUG */
92776
92777 #ifndef NDEBUG
92778 /* For tracing shifts, the names of all terminals and nonterminals
92779 ** are required.  The following table supplies these names */
92780 static const char *const yyTokenName[] = { 
92781   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
92782   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
92783   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
92784   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
92785   "TABLE",         "CREATE",        "IF",            "NOT",         
92786   "EXISTS",        "TEMP",          "LP",            "RP",          
92787   "AS",            "COMMA",         "ID",            "INDEXED",     
92788   "ABORT",         "ACTION",        "AFTER",         "ANALYZE",     
92789   "ASC",           "ATTACH",        "BEFORE",        "BY",          
92790   "CASCADE",       "CAST",          "COLUMNKW",      "CONFLICT",    
92791   "DATABASE",      "DESC",          "DETACH",        "EACH",        
92792   "FAIL",          "FOR",           "IGNORE",        "INITIALLY",   
92793   "INSTEAD",       "LIKE_KW",       "MATCH",         "NO",          
92794   "KEY",           "OF",            "OFFSET",        "PRAGMA",      
92795   "RAISE",         "REPLACE",       "RESTRICT",      "ROW",         
92796   "TRIGGER",       "VACUUM",        "VIEW",          "VIRTUAL",     
92797   "REINDEX",       "RENAME",        "CTIME_KW",      "ANY",         
92798   "OR",            "AND",           "IS",            "BETWEEN",     
92799   "IN",            "ISNULL",        "NOTNULL",       "NE",          
92800   "EQ",            "GT",            "LE",            "LT",          
92801   "GE",            "ESCAPE",        "BITAND",        "BITOR",       
92802   "LSHIFT",        "RSHIFT",        "PLUS",          "MINUS",       
92803   "STAR",          "SLASH",         "REM",           "CONCAT",      
92804   "COLLATE",       "BITNOT",        "STRING",        "JOIN_KW",     
92805   "CONSTRAINT",    "DEFAULT",       "NULL",          "PRIMARY",     
92806   "UNIQUE",        "CHECK",         "REFERENCES",    "AUTOINCR",    
92807   "ON",            "INSERT",        "DELETE",        "UPDATE",      
92808   "SET",           "DEFERRABLE",    "FOREIGN",       "DROP",        
92809   "UNION",         "ALL",           "EXCEPT",        "INTERSECT",   
92810   "SELECT",        "DISTINCT",      "DOT",           "FROM",        
92811   "JOIN",          "USING",         "ORDER",         "GROUP",       
92812   "HAVING",        "LIMIT",         "WHERE",         "INTO",        
92813   "VALUES",        "INTEGER",       "FLOAT",         "BLOB",        
92814   "REGISTER",      "VARIABLE",      "CASE",          "WHEN",        
92815   "THEN",          "ELSE",          "INDEX",         "ALTER",       
92816   "ADD",           "error",         "input",         "cmdlist",     
92817   "ecmd",          "explain",       "cmdx",          "cmd",         
92818   "transtype",     "trans_opt",     "nm",            "savepoint_opt",
92819   "create_table",  "create_table_args",  "createkw",      "temp",        
92820   "ifnotexists",   "dbnm",          "columnlist",    "conslist_opt",
92821   "select",        "column",        "columnid",      "type",        
92822   "carglist",      "id",            "ids",           "typetoken",   
92823   "typename",      "signed",        "plus_num",      "minus_num",   
92824   "carg",          "ccons",         "term",          "expr",        
92825   "onconf",        "sortorder",     "autoinc",       "idxlist_opt", 
92826   "refargs",       "defer_subclause",  "refarg",        "refact",      
92827   "init_deferred_pred_opt",  "conslist",      "tcons",         "idxlist",     
92828   "defer_subclause_opt",  "orconf",        "resolvetype",   "raisetype",   
92829   "ifexists",      "fullname",      "oneselect",     "multiselect_op",
92830   "distinct",      "selcollist",    "from",          "where_opt",   
92831   "groupby_opt",   "having_opt",    "orderby_opt",   "limit_opt",   
92832   "sclp",          "as",            "seltablist",    "stl_prefix",  
92833   "joinop",        "indexed_opt",   "on_opt",        "using_opt",   
92834   "joinop2",       "inscollist",    "sortlist",      "sortitem",    
92835   "nexprlist",     "setlist",       "insert_cmd",    "inscollist_opt",
92836   "itemlist",      "exprlist",      "likeop",        "escape",      
92837   "between_op",    "in_op",         "case_operand",  "case_exprlist",
92838   "case_else",     "uniqueflag",    "collate",       "nmnum",       
92839   "plus_opt",      "number",        "trigger_decl",  "trigger_cmd_list",
92840   "trigger_time",  "trigger_event",  "foreach_clause",  "when_clause", 
92841   "trigger_cmd",   "trnm",          "tridxby",       "database_kw_opt",
92842   "key_opt",       "add_column_fullname",  "kwcolumn_opt",  "create_vtab", 
92843   "vtabarglist",   "vtabarg",       "vtabargtoken",  "lp",          
92844   "anylist",     
92845 };
92846 #endif /* NDEBUG */
92847
92848 #ifndef NDEBUG
92849 /* For tracing reduce actions, the names of all rules are required.
92850 */
92851 static const char *const yyRuleName[] = {
92852  /*   0 */ "input ::= cmdlist",
92853  /*   1 */ "cmdlist ::= cmdlist ecmd",
92854  /*   2 */ "cmdlist ::= ecmd",
92855  /*   3 */ "ecmd ::= SEMI",
92856  /*   4 */ "ecmd ::= explain cmdx SEMI",
92857  /*   5 */ "explain ::=",
92858  /*   6 */ "explain ::= EXPLAIN",
92859  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
92860  /*   8 */ "cmdx ::= cmd",
92861  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
92862  /*  10 */ "trans_opt ::=",
92863  /*  11 */ "trans_opt ::= TRANSACTION",
92864  /*  12 */ "trans_opt ::= TRANSACTION nm",
92865  /*  13 */ "transtype ::=",
92866  /*  14 */ "transtype ::= DEFERRED",
92867  /*  15 */ "transtype ::= IMMEDIATE",
92868  /*  16 */ "transtype ::= EXCLUSIVE",
92869  /*  17 */ "cmd ::= COMMIT trans_opt",
92870  /*  18 */ "cmd ::= END trans_opt",
92871  /*  19 */ "cmd ::= ROLLBACK trans_opt",
92872  /*  20 */ "savepoint_opt ::= SAVEPOINT",
92873  /*  21 */ "savepoint_opt ::=",
92874  /*  22 */ "cmd ::= SAVEPOINT nm",
92875  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
92876  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
92877  /*  25 */ "cmd ::= create_table create_table_args",
92878  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
92879  /*  27 */ "createkw ::= CREATE",
92880  /*  28 */ "ifnotexists ::=",
92881  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
92882  /*  30 */ "temp ::= TEMP",
92883  /*  31 */ "temp ::=",
92884  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP",
92885  /*  33 */ "create_table_args ::= AS select",
92886  /*  34 */ "columnlist ::= columnlist COMMA column",
92887  /*  35 */ "columnlist ::= column",
92888  /*  36 */ "column ::= columnid type carglist",
92889  /*  37 */ "columnid ::= nm",
92890  /*  38 */ "id ::= ID",
92891  /*  39 */ "id ::= INDEXED",
92892  /*  40 */ "ids ::= ID|STRING",
92893  /*  41 */ "nm ::= id",
92894  /*  42 */ "nm ::= STRING",
92895  /*  43 */ "nm ::= JOIN_KW",
92896  /*  44 */ "type ::=",
92897  /*  45 */ "type ::= typetoken",
92898  /*  46 */ "typetoken ::= typename",
92899  /*  47 */ "typetoken ::= typename LP signed RP",
92900  /*  48 */ "typetoken ::= typename LP signed COMMA signed RP",
92901  /*  49 */ "typename ::= ids",
92902  /*  50 */ "typename ::= typename ids",
92903  /*  51 */ "signed ::= plus_num",
92904  /*  52 */ "signed ::= minus_num",
92905  /*  53 */ "carglist ::= carglist carg",
92906  /*  54 */ "carglist ::=",
92907  /*  55 */ "carg ::= CONSTRAINT nm ccons",
92908  /*  56 */ "carg ::= ccons",
92909  /*  57 */ "ccons ::= DEFAULT term",
92910  /*  58 */ "ccons ::= DEFAULT LP expr RP",
92911  /*  59 */ "ccons ::= DEFAULT PLUS term",
92912  /*  60 */ "ccons ::= DEFAULT MINUS term",
92913  /*  61 */ "ccons ::= DEFAULT id",
92914  /*  62 */ "ccons ::= NULL onconf",
92915  /*  63 */ "ccons ::= NOT NULL onconf",
92916  /*  64 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
92917  /*  65 */ "ccons ::= UNIQUE onconf",
92918  /*  66 */ "ccons ::= CHECK LP expr RP",
92919  /*  67 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
92920  /*  68 */ "ccons ::= defer_subclause",
92921  /*  69 */ "ccons ::= COLLATE ids",
92922  /*  70 */ "autoinc ::=",
92923  /*  71 */ "autoinc ::= AUTOINCR",
92924  /*  72 */ "refargs ::=",
92925  /*  73 */ "refargs ::= refargs refarg",
92926  /*  74 */ "refarg ::= MATCH nm",
92927  /*  75 */ "refarg ::= ON INSERT refact",
92928  /*  76 */ "refarg ::= ON DELETE refact",
92929  /*  77 */ "refarg ::= ON UPDATE refact",
92930  /*  78 */ "refact ::= SET NULL",
92931  /*  79 */ "refact ::= SET DEFAULT",
92932  /*  80 */ "refact ::= CASCADE",
92933  /*  81 */ "refact ::= RESTRICT",
92934  /*  82 */ "refact ::= NO ACTION",
92935  /*  83 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
92936  /*  84 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
92937  /*  85 */ "init_deferred_pred_opt ::=",
92938  /*  86 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
92939  /*  87 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
92940  /*  88 */ "conslist_opt ::=",
92941  /*  89 */ "conslist_opt ::= COMMA conslist",
92942  /*  90 */ "conslist ::= conslist COMMA tcons",
92943  /*  91 */ "conslist ::= conslist tcons",
92944  /*  92 */ "conslist ::= tcons",
92945  /*  93 */ "tcons ::= CONSTRAINT nm",
92946  /*  94 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
92947  /*  95 */ "tcons ::= UNIQUE LP idxlist RP onconf",
92948  /*  96 */ "tcons ::= CHECK LP expr RP onconf",
92949  /*  97 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
92950  /*  98 */ "defer_subclause_opt ::=",
92951  /*  99 */ "defer_subclause_opt ::= defer_subclause",
92952  /* 100 */ "onconf ::=",
92953  /* 101 */ "onconf ::= ON CONFLICT resolvetype",
92954  /* 102 */ "orconf ::=",
92955  /* 103 */ "orconf ::= OR resolvetype",
92956  /* 104 */ "resolvetype ::= raisetype",
92957  /* 105 */ "resolvetype ::= IGNORE",
92958  /* 106 */ "resolvetype ::= REPLACE",
92959  /* 107 */ "cmd ::= DROP TABLE ifexists fullname",
92960  /* 108 */ "ifexists ::= IF EXISTS",
92961  /* 109 */ "ifexists ::=",
92962  /* 110 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
92963  /* 111 */ "cmd ::= DROP VIEW ifexists fullname",
92964  /* 112 */ "cmd ::= select",
92965  /* 113 */ "select ::= oneselect",
92966  /* 114 */ "select ::= select multiselect_op oneselect",
92967  /* 115 */ "multiselect_op ::= UNION",
92968  /* 116 */ "multiselect_op ::= UNION ALL",
92969  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
92970  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
92971  /* 119 */ "distinct ::= DISTINCT",
92972  /* 120 */ "distinct ::= ALL",
92973  /* 121 */ "distinct ::=",
92974  /* 122 */ "sclp ::= selcollist COMMA",
92975  /* 123 */ "sclp ::=",
92976  /* 124 */ "selcollist ::= sclp expr as",
92977  /* 125 */ "selcollist ::= sclp STAR",
92978  /* 126 */ "selcollist ::= sclp nm DOT STAR",
92979  /* 127 */ "as ::= AS nm",
92980  /* 128 */ "as ::= ids",
92981  /* 129 */ "as ::=",
92982  /* 130 */ "from ::=",
92983  /* 131 */ "from ::= FROM seltablist",
92984  /* 132 */ "stl_prefix ::= seltablist joinop",
92985  /* 133 */ "stl_prefix ::=",
92986  /* 134 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
92987  /* 135 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
92988  /* 136 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
92989  /* 137 */ "dbnm ::=",
92990  /* 138 */ "dbnm ::= DOT nm",
92991  /* 139 */ "fullname ::= nm dbnm",
92992  /* 140 */ "joinop ::= COMMA|JOIN",
92993  /* 141 */ "joinop ::= JOIN_KW JOIN",
92994  /* 142 */ "joinop ::= JOIN_KW nm JOIN",
92995  /* 143 */ "joinop ::= JOIN_KW nm nm JOIN",
92996  /* 144 */ "on_opt ::= ON expr",
92997  /* 145 */ "on_opt ::=",
92998  /* 146 */ "indexed_opt ::=",
92999  /* 147 */ "indexed_opt ::= INDEXED BY nm",
93000  /* 148 */ "indexed_opt ::= NOT INDEXED",
93001  /* 149 */ "using_opt ::= USING LP inscollist RP",
93002  /* 150 */ "using_opt ::=",
93003  /* 151 */ "orderby_opt ::=",
93004  /* 152 */ "orderby_opt ::= ORDER BY sortlist",
93005  /* 153 */ "sortlist ::= sortlist COMMA sortitem sortorder",
93006  /* 154 */ "sortlist ::= sortitem sortorder",
93007  /* 155 */ "sortitem ::= expr",
93008  /* 156 */ "sortorder ::= ASC",
93009  /* 157 */ "sortorder ::= DESC",
93010  /* 158 */ "sortorder ::=",
93011  /* 159 */ "groupby_opt ::=",
93012  /* 160 */ "groupby_opt ::= GROUP BY nexprlist",
93013  /* 161 */ "having_opt ::=",
93014  /* 162 */ "having_opt ::= HAVING expr",
93015  /* 163 */ "limit_opt ::=",
93016  /* 164 */ "limit_opt ::= LIMIT expr",
93017  /* 165 */ "limit_opt ::= LIMIT expr OFFSET expr",
93018  /* 166 */ "limit_opt ::= LIMIT expr COMMA expr",
93019  /* 167 */ "cmd ::= DELETE FROM fullname indexed_opt where_opt",
93020  /* 168 */ "where_opt ::=",
93021  /* 169 */ "where_opt ::= WHERE expr",
93022  /* 170 */ "cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt",
93023  /* 171 */ "setlist ::= setlist COMMA nm EQ expr",
93024  /* 172 */ "setlist ::= nm EQ expr",
93025  /* 173 */ "cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP",
93026  /* 174 */ "cmd ::= insert_cmd INTO fullname inscollist_opt select",
93027  /* 175 */ "cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
93028  /* 176 */ "insert_cmd ::= INSERT orconf",
93029  /* 177 */ "insert_cmd ::= REPLACE",
93030  /* 178 */ "itemlist ::= itemlist COMMA expr",
93031  /* 179 */ "itemlist ::= expr",
93032  /* 180 */ "inscollist_opt ::=",
93033  /* 181 */ "inscollist_opt ::= LP inscollist RP",
93034  /* 182 */ "inscollist ::= inscollist COMMA nm",
93035  /* 183 */ "inscollist ::= nm",
93036  /* 184 */ "expr ::= term",
93037  /* 185 */ "expr ::= LP expr RP",
93038  /* 186 */ "term ::= NULL",
93039  /* 187 */ "expr ::= id",
93040  /* 188 */ "expr ::= JOIN_KW",
93041  /* 189 */ "expr ::= nm DOT nm",
93042  /* 190 */ "expr ::= nm DOT nm DOT nm",
93043  /* 191 */ "term ::= INTEGER|FLOAT|BLOB",
93044  /* 192 */ "term ::= STRING",
93045  /* 193 */ "expr ::= REGISTER",
93046  /* 194 */ "expr ::= VARIABLE",
93047  /* 195 */ "expr ::= expr COLLATE ids",
93048  /* 196 */ "expr ::= CAST LP expr AS typetoken RP",
93049  /* 197 */ "expr ::= ID LP distinct exprlist RP",
93050  /* 198 */ "expr ::= ID LP STAR RP",
93051  /* 199 */ "term ::= CTIME_KW",
93052  /* 200 */ "expr ::= expr AND expr",
93053  /* 201 */ "expr ::= expr OR expr",
93054  /* 202 */ "expr ::= expr LT|GT|GE|LE expr",
93055  /* 203 */ "expr ::= expr EQ|NE expr",
93056  /* 204 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
93057  /* 205 */ "expr ::= expr PLUS|MINUS expr",
93058  /* 206 */ "expr ::= expr STAR|SLASH|REM expr",
93059  /* 207 */ "expr ::= expr CONCAT expr",
93060  /* 208 */ "likeop ::= LIKE_KW",
93061  /* 209 */ "likeop ::= NOT LIKE_KW",
93062  /* 210 */ "likeop ::= MATCH",
93063  /* 211 */ "likeop ::= NOT MATCH",
93064  /* 212 */ "escape ::= ESCAPE expr",
93065  /* 213 */ "escape ::=",
93066  /* 214 */ "expr ::= expr likeop expr escape",
93067  /* 215 */ "expr ::= expr ISNULL|NOTNULL",
93068  /* 216 */ "expr ::= expr NOT NULL",
93069  /* 217 */ "expr ::= expr IS expr",
93070  /* 218 */ "expr ::= expr IS NOT expr",
93071  /* 219 */ "expr ::= NOT expr",
93072  /* 220 */ "expr ::= BITNOT expr",
93073  /* 221 */ "expr ::= MINUS expr",
93074  /* 222 */ "expr ::= PLUS expr",
93075  /* 223 */ "between_op ::= BETWEEN",
93076  /* 224 */ "between_op ::= NOT BETWEEN",
93077  /* 225 */ "expr ::= expr between_op expr AND expr",
93078  /* 226 */ "in_op ::= IN",
93079  /* 227 */ "in_op ::= NOT IN",
93080  /* 228 */ "expr ::= expr in_op LP exprlist RP",
93081  /* 229 */ "expr ::= LP select RP",
93082  /* 230 */ "expr ::= expr in_op LP select RP",
93083  /* 231 */ "expr ::= expr in_op nm dbnm",
93084  /* 232 */ "expr ::= EXISTS LP select RP",
93085  /* 233 */ "expr ::= CASE case_operand case_exprlist case_else END",
93086  /* 234 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
93087  /* 235 */ "case_exprlist ::= WHEN expr THEN expr",
93088  /* 236 */ "case_else ::= ELSE expr",
93089  /* 237 */ "case_else ::=",
93090  /* 238 */ "case_operand ::= expr",
93091  /* 239 */ "case_operand ::=",
93092  /* 240 */ "exprlist ::= nexprlist",
93093  /* 241 */ "exprlist ::=",
93094  /* 242 */ "nexprlist ::= nexprlist COMMA expr",
93095  /* 243 */ "nexprlist ::= expr",
93096  /* 244 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP",
93097  /* 245 */ "uniqueflag ::= UNIQUE",
93098  /* 246 */ "uniqueflag ::=",
93099  /* 247 */ "idxlist_opt ::=",
93100  /* 248 */ "idxlist_opt ::= LP idxlist RP",
93101  /* 249 */ "idxlist ::= idxlist COMMA nm collate sortorder",
93102  /* 250 */ "idxlist ::= nm collate sortorder",
93103  /* 251 */ "collate ::=",
93104  /* 252 */ "collate ::= COLLATE ids",
93105  /* 253 */ "cmd ::= DROP INDEX ifexists fullname",
93106  /* 254 */ "cmd ::= VACUUM",
93107  /* 255 */ "cmd ::= VACUUM nm",
93108  /* 256 */ "cmd ::= PRAGMA nm dbnm",
93109  /* 257 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
93110  /* 258 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
93111  /* 259 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
93112  /* 260 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
93113  /* 261 */ "nmnum ::= plus_num",
93114  /* 262 */ "nmnum ::= nm",
93115  /* 263 */ "nmnum ::= ON",
93116  /* 264 */ "nmnum ::= DELETE",
93117  /* 265 */ "nmnum ::= DEFAULT",
93118  /* 266 */ "plus_num ::= plus_opt number",
93119  /* 267 */ "minus_num ::= MINUS number",
93120  /* 268 */ "number ::= INTEGER|FLOAT",
93121  /* 269 */ "plus_opt ::= PLUS",
93122  /* 270 */ "plus_opt ::=",
93123  /* 271 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
93124  /* 272 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
93125  /* 273 */ "trigger_time ::= BEFORE",
93126  /* 274 */ "trigger_time ::= AFTER",
93127  /* 275 */ "trigger_time ::= INSTEAD OF",
93128  /* 276 */ "trigger_time ::=",
93129  /* 277 */ "trigger_event ::= DELETE|INSERT",
93130  /* 278 */ "trigger_event ::= UPDATE",
93131  /* 279 */ "trigger_event ::= UPDATE OF inscollist",
93132  /* 280 */ "foreach_clause ::=",
93133  /* 281 */ "foreach_clause ::= FOR EACH ROW",
93134  /* 282 */ "when_clause ::=",
93135  /* 283 */ "when_clause ::= WHEN expr",
93136  /* 284 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
93137  /* 285 */ "trigger_cmd_list ::= trigger_cmd SEMI",
93138  /* 286 */ "trnm ::= nm",
93139  /* 287 */ "trnm ::= nm DOT nm",
93140  /* 288 */ "tridxby ::=",
93141  /* 289 */ "tridxby ::= INDEXED BY nm",
93142  /* 290 */ "tridxby ::= NOT INDEXED",
93143  /* 291 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
93144  /* 292 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP",
93145  /* 293 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
93146  /* 294 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
93147  /* 295 */ "trigger_cmd ::= select",
93148  /* 296 */ "expr ::= RAISE LP IGNORE RP",
93149  /* 297 */ "expr ::= RAISE LP raisetype COMMA nm RP",
93150  /* 298 */ "raisetype ::= ROLLBACK",
93151  /* 299 */ "raisetype ::= ABORT",
93152  /* 300 */ "raisetype ::= FAIL",
93153  /* 301 */ "cmd ::= DROP TRIGGER ifexists fullname",
93154  /* 302 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
93155  /* 303 */ "cmd ::= DETACH database_kw_opt expr",
93156  /* 304 */ "key_opt ::=",
93157  /* 305 */ "key_opt ::= KEY expr",
93158  /* 306 */ "database_kw_opt ::= DATABASE",
93159  /* 307 */ "database_kw_opt ::=",
93160  /* 308 */ "cmd ::= REINDEX",
93161  /* 309 */ "cmd ::= REINDEX nm dbnm",
93162  /* 310 */ "cmd ::= ANALYZE",
93163  /* 311 */ "cmd ::= ANALYZE nm dbnm",
93164  /* 312 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
93165  /* 313 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
93166  /* 314 */ "add_column_fullname ::= fullname",
93167  /* 315 */ "kwcolumn_opt ::=",
93168  /* 316 */ "kwcolumn_opt ::= COLUMNKW",
93169  /* 317 */ "cmd ::= create_vtab",
93170  /* 318 */ "cmd ::= create_vtab LP vtabarglist RP",
93171  /* 319 */ "create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm",
93172  /* 320 */ "vtabarglist ::= vtabarg",
93173  /* 321 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
93174  /* 322 */ "vtabarg ::=",
93175  /* 323 */ "vtabarg ::= vtabarg vtabargtoken",
93176  /* 324 */ "vtabargtoken ::= ANY",
93177  /* 325 */ "vtabargtoken ::= lp anylist RP",
93178  /* 326 */ "lp ::= LP",
93179  /* 327 */ "anylist ::=",
93180  /* 328 */ "anylist ::= anylist LP anylist RP",
93181  /* 329 */ "anylist ::= anylist ANY",
93182 };
93183 #endif /* NDEBUG */
93184
93185
93186 #if YYSTACKDEPTH<=0
93187 /*
93188 ** Try to increase the size of the parser stack.
93189 */
93190 static void yyGrowStack(yyParser *p){
93191   int newSize;
93192   yyStackEntry *pNew;
93193
93194   newSize = p->yystksz*2 + 100;
93195   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
93196   if( pNew ){
93197     p->yystack = pNew;
93198     p->yystksz = newSize;
93199 #ifndef NDEBUG
93200     if( yyTraceFILE ){
93201       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
93202               yyTracePrompt, p->yystksz);
93203     }
93204 #endif
93205   }
93206 }
93207 #endif
93208
93209 /* 
93210 ** This function allocates a new parser.
93211 ** The only argument is a pointer to a function which works like
93212 ** malloc.
93213 **
93214 ** Inputs:
93215 ** A pointer to the function used to allocate memory.
93216 **
93217 ** Outputs:
93218 ** A pointer to a parser.  This pointer is used in subsequent calls
93219 ** to sqlite3Parser and sqlite3ParserFree.
93220 */
93221 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(size_t)){
93222   yyParser *pParser;
93223   pParser = (yyParser*)(*mallocProc)( (size_t)sizeof(yyParser) );
93224   if( pParser ){
93225     pParser->yyidx = -1;
93226 #ifdef YYTRACKMAXSTACKDEPTH
93227     pParser->yyidxMax = 0;
93228 #endif
93229 #if YYSTACKDEPTH<=0
93230     pParser->yystack = NULL;
93231     pParser->yystksz = 0;
93232     yyGrowStack(pParser);
93233 #endif
93234   }
93235   return pParser;
93236 }
93237
93238 /* The following function deletes the value associated with a
93239 ** symbol.  The symbol can be either a terminal or nonterminal.
93240 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
93241 ** the value.
93242 */
93243 static void yy_destructor(
93244   yyParser *yypParser,    /* The parser */
93245   YYCODETYPE yymajor,     /* Type code for object to destroy */
93246   YYMINORTYPE *yypminor   /* The object to be destroyed */
93247 ){
93248   sqlite3ParserARG_FETCH;
93249   switch( yymajor ){
93250     /* Here is inserted the actions which take place when a
93251     ** terminal or non-terminal is destroyed.  This can happen
93252     ** when the symbol is popped from the stack during a
93253     ** reduce or during error processing or when a parser is 
93254     ** being destroyed before it is finished parsing.
93255     **
93256     ** Note: during a reduce, the only symbols destroyed are those
93257     ** which appear on the RHS of the rule, but which are not used
93258     ** inside the C code.
93259     */
93260     case 160: /* select */
93261     case 194: /* oneselect */
93262 {
93263 sqlite3SelectDelete(pParse->db, (yypminor->yy3));
93264 }
93265       break;
93266     case 174: /* term */
93267     case 175: /* expr */
93268     case 223: /* escape */
93269 {
93270 sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
93271 }
93272       break;
93273     case 179: /* idxlist_opt */
93274     case 187: /* idxlist */
93275     case 197: /* selcollist */
93276     case 200: /* groupby_opt */
93277     case 202: /* orderby_opt */
93278     case 204: /* sclp */
93279     case 214: /* sortlist */
93280     case 216: /* nexprlist */
93281     case 217: /* setlist */
93282     case 220: /* itemlist */
93283     case 221: /* exprlist */
93284     case 227: /* case_exprlist */
93285 {
93286 sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
93287 }
93288       break;
93289     case 193: /* fullname */
93290     case 198: /* from */
93291     case 206: /* seltablist */
93292     case 207: /* stl_prefix */
93293 {
93294 sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
93295 }
93296       break;
93297     case 199: /* where_opt */
93298     case 201: /* having_opt */
93299     case 210: /* on_opt */
93300     case 215: /* sortitem */
93301     case 226: /* case_operand */
93302     case 228: /* case_else */
93303     case 239: /* when_clause */
93304     case 244: /* key_opt */
93305 {
93306 sqlite3ExprDelete(pParse->db, (yypminor->yy132));
93307 }
93308       break;
93309     case 211: /* using_opt */
93310     case 213: /* inscollist */
93311     case 219: /* inscollist_opt */
93312 {
93313 sqlite3IdListDelete(pParse->db, (yypminor->yy408));
93314 }
93315       break;
93316     case 235: /* trigger_cmd_list */
93317     case 240: /* trigger_cmd */
93318 {
93319 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
93320 }
93321       break;
93322     case 237: /* trigger_event */
93323 {
93324 sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
93325 }
93326       break;
93327     default:  break;   /* If no destructor action specified: do nothing */
93328   }
93329 }
93330
93331 /*
93332 ** Pop the parser's stack once.
93333 **
93334 ** If there is a destructor routine associated with the token which
93335 ** is popped from the stack, then call it.
93336 **
93337 ** Return the major token number for the symbol popped.
93338 */
93339 static int yy_pop_parser_stack(yyParser *pParser){
93340   YYCODETYPE yymajor;
93341   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
93342
93343   /* There is no mechanism by which the parser stack can be popped below
93344   ** empty in SQLite.  */
93345   if( NEVER(pParser->yyidx<0) ) return 0;
93346 #ifndef NDEBUG
93347   if( yyTraceFILE && pParser->yyidx>=0 ){
93348     fprintf(yyTraceFILE,"%sPopping %s\n",
93349       yyTracePrompt,
93350       yyTokenName[yytos->major]);
93351   }
93352 #endif
93353   yymajor = yytos->major;
93354   yy_destructor(pParser, yymajor, &yytos->minor);
93355   pParser->yyidx--;
93356   return yymajor;
93357 }
93358
93359 /* 
93360 ** Deallocate and destroy a parser.  Destructors are all called for
93361 ** all stack elements before shutting the parser down.
93362 **
93363 ** Inputs:
93364 ** <ul>
93365 ** <li>  A pointer to the parser.  This should be a pointer
93366 **       obtained from sqlite3ParserAlloc.
93367 ** <li>  A pointer to a function used to reclaim memory obtained
93368 **       from malloc.
93369 ** </ul>
93370 */
93371 SQLITE_PRIVATE void sqlite3ParserFree(
93372   void *p,                    /* The parser to be deleted */
93373   void (*freeProc)(void*)     /* Function used to reclaim memory */
93374 ){
93375   yyParser *pParser = (yyParser*)p;
93376   /* In SQLite, we never try to destroy a parser that was not successfully
93377   ** created in the first place. */
93378   if( NEVER(pParser==0) ) return;
93379   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
93380 #if YYSTACKDEPTH<=0
93381   free(pParser->yystack);
93382 #endif
93383   (*freeProc)((void*)pParser);
93384 }
93385
93386 /*
93387 ** Return the peak depth of the stack for a parser.
93388 */
93389 #ifdef YYTRACKMAXSTACKDEPTH
93390 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
93391   yyParser *pParser = (yyParser*)p;
93392   return pParser->yyidxMax;
93393 }
93394 #endif
93395
93396 /*
93397 ** Find the appropriate action for a parser given the terminal
93398 ** look-ahead token iLookAhead.
93399 **
93400 ** If the look-ahead token is YYNOCODE, then check to see if the action is
93401 ** independent of the look-ahead.  If it is, return the action, otherwise
93402 ** return YY_NO_ACTION.
93403 */
93404 static int yy_find_shift_action(
93405   yyParser *pParser,        /* The parser */
93406   YYCODETYPE iLookAhead     /* The look-ahead token */
93407 ){
93408   int i;
93409   int stateno = pParser->yystack[pParser->yyidx].stateno;
93410  
93411   if( stateno>YY_SHIFT_COUNT
93412    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
93413     return yy_default[stateno];
93414   }
93415   assert( iLookAhead!=YYNOCODE );
93416   i += iLookAhead;
93417   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
93418     if( iLookAhead>0 ){
93419 #ifdef YYFALLBACK
93420       YYCODETYPE iFallback;            /* Fallback token */
93421       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
93422              && (iFallback = yyFallback[iLookAhead])!=0 ){
93423 #ifndef NDEBUG
93424         if( yyTraceFILE ){
93425           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
93426              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
93427         }
93428 #endif
93429         return yy_find_shift_action(pParser, iFallback);
93430       }
93431 #endif
93432 #ifdef YYWILDCARD
93433       {
93434         int j = i - iLookAhead + YYWILDCARD;
93435         if( 
93436 #if YY_SHIFT_MIN+YYWILDCARD<0
93437           j>=0 &&
93438 #endif
93439 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
93440           j<YY_ACTTAB_COUNT &&
93441 #endif
93442           yy_lookahead[j]==YYWILDCARD
93443         ){
93444 #ifndef NDEBUG
93445           if( yyTraceFILE ){
93446             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
93447                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
93448           }
93449 #endif /* NDEBUG */
93450           return yy_action[j];
93451         }
93452       }
93453 #endif /* YYWILDCARD */
93454     }
93455     return yy_default[stateno];
93456   }else{
93457     return yy_action[i];
93458   }
93459 }
93460
93461 /*
93462 ** Find the appropriate action for a parser given the non-terminal
93463 ** look-ahead token iLookAhead.
93464 **
93465 ** If the look-ahead token is YYNOCODE, then check to see if the action is
93466 ** independent of the look-ahead.  If it is, return the action, otherwise
93467 ** return YY_NO_ACTION.
93468 */
93469 static int yy_find_reduce_action(
93470   int stateno,              /* Current state number */
93471   YYCODETYPE iLookAhead     /* The look-ahead token */
93472 ){
93473   int i;
93474 #ifdef YYERRORSYMBOL
93475   if( stateno>YY_REDUCE_COUNT ){
93476     return yy_default[stateno];
93477   }
93478 #else
93479   assert( stateno<=YY_REDUCE_COUNT );
93480 #endif
93481   i = yy_reduce_ofst[stateno];
93482   assert( i!=YY_REDUCE_USE_DFLT );
93483   assert( iLookAhead!=YYNOCODE );
93484   i += iLookAhead;
93485 #ifdef YYERRORSYMBOL
93486   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
93487     return yy_default[stateno];
93488   }
93489 #else
93490   assert( i>=0 && i<YY_ACTTAB_COUNT );
93491   assert( yy_lookahead[i]==iLookAhead );
93492 #endif
93493   return yy_action[i];
93494 }
93495
93496 /*
93497 ** The following routine is called if the stack overflows.
93498 */
93499 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
93500    sqlite3ParserARG_FETCH;
93501    yypParser->yyidx--;
93502 #ifndef NDEBUG
93503    if( yyTraceFILE ){
93504      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
93505    }
93506 #endif
93507    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
93508    /* Here code is inserted which will execute if the parser
93509    ** stack every overflows */
93510
93511   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
93512   sqlite3ErrorMsg(pParse, "parser stack overflow");
93513   pParse->parseError = 1;
93514    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
93515 }
93516
93517 /*
93518 ** Perform a shift action.
93519 */
93520 static void yy_shift(
93521   yyParser *yypParser,          /* The parser to be shifted */
93522   int yyNewState,               /* The new state to shift in */
93523   int yyMajor,                  /* The major token to shift in */
93524   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
93525 ){
93526   yyStackEntry *yytos;
93527   yypParser->yyidx++;
93528 #ifdef YYTRACKMAXSTACKDEPTH
93529   if( yypParser->yyidx>yypParser->yyidxMax ){
93530     yypParser->yyidxMax = yypParser->yyidx;
93531   }
93532 #endif
93533 #if YYSTACKDEPTH>0 
93534   if( yypParser->yyidx>=YYSTACKDEPTH ){
93535     yyStackOverflow(yypParser, yypMinor);
93536     return;
93537   }
93538 #else
93539   if( yypParser->yyidx>=yypParser->yystksz ){
93540     yyGrowStack(yypParser);
93541     if( yypParser->yyidx>=yypParser->yystksz ){
93542       yyStackOverflow(yypParser, yypMinor);
93543       return;
93544     }
93545   }
93546 #endif
93547   yytos = &yypParser->yystack[yypParser->yyidx];
93548   yytos->stateno = (YYACTIONTYPE)yyNewState;
93549   yytos->major = (YYCODETYPE)yyMajor;
93550   yytos->minor = *yypMinor;
93551 #ifndef NDEBUG
93552   if( yyTraceFILE && yypParser->yyidx>0 ){
93553     int i;
93554     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
93555     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
93556     for(i=1; i<=yypParser->yyidx; i++)
93557       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
93558     fprintf(yyTraceFILE,"\n");
93559   }
93560 #endif
93561 }
93562
93563 /* The following table contains information about every rule that
93564 ** is used during the reduce.
93565 */
93566 static const struct {
93567   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
93568   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
93569 } yyRuleInfo[] = {
93570   { 142, 1 },
93571   { 143, 2 },
93572   { 143, 1 },
93573   { 144, 1 },
93574   { 144, 3 },
93575   { 145, 0 },
93576   { 145, 1 },
93577   { 145, 3 },
93578   { 146, 1 },
93579   { 147, 3 },
93580   { 149, 0 },
93581   { 149, 1 },
93582   { 149, 2 },
93583   { 148, 0 },
93584   { 148, 1 },
93585   { 148, 1 },
93586   { 148, 1 },
93587   { 147, 2 },
93588   { 147, 2 },
93589   { 147, 2 },
93590   { 151, 1 },
93591   { 151, 0 },
93592   { 147, 2 },
93593   { 147, 3 },
93594   { 147, 5 },
93595   { 147, 2 },
93596   { 152, 6 },
93597   { 154, 1 },
93598   { 156, 0 },
93599   { 156, 3 },
93600   { 155, 1 },
93601   { 155, 0 },
93602   { 153, 4 },
93603   { 153, 2 },
93604   { 158, 3 },
93605   { 158, 1 },
93606   { 161, 3 },
93607   { 162, 1 },
93608   { 165, 1 },
93609   { 165, 1 },
93610   { 166, 1 },
93611   { 150, 1 },
93612   { 150, 1 },
93613   { 150, 1 },
93614   { 163, 0 },
93615   { 163, 1 },
93616   { 167, 1 },
93617   { 167, 4 },
93618   { 167, 6 },
93619   { 168, 1 },
93620   { 168, 2 },
93621   { 169, 1 },
93622   { 169, 1 },
93623   { 164, 2 },
93624   { 164, 0 },
93625   { 172, 3 },
93626   { 172, 1 },
93627   { 173, 2 },
93628   { 173, 4 },
93629   { 173, 3 },
93630   { 173, 3 },
93631   { 173, 2 },
93632   { 173, 2 },
93633   { 173, 3 },
93634   { 173, 5 },
93635   { 173, 2 },
93636   { 173, 4 },
93637   { 173, 4 },
93638   { 173, 1 },
93639   { 173, 2 },
93640   { 178, 0 },
93641   { 178, 1 },
93642   { 180, 0 },
93643   { 180, 2 },
93644   { 182, 2 },
93645   { 182, 3 },
93646   { 182, 3 },
93647   { 182, 3 },
93648   { 183, 2 },
93649   { 183, 2 },
93650   { 183, 1 },
93651   { 183, 1 },
93652   { 183, 2 },
93653   { 181, 3 },
93654   { 181, 2 },
93655   { 184, 0 },
93656   { 184, 2 },
93657   { 184, 2 },
93658   { 159, 0 },
93659   { 159, 2 },
93660   { 185, 3 },
93661   { 185, 2 },
93662   { 185, 1 },
93663   { 186, 2 },
93664   { 186, 7 },
93665   { 186, 5 },
93666   { 186, 5 },
93667   { 186, 10 },
93668   { 188, 0 },
93669   { 188, 1 },
93670   { 176, 0 },
93671   { 176, 3 },
93672   { 189, 0 },
93673   { 189, 2 },
93674   { 190, 1 },
93675   { 190, 1 },
93676   { 190, 1 },
93677   { 147, 4 },
93678   { 192, 2 },
93679   { 192, 0 },
93680   { 147, 8 },
93681   { 147, 4 },
93682   { 147, 1 },
93683   { 160, 1 },
93684   { 160, 3 },
93685   { 195, 1 },
93686   { 195, 2 },
93687   { 195, 1 },
93688   { 194, 9 },
93689   { 196, 1 },
93690   { 196, 1 },
93691   { 196, 0 },
93692   { 204, 2 },
93693   { 204, 0 },
93694   { 197, 3 },
93695   { 197, 2 },
93696   { 197, 4 },
93697   { 205, 2 },
93698   { 205, 1 },
93699   { 205, 0 },
93700   { 198, 0 },
93701   { 198, 2 },
93702   { 207, 2 },
93703   { 207, 0 },
93704   { 206, 7 },
93705   { 206, 7 },
93706   { 206, 7 },
93707   { 157, 0 },
93708   { 157, 2 },
93709   { 193, 2 },
93710   { 208, 1 },
93711   { 208, 2 },
93712   { 208, 3 },
93713   { 208, 4 },
93714   { 210, 2 },
93715   { 210, 0 },
93716   { 209, 0 },
93717   { 209, 3 },
93718   { 209, 2 },
93719   { 211, 4 },
93720   { 211, 0 },
93721   { 202, 0 },
93722   { 202, 3 },
93723   { 214, 4 },
93724   { 214, 2 },
93725   { 215, 1 },
93726   { 177, 1 },
93727   { 177, 1 },
93728   { 177, 0 },
93729   { 200, 0 },
93730   { 200, 3 },
93731   { 201, 0 },
93732   { 201, 2 },
93733   { 203, 0 },
93734   { 203, 2 },
93735   { 203, 4 },
93736   { 203, 4 },
93737   { 147, 5 },
93738   { 199, 0 },
93739   { 199, 2 },
93740   { 147, 7 },
93741   { 217, 5 },
93742   { 217, 3 },
93743   { 147, 8 },
93744   { 147, 5 },
93745   { 147, 6 },
93746   { 218, 2 },
93747   { 218, 1 },
93748   { 220, 3 },
93749   { 220, 1 },
93750   { 219, 0 },
93751   { 219, 3 },
93752   { 213, 3 },
93753   { 213, 1 },
93754   { 175, 1 },
93755   { 175, 3 },
93756   { 174, 1 },
93757   { 175, 1 },
93758   { 175, 1 },
93759   { 175, 3 },
93760   { 175, 5 },
93761   { 174, 1 },
93762   { 174, 1 },
93763   { 175, 1 },
93764   { 175, 1 },
93765   { 175, 3 },
93766   { 175, 6 },
93767   { 175, 5 },
93768   { 175, 4 },
93769   { 174, 1 },
93770   { 175, 3 },
93771   { 175, 3 },
93772   { 175, 3 },
93773   { 175, 3 },
93774   { 175, 3 },
93775   { 175, 3 },
93776   { 175, 3 },
93777   { 175, 3 },
93778   { 222, 1 },
93779   { 222, 2 },
93780   { 222, 1 },
93781   { 222, 2 },
93782   { 223, 2 },
93783   { 223, 0 },
93784   { 175, 4 },
93785   { 175, 2 },
93786   { 175, 3 },
93787   { 175, 3 },
93788   { 175, 4 },
93789   { 175, 2 },
93790   { 175, 2 },
93791   { 175, 2 },
93792   { 175, 2 },
93793   { 224, 1 },
93794   { 224, 2 },
93795   { 175, 5 },
93796   { 225, 1 },
93797   { 225, 2 },
93798   { 175, 5 },
93799   { 175, 3 },
93800   { 175, 5 },
93801   { 175, 4 },
93802   { 175, 4 },
93803   { 175, 5 },
93804   { 227, 5 },
93805   { 227, 4 },
93806   { 228, 2 },
93807   { 228, 0 },
93808   { 226, 1 },
93809   { 226, 0 },
93810   { 221, 1 },
93811   { 221, 0 },
93812   { 216, 3 },
93813   { 216, 1 },
93814   { 147, 11 },
93815   { 229, 1 },
93816   { 229, 0 },
93817   { 179, 0 },
93818   { 179, 3 },
93819   { 187, 5 },
93820   { 187, 3 },
93821   { 230, 0 },
93822   { 230, 2 },
93823   { 147, 4 },
93824   { 147, 1 },
93825   { 147, 2 },
93826   { 147, 3 },
93827   { 147, 5 },
93828   { 147, 6 },
93829   { 147, 5 },
93830   { 147, 6 },
93831   { 231, 1 },
93832   { 231, 1 },
93833   { 231, 1 },
93834   { 231, 1 },
93835   { 231, 1 },
93836   { 170, 2 },
93837   { 171, 2 },
93838   { 233, 1 },
93839   { 232, 1 },
93840   { 232, 0 },
93841   { 147, 5 },
93842   { 234, 11 },
93843   { 236, 1 },
93844   { 236, 1 },
93845   { 236, 2 },
93846   { 236, 0 },
93847   { 237, 1 },
93848   { 237, 1 },
93849   { 237, 3 },
93850   { 238, 0 },
93851   { 238, 3 },
93852   { 239, 0 },
93853   { 239, 2 },
93854   { 235, 3 },
93855   { 235, 2 },
93856   { 241, 1 },
93857   { 241, 3 },
93858   { 242, 0 },
93859   { 242, 3 },
93860   { 242, 2 },
93861   { 240, 7 },
93862   { 240, 8 },
93863   { 240, 5 },
93864   { 240, 5 },
93865   { 240, 1 },
93866   { 175, 4 },
93867   { 175, 6 },
93868   { 191, 1 },
93869   { 191, 1 },
93870   { 191, 1 },
93871   { 147, 4 },
93872   { 147, 6 },
93873   { 147, 3 },
93874   { 244, 0 },
93875   { 244, 2 },
93876   { 243, 1 },
93877   { 243, 0 },
93878   { 147, 1 },
93879   { 147, 3 },
93880   { 147, 1 },
93881   { 147, 3 },
93882   { 147, 6 },
93883   { 147, 6 },
93884   { 245, 1 },
93885   { 246, 0 },
93886   { 246, 1 },
93887   { 147, 1 },
93888   { 147, 4 },
93889   { 247, 7 },
93890   { 248, 1 },
93891   { 248, 3 },
93892   { 249, 0 },
93893   { 249, 2 },
93894   { 250, 1 },
93895   { 250, 3 },
93896   { 251, 1 },
93897   { 252, 0 },
93898   { 252, 4 },
93899   { 252, 2 },
93900 };
93901
93902 static void yy_accept(yyParser*);  /* Forward Declaration */
93903
93904 /*
93905 ** Perform a reduce action and the shift that must immediately
93906 ** follow the reduce.
93907 */
93908 static void yy_reduce(
93909   yyParser *yypParser,         /* The parser */
93910   int yyruleno                 /* Number of the rule by which to reduce */
93911 ){
93912   int yygoto;                     /* The next state */
93913   int yyact;                      /* The next action */
93914   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
93915   yyStackEntry *yymsp;            /* The top of the parser's stack */
93916   int yysize;                     /* Amount to pop the stack */
93917   sqlite3ParserARG_FETCH;
93918   yymsp = &yypParser->yystack[yypParser->yyidx];
93919 #ifndef NDEBUG
93920   if( yyTraceFILE && yyruleno>=0 
93921         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
93922     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
93923       yyRuleName[yyruleno]);
93924   }
93925 #endif /* NDEBUG */
93926
93927   /* Silence complaints from purify about yygotominor being uninitialized
93928   ** in some cases when it is copied into the stack after the following
93929   ** switch.  yygotominor is uninitialized when a rule reduces that does
93930   ** not set the value of its left-hand side nonterminal.  Leaving the
93931   ** value of the nonterminal uninitialized is utterly harmless as long
93932   ** as the value is never used.  So really the only thing this code
93933   ** accomplishes is to quieten purify.  
93934   **
93935   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
93936   ** without this code, their parser segfaults.  I'm not sure what there
93937   ** parser is doing to make this happen.  This is the second bug report
93938   ** from wireshark this week.  Clearly they are stressing Lemon in ways
93939   ** that it has not been previously stressed...  (SQLite ticket #2172)
93940   */
93941   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
93942   yygotominor = yyzerominor;
93943
93944
93945   switch( yyruleno ){
93946   /* Beginning here are the reduction cases.  A typical example
93947   ** follows:
93948   **   case 0:
93949   **  #line <lineno> <grammarfile>
93950   **     { ... }           // User supplied code
93951   **  #line <lineno> <thisfile>
93952   **     break;
93953   */
93954       case 5: /* explain ::= */
93955 { sqlite3BeginParse(pParse, 0); }
93956         break;
93957       case 6: /* explain ::= EXPLAIN */
93958 { sqlite3BeginParse(pParse, 1); }
93959         break;
93960       case 7: /* explain ::= EXPLAIN QUERY PLAN */
93961 { sqlite3BeginParse(pParse, 2); }
93962         break;
93963       case 8: /* cmdx ::= cmd */
93964 { sqlite3FinishCoding(pParse); }
93965         break;
93966       case 9: /* cmd ::= BEGIN transtype trans_opt */
93967 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
93968         break;
93969       case 13: /* transtype ::= */
93970 {yygotominor.yy328 = TK_DEFERRED;}
93971         break;
93972       case 14: /* transtype ::= DEFERRED */
93973       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
93974       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
93975       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
93976       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
93977 {yygotominor.yy328 = yymsp[0].major;}
93978         break;
93979       case 17: /* cmd ::= COMMIT trans_opt */
93980       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
93981 {sqlite3CommitTransaction(pParse);}
93982         break;
93983       case 19: /* cmd ::= ROLLBACK trans_opt */
93984 {sqlite3RollbackTransaction(pParse);}
93985         break;
93986       case 22: /* cmd ::= SAVEPOINT nm */
93987 {
93988   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
93989 }
93990         break;
93991       case 23: /* cmd ::= RELEASE savepoint_opt nm */
93992 {
93993   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
93994 }
93995         break;
93996       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
93997 {
93998   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
93999 }
94000         break;
94001       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
94002 {
94003    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
94004 }
94005         break;
94006       case 27: /* createkw ::= CREATE */
94007 {
94008   pParse->db->lookaside.bEnabled = 0;
94009   yygotominor.yy0 = yymsp[0].minor.yy0;
94010 }
94011         break;
94012       case 28: /* ifnotexists ::= */
94013       case 31: /* temp ::= */ yytestcase(yyruleno==31);
94014       case 70: /* autoinc ::= */ yytestcase(yyruleno==70);
94015       case 83: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==83);
94016       case 85: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==85);
94017       case 87: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==87);
94018       case 98: /* defer_subclause_opt ::= */ yytestcase(yyruleno==98);
94019       case 109: /* ifexists ::= */ yytestcase(yyruleno==109);
94020       case 120: /* distinct ::= ALL */ yytestcase(yyruleno==120);
94021       case 121: /* distinct ::= */ yytestcase(yyruleno==121);
94022       case 223: /* between_op ::= BETWEEN */ yytestcase(yyruleno==223);
94023       case 226: /* in_op ::= IN */ yytestcase(yyruleno==226);
94024 {yygotominor.yy328 = 0;}
94025         break;
94026       case 29: /* ifnotexists ::= IF NOT EXISTS */
94027       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
94028       case 71: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==71);
94029       case 86: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==86);
94030       case 108: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==108);
94031       case 119: /* distinct ::= DISTINCT */ yytestcase(yyruleno==119);
94032       case 224: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==224);
94033       case 227: /* in_op ::= NOT IN */ yytestcase(yyruleno==227);
94034 {yygotominor.yy328 = 1;}
94035         break;
94036       case 32: /* create_table_args ::= LP columnlist conslist_opt RP */
94037 {
94038   sqlite3EndTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0);
94039 }
94040         break;
94041       case 33: /* create_table_args ::= AS select */
94042 {
94043   sqlite3EndTable(pParse,0,0,yymsp[0].minor.yy3);
94044   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
94045 }
94046         break;
94047       case 36: /* column ::= columnid type carglist */
94048 {
94049   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
94050   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
94051 }
94052         break;
94053       case 37: /* columnid ::= nm */
94054 {
94055   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
94056   yygotominor.yy0 = yymsp[0].minor.yy0;
94057 }
94058         break;
94059       case 38: /* id ::= ID */
94060       case 39: /* id ::= INDEXED */ yytestcase(yyruleno==39);
94061       case 40: /* ids ::= ID|STRING */ yytestcase(yyruleno==40);
94062       case 41: /* nm ::= id */ yytestcase(yyruleno==41);
94063       case 42: /* nm ::= STRING */ yytestcase(yyruleno==42);
94064       case 43: /* nm ::= JOIN_KW */ yytestcase(yyruleno==43);
94065       case 46: /* typetoken ::= typename */ yytestcase(yyruleno==46);
94066       case 49: /* typename ::= ids */ yytestcase(yyruleno==49);
94067       case 127: /* as ::= AS nm */ yytestcase(yyruleno==127);
94068       case 128: /* as ::= ids */ yytestcase(yyruleno==128);
94069       case 138: /* dbnm ::= DOT nm */ yytestcase(yyruleno==138);
94070       case 147: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==147);
94071       case 252: /* collate ::= COLLATE ids */ yytestcase(yyruleno==252);
94072       case 261: /* nmnum ::= plus_num */ yytestcase(yyruleno==261);
94073       case 262: /* nmnum ::= nm */ yytestcase(yyruleno==262);
94074       case 263: /* nmnum ::= ON */ yytestcase(yyruleno==263);
94075       case 264: /* nmnum ::= DELETE */ yytestcase(yyruleno==264);
94076       case 265: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==265);
94077       case 266: /* plus_num ::= plus_opt number */ yytestcase(yyruleno==266);
94078       case 267: /* minus_num ::= MINUS number */ yytestcase(yyruleno==267);
94079       case 268: /* number ::= INTEGER|FLOAT */ yytestcase(yyruleno==268);
94080       case 286: /* trnm ::= nm */ yytestcase(yyruleno==286);
94081 {yygotominor.yy0 = yymsp[0].minor.yy0;}
94082         break;
94083       case 45: /* type ::= typetoken */
94084 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
94085         break;
94086       case 47: /* typetoken ::= typename LP signed RP */
94087 {
94088   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
94089   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
94090 }
94091         break;
94092       case 48: /* typetoken ::= typename LP signed COMMA signed RP */
94093 {
94094   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
94095   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
94096 }
94097         break;
94098       case 50: /* typename ::= typename ids */
94099 {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);}
94100         break;
94101       case 57: /* ccons ::= DEFAULT term */
94102       case 59: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==59);
94103 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
94104         break;
94105       case 58: /* ccons ::= DEFAULT LP expr RP */
94106 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
94107         break;
94108       case 60: /* ccons ::= DEFAULT MINUS term */
94109 {
94110   ExprSpan v;
94111   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
94112   v.zStart = yymsp[-1].minor.yy0.z;
94113   v.zEnd = yymsp[0].minor.yy346.zEnd;
94114   sqlite3AddDefaultValue(pParse,&v);
94115 }
94116         break;
94117       case 61: /* ccons ::= DEFAULT id */
94118 {
94119   ExprSpan v;
94120   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
94121   sqlite3AddDefaultValue(pParse,&v);
94122 }
94123         break;
94124       case 63: /* ccons ::= NOT NULL onconf */
94125 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
94126         break;
94127       case 64: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
94128 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
94129         break;
94130       case 65: /* ccons ::= UNIQUE onconf */
94131 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
94132         break;
94133       case 66: /* ccons ::= CHECK LP expr RP */
94134 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
94135         break;
94136       case 67: /* ccons ::= REFERENCES nm idxlist_opt refargs */
94137 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
94138         break;
94139       case 68: /* ccons ::= defer_subclause */
94140 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
94141         break;
94142       case 69: /* ccons ::= COLLATE ids */
94143 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
94144         break;
94145       case 72: /* refargs ::= */
94146 { yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
94147         break;
94148       case 73: /* refargs ::= refargs refarg */
94149 { yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
94150         break;
94151       case 74: /* refarg ::= MATCH nm */
94152       case 75: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==75);
94153 { yygotominor.yy429.value = 0;     yygotominor.yy429.mask = 0x000000; }
94154         break;
94155       case 76: /* refarg ::= ON DELETE refact */
94156 { yygotominor.yy429.value = yymsp[0].minor.yy328;     yygotominor.yy429.mask = 0x0000ff; }
94157         break;
94158       case 77: /* refarg ::= ON UPDATE refact */
94159 { yygotominor.yy429.value = yymsp[0].minor.yy328<<8;  yygotominor.yy429.mask = 0x00ff00; }
94160         break;
94161       case 78: /* refact ::= SET NULL */
94162 { yygotominor.yy328 = OE_SetNull;  /* EV: R-33326-45252 */}
94163         break;
94164       case 79: /* refact ::= SET DEFAULT */
94165 { yygotominor.yy328 = OE_SetDflt;  /* EV: R-33326-45252 */}
94166         break;
94167       case 80: /* refact ::= CASCADE */
94168 { yygotominor.yy328 = OE_Cascade;  /* EV: R-33326-45252 */}
94169         break;
94170       case 81: /* refact ::= RESTRICT */
94171 { yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
94172         break;
94173       case 82: /* refact ::= NO ACTION */
94174 { yygotominor.yy328 = OE_None;     /* EV: R-33326-45252 */}
94175         break;
94176       case 84: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
94177       case 99: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==99);
94178       case 101: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==101);
94179       case 104: /* resolvetype ::= raisetype */ yytestcase(yyruleno==104);
94180 {yygotominor.yy328 = yymsp[0].minor.yy328;}
94181         break;
94182       case 88: /* conslist_opt ::= */
94183 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
94184         break;
94185       case 89: /* conslist_opt ::= COMMA conslist */
94186 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
94187         break;
94188       case 94: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
94189 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
94190         break;
94191       case 95: /* tcons ::= UNIQUE LP idxlist RP onconf */
94192 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
94193         break;
94194       case 96: /* tcons ::= CHECK LP expr RP onconf */
94195 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
94196         break;
94197       case 97: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
94198 {
94199     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
94200     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
94201 }
94202         break;
94203       case 100: /* onconf ::= */
94204 {yygotominor.yy328 = OE_Default;}
94205         break;
94206       case 102: /* orconf ::= */
94207 {yygotominor.yy186 = OE_Default;}
94208         break;
94209       case 103: /* orconf ::= OR resolvetype */
94210 {yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
94211         break;
94212       case 105: /* resolvetype ::= IGNORE */
94213 {yygotominor.yy328 = OE_Ignore;}
94214         break;
94215       case 106: /* resolvetype ::= REPLACE */
94216 {yygotominor.yy328 = OE_Replace;}
94217         break;
94218       case 107: /* cmd ::= DROP TABLE ifexists fullname */
94219 {
94220   sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
94221 }
94222         break;
94223       case 110: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
94224 {
94225   sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy3, yymsp[-6].minor.yy328, yymsp[-4].minor.yy328);
94226 }
94227         break;
94228       case 111: /* cmd ::= DROP VIEW ifexists fullname */
94229 {
94230   sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
94231 }
94232         break;
94233       case 112: /* cmd ::= select */
94234 {
94235   SelectDest dest = {SRT_Output, 0, 0, 0, 0};
94236   sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
94237   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
94238 }
94239         break;
94240       case 113: /* select ::= oneselect */
94241 {yygotominor.yy3 = yymsp[0].minor.yy3;}
94242         break;
94243       case 114: /* select ::= select multiselect_op oneselect */
94244 {
94245   if( yymsp[0].minor.yy3 ){
94246     yymsp[0].minor.yy3->op = (u8)yymsp[-1].minor.yy328;
94247     yymsp[0].minor.yy3->pPrior = yymsp[-2].minor.yy3;
94248   }else{
94249     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
94250   }
94251   yygotominor.yy3 = yymsp[0].minor.yy3;
94252 }
94253         break;
94254       case 116: /* multiselect_op ::= UNION ALL */
94255 {yygotominor.yy328 = TK_ALL;}
94256         break;
94257       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
94258 {
94259   yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy14,yymsp[-5].minor.yy65,yymsp[-4].minor.yy132,yymsp[-3].minor.yy14,yymsp[-2].minor.yy132,yymsp[-1].minor.yy14,yymsp[-7].minor.yy328,yymsp[0].minor.yy476.pLimit,yymsp[0].minor.yy476.pOffset);
94260 }
94261         break;
94262       case 122: /* sclp ::= selcollist COMMA */
94263       case 248: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==248);
94264 {yygotominor.yy14 = yymsp[-1].minor.yy14;}
94265         break;
94266       case 123: /* sclp ::= */
94267       case 151: /* orderby_opt ::= */ yytestcase(yyruleno==151);
94268       case 159: /* groupby_opt ::= */ yytestcase(yyruleno==159);
94269       case 241: /* exprlist ::= */ yytestcase(yyruleno==241);
94270       case 247: /* idxlist_opt ::= */ yytestcase(yyruleno==247);
94271 {yygotominor.yy14 = 0;}
94272         break;
94273       case 124: /* selcollist ::= sclp expr as */
94274 {
94275    yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
94276    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
94277    sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
94278 }
94279         break;
94280       case 125: /* selcollist ::= sclp STAR */
94281 {
94282   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
94283   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
94284 }
94285         break;
94286       case 126: /* selcollist ::= sclp nm DOT STAR */
94287 {
94288   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
94289   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
94290   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
94291   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
94292 }
94293         break;
94294       case 129: /* as ::= */
94295 {yygotominor.yy0.n = 0;}
94296         break;
94297       case 130: /* from ::= */
94298 {yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
94299         break;
94300       case 131: /* from ::= FROM seltablist */
94301 {
94302   yygotominor.yy65 = yymsp[0].minor.yy65;
94303   sqlite3SrcListShiftJoinType(yygotominor.yy65);
94304 }
94305         break;
94306       case 132: /* stl_prefix ::= seltablist joinop */
94307 {
94308    yygotominor.yy65 = yymsp[-1].minor.yy65;
94309    if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
94310 }
94311         break;
94312       case 133: /* stl_prefix ::= */
94313 {yygotominor.yy65 = 0;}
94314         break;
94315       case 134: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
94316 {
94317   yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
94318   sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
94319 }
94320         break;
94321       case 135: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
94322 {
94323     yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy3,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
94324   }
94325         break;
94326       case 136: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
94327 {
94328     if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
94329       yygotominor.yy65 = yymsp[-4].minor.yy65;
94330     }else{
94331       Select *pSubquery;
94332       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
94333       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,0,0,0);
94334       yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
94335     }
94336   }
94337         break;
94338       case 137: /* dbnm ::= */
94339       case 146: /* indexed_opt ::= */ yytestcase(yyruleno==146);
94340 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
94341         break;
94342       case 139: /* fullname ::= nm dbnm */
94343 {yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
94344         break;
94345       case 140: /* joinop ::= COMMA|JOIN */
94346 { yygotominor.yy328 = JT_INNER; }
94347         break;
94348       case 141: /* joinop ::= JOIN_KW JOIN */
94349 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
94350         break;
94351       case 142: /* joinop ::= JOIN_KW nm JOIN */
94352 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
94353         break;
94354       case 143: /* joinop ::= JOIN_KW nm nm JOIN */
94355 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
94356         break;
94357       case 144: /* on_opt ::= ON expr */
94358       case 155: /* sortitem ::= expr */ yytestcase(yyruleno==155);
94359       case 162: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==162);
94360       case 169: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==169);
94361       case 236: /* case_else ::= ELSE expr */ yytestcase(yyruleno==236);
94362       case 238: /* case_operand ::= expr */ yytestcase(yyruleno==238);
94363 {yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
94364         break;
94365       case 145: /* on_opt ::= */
94366       case 161: /* having_opt ::= */ yytestcase(yyruleno==161);
94367       case 168: /* where_opt ::= */ yytestcase(yyruleno==168);
94368       case 237: /* case_else ::= */ yytestcase(yyruleno==237);
94369       case 239: /* case_operand ::= */ yytestcase(yyruleno==239);
94370 {yygotominor.yy132 = 0;}
94371         break;
94372       case 148: /* indexed_opt ::= NOT INDEXED */
94373 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
94374         break;
94375       case 149: /* using_opt ::= USING LP inscollist RP */
94376       case 181: /* inscollist_opt ::= LP inscollist RP */ yytestcase(yyruleno==181);
94377 {yygotominor.yy408 = yymsp[-1].minor.yy408;}
94378         break;
94379       case 150: /* using_opt ::= */
94380       case 180: /* inscollist_opt ::= */ yytestcase(yyruleno==180);
94381 {yygotominor.yy408 = 0;}
94382         break;
94383       case 152: /* orderby_opt ::= ORDER BY sortlist */
94384       case 160: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==160);
94385       case 240: /* exprlist ::= nexprlist */ yytestcase(yyruleno==240);
94386 {yygotominor.yy14 = yymsp[0].minor.yy14;}
94387         break;
94388       case 153: /* sortlist ::= sortlist COMMA sortitem sortorder */
94389 {
94390   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy132);
94391   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
94392 }
94393         break;
94394       case 154: /* sortlist ::= sortitem sortorder */
94395 {
94396   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy132);
94397   if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
94398 }
94399         break;
94400       case 156: /* sortorder ::= ASC */
94401       case 158: /* sortorder ::= */ yytestcase(yyruleno==158);
94402 {yygotominor.yy328 = SQLITE_SO_ASC;}
94403         break;
94404       case 157: /* sortorder ::= DESC */
94405 {yygotominor.yy328 = SQLITE_SO_DESC;}
94406         break;
94407       case 163: /* limit_opt ::= */
94408 {yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
94409         break;
94410       case 164: /* limit_opt ::= LIMIT expr */
94411 {yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
94412         break;
94413       case 165: /* limit_opt ::= LIMIT expr OFFSET expr */
94414 {yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
94415         break;
94416       case 166: /* limit_opt ::= LIMIT expr COMMA expr */
94417 {yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
94418         break;
94419       case 167: /* cmd ::= DELETE FROM fullname indexed_opt where_opt */
94420 {
94421   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
94422   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
94423 }
94424         break;
94425       case 170: /* cmd ::= UPDATE orconf fullname indexed_opt SET setlist where_opt */
94426 {
94427   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
94428   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list"); 
94429   sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
94430 }
94431         break;
94432       case 171: /* setlist ::= setlist COMMA nm EQ expr */
94433 {
94434   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
94435   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
94436 }
94437         break;
94438       case 172: /* setlist ::= nm EQ expr */
94439 {
94440   yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
94441   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
94442 }
94443         break;
94444       case 173: /* cmd ::= insert_cmd INTO fullname inscollist_opt VALUES LP itemlist RP */
94445 {sqlite3Insert(pParse, yymsp[-5].minor.yy65, yymsp[-1].minor.yy14, 0, yymsp[-4].minor.yy408, yymsp[-7].minor.yy186);}
94446         break;
94447       case 174: /* cmd ::= insert_cmd INTO fullname inscollist_opt select */
94448 {sqlite3Insert(pParse, yymsp[-2].minor.yy65, 0, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);}
94449         break;
94450       case 175: /* cmd ::= insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
94451 {sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);}
94452         break;
94453       case 176: /* insert_cmd ::= INSERT orconf */
94454 {yygotominor.yy186 = yymsp[0].minor.yy186;}
94455         break;
94456       case 177: /* insert_cmd ::= REPLACE */
94457 {yygotominor.yy186 = OE_Replace;}
94458         break;
94459       case 178: /* itemlist ::= itemlist COMMA expr */
94460       case 242: /* nexprlist ::= nexprlist COMMA expr */ yytestcase(yyruleno==242);
94461 {yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
94462         break;
94463       case 179: /* itemlist ::= expr */
94464       case 243: /* nexprlist ::= expr */ yytestcase(yyruleno==243);
94465 {yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
94466         break;
94467       case 182: /* inscollist ::= inscollist COMMA nm */
94468 {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
94469         break;
94470       case 183: /* inscollist ::= nm */
94471 {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
94472         break;
94473       case 184: /* expr ::= term */
94474       case 212: /* escape ::= ESCAPE expr */ yytestcase(yyruleno==212);
94475 {yygotominor.yy346 = yymsp[0].minor.yy346;}
94476         break;
94477       case 185: /* expr ::= LP expr RP */
94478 {yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
94479         break;
94480       case 186: /* term ::= NULL */
94481       case 191: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==191);
94482       case 192: /* term ::= STRING */ yytestcase(yyruleno==192);
94483 {spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
94484         break;
94485       case 187: /* expr ::= id */
94486       case 188: /* expr ::= JOIN_KW */ yytestcase(yyruleno==188);
94487 {spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
94488         break;
94489       case 189: /* expr ::= nm DOT nm */
94490 {
94491   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
94492   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
94493   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
94494   spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
94495 }
94496         break;
94497       case 190: /* expr ::= nm DOT nm DOT nm */
94498 {
94499   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
94500   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
94501   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
94502   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
94503   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
94504   spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
94505 }
94506         break;
94507       case 193: /* expr ::= REGISTER */
94508 {
94509   /* When doing a nested parse, one can include terms in an expression
94510   ** that look like this:   #1 #2 ...  These terms refer to registers
94511   ** in the virtual machine.  #N is the N-th register. */
94512   if( pParse->nested==0 ){
94513     sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
94514     yygotominor.yy346.pExpr = 0;
94515   }else{
94516     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
94517     if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
94518   }
94519   spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
94520 }
94521         break;
94522       case 194: /* expr ::= VARIABLE */
94523 {
94524   spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
94525   sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
94526   spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
94527 }
94528         break;
94529       case 195: /* expr ::= expr COLLATE ids */
94530 {
94531   yygotominor.yy346.pExpr = sqlite3ExprSetColl(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0);
94532   yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
94533   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
94534 }
94535         break;
94536       case 196: /* expr ::= CAST LP expr AS typetoken RP */
94537 {
94538   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
94539   spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
94540 }
94541         break;
94542       case 197: /* expr ::= ID LP distinct exprlist RP */
94543 {
94544   if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
94545     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
94546   }
94547   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
94548   spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
94549   if( yymsp[-2].minor.yy328 && yygotominor.yy346.pExpr ){
94550     yygotominor.yy346.pExpr->flags |= EP_Distinct;
94551   }
94552 }
94553         break;
94554       case 198: /* expr ::= ID LP STAR RP */
94555 {
94556   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
94557   spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
94558 }
94559         break;
94560       case 199: /* term ::= CTIME_KW */
94561 {
94562   /* The CURRENT_TIME, CURRENT_DATE, and CURRENT_TIMESTAMP values are
94563   ** treated as functions that return constants */
94564   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0,&yymsp[0].minor.yy0);
94565   if( yygotominor.yy346.pExpr ){
94566     yygotominor.yy346.pExpr->op = TK_CONST_FUNC;  
94567   }
94568   spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
94569 }
94570         break;
94571       case 200: /* expr ::= expr AND expr */
94572       case 201: /* expr ::= expr OR expr */ yytestcase(yyruleno==201);
94573       case 202: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==202);
94574       case 203: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==203);
94575       case 204: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==204);
94576       case 205: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==205);
94577       case 206: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==206);
94578       case 207: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==207);
94579 {spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
94580         break;
94581       case 208: /* likeop ::= LIKE_KW */
94582       case 210: /* likeop ::= MATCH */ yytestcase(yyruleno==210);
94583 {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.not = 0;}
94584         break;
94585       case 209: /* likeop ::= NOT LIKE_KW */
94586       case 211: /* likeop ::= NOT MATCH */ yytestcase(yyruleno==211);
94587 {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.not = 1;}
94588         break;
94589       case 213: /* escape ::= */
94590 {memset(&yygotominor.yy346,0,sizeof(yygotominor.yy346));}
94591         break;
94592       case 214: /* expr ::= expr likeop expr escape */
94593 {
94594   ExprList *pList;
94595   pList = sqlite3ExprListAppend(pParse,0, yymsp[-1].minor.yy346.pExpr);
94596   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-3].minor.yy346.pExpr);
94597   if( yymsp[0].minor.yy346.pExpr ){
94598     pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
94599   }
94600   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-2].minor.yy96.eOperator);
94601   if( yymsp[-2].minor.yy96.not ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
94602   yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
94603   yygotominor.yy346.zEnd = yymsp[-1].minor.yy346.zEnd;
94604   if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
94605 }
94606         break;
94607       case 215: /* expr ::= expr ISNULL|NOTNULL */
94608 {spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
94609         break;
94610       case 216: /* expr ::= expr NOT NULL */
94611 {spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
94612         break;
94613       case 217: /* expr ::= expr IS expr */
94614 {
94615   spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
94616   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
94617 }
94618         break;
94619       case 218: /* expr ::= expr IS NOT expr */
94620 {
94621   spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
94622   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
94623 }
94624         break;
94625       case 219: /* expr ::= NOT expr */
94626       case 220: /* expr ::= BITNOT expr */ yytestcase(yyruleno==220);
94627 {spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
94628         break;
94629       case 221: /* expr ::= MINUS expr */
94630 {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
94631         break;
94632       case 222: /* expr ::= PLUS expr */
94633 {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
94634         break;
94635       case 225: /* expr ::= expr between_op expr AND expr */
94636 {
94637   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
94638   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
94639   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
94640   if( yygotominor.yy346.pExpr ){
94641     yygotominor.yy346.pExpr->x.pList = pList;
94642   }else{
94643     sqlite3ExprListDelete(pParse->db, pList);
94644   } 
94645   if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
94646   yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
94647   yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
94648 }
94649         break;
94650       case 228: /* expr ::= expr in_op LP exprlist RP */
94651 {
94652     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
94653     if( yygotominor.yy346.pExpr ){
94654       yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
94655       sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
94656     }else{
94657       sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
94658     }
94659     if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
94660     yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
94661     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
94662   }
94663         break;
94664       case 229: /* expr ::= LP select RP */
94665 {
94666     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
94667     if( yygotominor.yy346.pExpr ){
94668       yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
94669       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
94670       sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
94671     }else{
94672       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
94673     }
94674     yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
94675     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
94676   }
94677         break;
94678       case 230: /* expr ::= expr in_op LP select RP */
94679 {
94680     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
94681     if( yygotominor.yy346.pExpr ){
94682       yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
94683       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
94684       sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
94685     }else{
94686       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
94687     }
94688     if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
94689     yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
94690     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
94691   }
94692         break;
94693       case 231: /* expr ::= expr in_op nm dbnm */
94694 {
94695     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
94696     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
94697     if( yygotominor.yy346.pExpr ){
94698       yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
94699       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
94700       sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
94701     }else{
94702       sqlite3SrcListDelete(pParse->db, pSrc);
94703     }
94704     if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
94705     yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
94706     yygotominor.yy346.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];
94707   }
94708         break;
94709       case 232: /* expr ::= EXISTS LP select RP */
94710 {
94711     Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
94712     if( p ){
94713       p->x.pSelect = yymsp[-1].minor.yy3;
94714       ExprSetProperty(p, EP_xIsSelect);
94715       sqlite3ExprSetHeight(pParse, p);
94716     }else{
94717       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
94718     }
94719     yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
94720     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
94721   }
94722         break;
94723       case 233: /* expr ::= CASE case_operand case_exprlist case_else END */
94724 {
94725   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, yymsp[-1].minor.yy132, 0);
94726   if( yygotominor.yy346.pExpr ){
94727     yygotominor.yy346.pExpr->x.pList = yymsp[-2].minor.yy14;
94728     sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
94729   }else{
94730     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
94731   }
94732   yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
94733   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
94734 }
94735         break;
94736       case 234: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
94737 {
94738   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
94739   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
94740 }
94741         break;
94742       case 235: /* case_exprlist ::= WHEN expr THEN expr */
94743 {
94744   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
94745   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
94746 }
94747         break;
94748       case 244: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP */
94749 {
94750   sqlite3CreateIndex(pParse, &yymsp[-6].minor.yy0, &yymsp[-5].minor.yy0, 
94751                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-3].minor.yy0,0), yymsp[-1].minor.yy14, yymsp[-9].minor.yy328,
94752                       &yymsp[-10].minor.yy0, &yymsp[0].minor.yy0, SQLITE_SO_ASC, yymsp[-7].minor.yy328);
94753 }
94754         break;
94755       case 245: /* uniqueflag ::= UNIQUE */
94756       case 299: /* raisetype ::= ABORT */ yytestcase(yyruleno==299);
94757 {yygotominor.yy328 = OE_Abort;}
94758         break;
94759       case 246: /* uniqueflag ::= */
94760 {yygotominor.yy328 = OE_None;}
94761         break;
94762       case 249: /* idxlist ::= idxlist COMMA nm collate sortorder */
94763 {
94764   Expr *p = 0;
94765   if( yymsp[-1].minor.yy0.n>0 ){
94766     p = sqlite3Expr(pParse->db, TK_COLUMN, 0);
94767     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
94768   }
94769   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
94770   sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
94771   sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
94772   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
94773 }
94774         break;
94775       case 250: /* idxlist ::= nm collate sortorder */
94776 {
94777   Expr *p = 0;
94778   if( yymsp[-1].minor.yy0.n>0 ){
94779     p = sqlite3PExpr(pParse, TK_COLUMN, 0, 0, 0);
94780     sqlite3ExprSetColl(pParse, p, &yymsp[-1].minor.yy0);
94781   }
94782   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
94783   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
94784   sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
94785   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
94786 }
94787         break;
94788       case 251: /* collate ::= */
94789 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
94790         break;
94791       case 253: /* cmd ::= DROP INDEX ifexists fullname */
94792 {sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
94793         break;
94794       case 254: /* cmd ::= VACUUM */
94795       case 255: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==255);
94796 {sqlite3Vacuum(pParse);}
94797         break;
94798       case 256: /* cmd ::= PRAGMA nm dbnm */
94799 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
94800         break;
94801       case 257: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
94802 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
94803         break;
94804       case 258: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
94805 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
94806         break;
94807       case 259: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
94808 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
94809         break;
94810       case 260: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
94811 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
94812         break;
94813       case 271: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
94814 {
94815   Token all;
94816   all.z = yymsp[-3].minor.yy0.z;
94817   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
94818   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
94819 }
94820         break;
94821       case 272: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
94822 {
94823   sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy328, yymsp[-4].minor.yy378.a, yymsp[-4].minor.yy378.b, yymsp[-2].minor.yy65, yymsp[0].minor.yy132, yymsp[-10].minor.yy328, yymsp[-8].minor.yy328);
94824   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
94825 }
94826         break;
94827       case 273: /* trigger_time ::= BEFORE */
94828       case 276: /* trigger_time ::= */ yytestcase(yyruleno==276);
94829 { yygotominor.yy328 = TK_BEFORE; }
94830         break;
94831       case 274: /* trigger_time ::= AFTER */
94832 { yygotominor.yy328 = TK_AFTER;  }
94833         break;
94834       case 275: /* trigger_time ::= INSTEAD OF */
94835 { yygotominor.yy328 = TK_INSTEAD;}
94836         break;
94837       case 277: /* trigger_event ::= DELETE|INSERT */
94838       case 278: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==278);
94839 {yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
94840         break;
94841       case 279: /* trigger_event ::= UPDATE OF inscollist */
94842 {yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
94843         break;
94844       case 282: /* when_clause ::= */
94845       case 304: /* key_opt ::= */ yytestcase(yyruleno==304);
94846 { yygotominor.yy132 = 0; }
94847         break;
94848       case 283: /* when_clause ::= WHEN expr */
94849       case 305: /* key_opt ::= KEY expr */ yytestcase(yyruleno==305);
94850 { yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
94851         break;
94852       case 284: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
94853 {
94854   assert( yymsp[-2].minor.yy473!=0 );
94855   yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
94856   yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
94857   yygotominor.yy473 = yymsp[-2].minor.yy473;
94858 }
94859         break;
94860       case 285: /* trigger_cmd_list ::= trigger_cmd SEMI */
94861
94862   assert( yymsp[-1].minor.yy473!=0 );
94863   yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
94864   yygotominor.yy473 = yymsp[-1].minor.yy473;
94865 }
94866         break;
94867       case 287: /* trnm ::= nm DOT nm */
94868 {
94869   yygotominor.yy0 = yymsp[0].minor.yy0;
94870   sqlite3ErrorMsg(pParse, 
94871         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
94872         "statements within triggers");
94873 }
94874         break;
94875       case 289: /* tridxby ::= INDEXED BY nm */
94876 {
94877   sqlite3ErrorMsg(pParse,
94878         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
94879         "within triggers");
94880 }
94881         break;
94882       case 290: /* tridxby ::= NOT INDEXED */
94883 {
94884   sqlite3ErrorMsg(pParse,
94885         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
94886         "within triggers");
94887 }
94888         break;
94889       case 291: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
94890 { yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
94891         break;
94892       case 292: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt VALUES LP itemlist RP */
94893 {yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy408, yymsp[-1].minor.yy14, 0, yymsp[-7].minor.yy186);}
94894         break;
94895       case 293: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
94896 {yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, 0, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
94897         break;
94898       case 294: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
94899 {yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
94900         break;
94901       case 295: /* trigger_cmd ::= select */
94902 {yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
94903         break;
94904       case 296: /* expr ::= RAISE LP IGNORE RP */
94905 {
94906   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
94907   if( yygotominor.yy346.pExpr ){
94908     yygotominor.yy346.pExpr->affinity = OE_Ignore;
94909   }
94910   yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
94911   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
94912 }
94913         break;
94914       case 297: /* expr ::= RAISE LP raisetype COMMA nm RP */
94915 {
94916   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
94917   if( yygotominor.yy346.pExpr ) {
94918     yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
94919   }
94920   yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
94921   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
94922 }
94923         break;
94924       case 298: /* raisetype ::= ROLLBACK */
94925 {yygotominor.yy328 = OE_Rollback;}
94926         break;
94927       case 300: /* raisetype ::= FAIL */
94928 {yygotominor.yy328 = OE_Fail;}
94929         break;
94930       case 301: /* cmd ::= DROP TRIGGER ifexists fullname */
94931 {
94932   sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
94933 }
94934         break;
94935       case 302: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
94936 {
94937   sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
94938 }
94939         break;
94940       case 303: /* cmd ::= DETACH database_kw_opt expr */
94941 {
94942   sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
94943 }
94944         break;
94945       case 308: /* cmd ::= REINDEX */
94946 {sqlite3Reindex(pParse, 0, 0);}
94947         break;
94948       case 309: /* cmd ::= REINDEX nm dbnm */
94949 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
94950         break;
94951       case 310: /* cmd ::= ANALYZE */
94952 {sqlite3Analyze(pParse, 0, 0);}
94953         break;
94954       case 311: /* cmd ::= ANALYZE nm dbnm */
94955 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
94956         break;
94957       case 312: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
94958 {
94959   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
94960 }
94961         break;
94962       case 313: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
94963 {
94964   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
94965 }
94966         break;
94967       case 314: /* add_column_fullname ::= fullname */
94968 {
94969   pParse->db->lookaside.bEnabled = 0;
94970   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
94971 }
94972         break;
94973       case 317: /* cmd ::= create_vtab */
94974 {sqlite3VtabFinishParse(pParse,0);}
94975         break;
94976       case 318: /* cmd ::= create_vtab LP vtabarglist RP */
94977 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
94978         break;
94979       case 319: /* create_vtab ::= createkw VIRTUAL TABLE nm dbnm USING nm */
94980 {
94981     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0);
94982 }
94983         break;
94984       case 322: /* vtabarg ::= */
94985 {sqlite3VtabArgInit(pParse);}
94986         break;
94987       case 324: /* vtabargtoken ::= ANY */
94988       case 325: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==325);
94989       case 326: /* lp ::= LP */ yytestcase(yyruleno==326);
94990 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
94991         break;
94992       default:
94993       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
94994       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
94995       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
94996       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
94997       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
94998       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
94999       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
95000       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
95001       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
95002       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
95003       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
95004       /* (34) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==34);
95005       /* (35) columnlist ::= column */ yytestcase(yyruleno==35);
95006       /* (44) type ::= */ yytestcase(yyruleno==44);
95007       /* (51) signed ::= plus_num */ yytestcase(yyruleno==51);
95008       /* (52) signed ::= minus_num */ yytestcase(yyruleno==52);
95009       /* (53) carglist ::= carglist carg */ yytestcase(yyruleno==53);
95010       /* (54) carglist ::= */ yytestcase(yyruleno==54);
95011       /* (55) carg ::= CONSTRAINT nm ccons */ yytestcase(yyruleno==55);
95012       /* (56) carg ::= ccons */ yytestcase(yyruleno==56);
95013       /* (62) ccons ::= NULL onconf */ yytestcase(yyruleno==62);
95014       /* (90) conslist ::= conslist COMMA tcons */ yytestcase(yyruleno==90);
95015       /* (91) conslist ::= conslist tcons */ yytestcase(yyruleno==91);
95016       /* (92) conslist ::= tcons */ yytestcase(yyruleno==92);
95017       /* (93) tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==93);
95018       /* (269) plus_opt ::= PLUS */ yytestcase(yyruleno==269);
95019       /* (270) plus_opt ::= */ yytestcase(yyruleno==270);
95020       /* (280) foreach_clause ::= */ yytestcase(yyruleno==280);
95021       /* (281) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==281);
95022       /* (288) tridxby ::= */ yytestcase(yyruleno==288);
95023       /* (306) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==306);
95024       /* (307) database_kw_opt ::= */ yytestcase(yyruleno==307);
95025       /* (315) kwcolumn_opt ::= */ yytestcase(yyruleno==315);
95026       /* (316) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==316);
95027       /* (320) vtabarglist ::= vtabarg */ yytestcase(yyruleno==320);
95028       /* (321) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==321);
95029       /* (323) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==323);
95030       /* (327) anylist ::= */ yytestcase(yyruleno==327);
95031       /* (328) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==328);
95032       /* (329) anylist ::= anylist ANY */ yytestcase(yyruleno==329);
95033         break;
95034   };
95035   yygoto = yyRuleInfo[yyruleno].lhs;
95036   yysize = yyRuleInfo[yyruleno].nrhs;
95037   yypParser->yyidx -= yysize;
95038   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
95039   if( yyact < YYNSTATE ){
95040 #ifdef NDEBUG
95041     /* If we are not debugging and the reduce action popped at least
95042     ** one element off the stack, then we can push the new element back
95043     ** onto the stack here, and skip the stack overflow test in yy_shift().
95044     ** That gives a significant speed improvement. */
95045     if( yysize ){
95046       yypParser->yyidx++;
95047       yymsp -= yysize-1;
95048       yymsp->stateno = (YYACTIONTYPE)yyact;
95049       yymsp->major = (YYCODETYPE)yygoto;
95050       yymsp->minor = yygotominor;
95051     }else
95052 #endif
95053     {
95054       yy_shift(yypParser,yyact,yygoto,&yygotominor);
95055     }
95056   }else{
95057     assert( yyact == YYNSTATE + YYNRULE + 1 );
95058     yy_accept(yypParser);
95059   }
95060 }
95061
95062 /*
95063 ** The following code executes when the parse fails
95064 */
95065 #ifndef YYNOERRORRECOVERY
95066 static void yy_parse_failed(
95067   yyParser *yypParser           /* The parser */
95068 ){
95069   sqlite3ParserARG_FETCH;
95070 #ifndef NDEBUG
95071   if( yyTraceFILE ){
95072     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
95073   }
95074 #endif
95075   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
95076   /* Here code is inserted which will be executed whenever the
95077   ** parser fails */
95078   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
95079 }
95080 #endif /* YYNOERRORRECOVERY */
95081
95082 /*
95083 ** The following code executes when a syntax error first occurs.
95084 */
95085 static void yy_syntax_error(
95086   yyParser *yypParser,           /* The parser */
95087   int yymajor,                   /* The major type of the error token */
95088   YYMINORTYPE yyminor            /* The minor type of the error token */
95089 ){
95090   sqlite3ParserARG_FETCH;
95091 #define TOKEN (yyminor.yy0)
95092
95093   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
95094   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
95095   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
95096   pParse->parseError = 1;
95097   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
95098 }
95099
95100 /*
95101 ** The following is executed when the parser accepts
95102 */
95103 static void yy_accept(
95104   yyParser *yypParser           /* The parser */
95105 ){
95106   sqlite3ParserARG_FETCH;
95107 #ifndef NDEBUG
95108   if( yyTraceFILE ){
95109     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
95110   }
95111 #endif
95112   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
95113   /* Here code is inserted which will be executed whenever the
95114   ** parser accepts */
95115   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
95116 }
95117
95118 /* The main parser program.
95119 ** The first argument is a pointer to a structure obtained from
95120 ** "sqlite3ParserAlloc" which describes the current state of the parser.
95121 ** The second argument is the major token number.  The third is
95122 ** the minor token.  The fourth optional argument is whatever the
95123 ** user wants (and specified in the grammar) and is available for
95124 ** use by the action routines.
95125 **
95126 ** Inputs:
95127 ** <ul>
95128 ** <li> A pointer to the parser (an opaque structure.)
95129 ** <li> The major token number.
95130 ** <li> The minor token number.
95131 ** <li> An option argument of a grammar-specified type.
95132 ** </ul>
95133 **
95134 ** Outputs:
95135 ** None.
95136 */
95137 SQLITE_PRIVATE void sqlite3Parser(
95138   void *yyp,                   /* The parser */
95139   int yymajor,                 /* The major token code number */
95140   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
95141   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
95142 ){
95143   YYMINORTYPE yyminorunion;
95144   int yyact;            /* The parser action. */
95145   int yyendofinput;     /* True if we are at the end of input */
95146 #ifdef YYERRORSYMBOL
95147   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
95148 #endif
95149   yyParser *yypParser;  /* The parser */
95150
95151   /* (re)initialize the parser, if necessary */
95152   yypParser = (yyParser*)yyp;
95153   if( yypParser->yyidx<0 ){
95154 #if YYSTACKDEPTH<=0
95155     if( yypParser->yystksz <=0 ){
95156       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
95157       yyminorunion = yyzerominor;
95158       yyStackOverflow(yypParser, &yyminorunion);
95159       return;
95160     }
95161 #endif
95162     yypParser->yyidx = 0;
95163     yypParser->yyerrcnt = -1;
95164     yypParser->yystack[0].stateno = 0;
95165     yypParser->yystack[0].major = 0;
95166   }
95167   yyminorunion.yy0 = yyminor;
95168   yyendofinput = (yymajor==0);
95169   sqlite3ParserARG_STORE;
95170
95171 #ifndef NDEBUG
95172   if( yyTraceFILE ){
95173     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
95174   }
95175 #endif
95176
95177   do{
95178     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
95179     if( yyact<YYNSTATE ){
95180       assert( !yyendofinput );  /* Impossible to shift the $ token */
95181       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
95182       yypParser->yyerrcnt--;
95183       yymajor = YYNOCODE;
95184     }else if( yyact < YYNSTATE + YYNRULE ){
95185       yy_reduce(yypParser,yyact-YYNSTATE);
95186     }else{
95187       assert( yyact == YY_ERROR_ACTION );
95188 #ifdef YYERRORSYMBOL
95189       int yymx;
95190 #endif
95191 #ifndef NDEBUG
95192       if( yyTraceFILE ){
95193         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
95194       }
95195 #endif
95196 #ifdef YYERRORSYMBOL
95197       /* A syntax error has occurred.
95198       ** The response to an error depends upon whether or not the
95199       ** grammar defines an error token "ERROR".  
95200       **
95201       ** This is what we do if the grammar does define ERROR:
95202       **
95203       **  * Call the %syntax_error function.
95204       **
95205       **  * Begin popping the stack until we enter a state where
95206       **    it is legal to shift the error symbol, then shift
95207       **    the error symbol.
95208       **
95209       **  * Set the error count to three.
95210       **
95211       **  * Begin accepting and shifting new tokens.  No new error
95212       **    processing will occur until three tokens have been
95213       **    shifted successfully.
95214       **
95215       */
95216       if( yypParser->yyerrcnt<0 ){
95217         yy_syntax_error(yypParser,yymajor,yyminorunion);
95218       }
95219       yymx = yypParser->yystack[yypParser->yyidx].major;
95220       if( yymx==YYERRORSYMBOL || yyerrorhit ){
95221 #ifndef NDEBUG
95222         if( yyTraceFILE ){
95223           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
95224              yyTracePrompt,yyTokenName[yymajor]);
95225         }
95226 #endif
95227         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
95228         yymajor = YYNOCODE;
95229       }else{
95230          while(
95231           yypParser->yyidx >= 0 &&
95232           yymx != YYERRORSYMBOL &&
95233           (yyact = yy_find_reduce_action(
95234                         yypParser->yystack[yypParser->yyidx].stateno,
95235                         YYERRORSYMBOL)) >= YYNSTATE
95236         ){
95237           yy_pop_parser_stack(yypParser);
95238         }
95239         if( yypParser->yyidx < 0 || yymajor==0 ){
95240           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
95241           yy_parse_failed(yypParser);
95242           yymajor = YYNOCODE;
95243         }else if( yymx!=YYERRORSYMBOL ){
95244           YYMINORTYPE u2;
95245           u2.YYERRSYMDT = 0;
95246           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
95247         }
95248       }
95249       yypParser->yyerrcnt = 3;
95250       yyerrorhit = 1;
95251 #elif defined(YYNOERRORRECOVERY)
95252       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
95253       ** do any kind of error recovery.  Instead, simply invoke the syntax
95254       ** error routine and continue going as if nothing had happened.
95255       **
95256       ** Applications can set this macro (for example inside %include) if
95257       ** they intend to abandon the parse upon the first syntax error seen.
95258       */
95259       yy_syntax_error(yypParser,yymajor,yyminorunion);
95260       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
95261       yymajor = YYNOCODE;
95262       
95263 #else  /* YYERRORSYMBOL is not defined */
95264       /* This is what we do if the grammar does not define ERROR:
95265       **
95266       **  * Report an error message, and throw away the input token.
95267       **
95268       **  * If the input token is $, then fail the parse.
95269       **
95270       ** As before, subsequent error messages are suppressed until
95271       ** three input tokens have been successfully shifted.
95272       */
95273       if( yypParser->yyerrcnt<=0 ){
95274         yy_syntax_error(yypParser,yymajor,yyminorunion);
95275       }
95276       yypParser->yyerrcnt = 3;
95277       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
95278       if( yyendofinput ){
95279         yy_parse_failed(yypParser);
95280       }
95281       yymajor = YYNOCODE;
95282 #endif
95283     }
95284   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
95285   return;
95286 }
95287
95288 /************** End of parse.c ***********************************************/
95289 /************** Begin file tokenize.c ****************************************/
95290 /*
95291 ** 2001 September 15
95292 **
95293 ** The author disclaims copyright to this source code.  In place of
95294 ** a legal notice, here is a blessing:
95295 **
95296 **    May you do good and not evil.
95297 **    May you find forgiveness for yourself and forgive others.
95298 **    May you share freely, never taking more than you give.
95299 **
95300 *************************************************************************
95301 ** An tokenizer for SQL
95302 **
95303 ** This file contains C code that splits an SQL input string up into
95304 ** individual tokens and sends those tokens one-by-one over to the
95305 ** parser for analysis.
95306 */
95307
95308 /*
95309 ** The charMap() macro maps alphabetic characters into their
95310 ** lower-case ASCII equivalent.  On ASCII machines, this is just
95311 ** an upper-to-lower case map.  On EBCDIC machines we also need
95312 ** to adjust the encoding.  Only alphabetic characters and underscores
95313 ** need to be translated.
95314 */
95315 #ifdef SQLITE_ASCII
95316 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
95317 #endif
95318 #ifdef SQLITE_EBCDIC
95319 # define charMap(X) ebcdicToAscii[(unsigned char)X]
95320 const unsigned char ebcdicToAscii[] = {
95321 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
95322    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
95323    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
95324    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
95325    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
95326    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
95327    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
95328    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
95329    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
95330    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
95331    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
95332    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
95333    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
95334    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
95335    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
95336    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
95337    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
95338 };
95339 #endif
95340
95341 /*
95342 ** The sqlite3KeywordCode function looks up an identifier to determine if
95343 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
95344 ** returned.  If the input is not a keyword, TK_ID is returned.
95345 **
95346 ** The implementation of this routine was generated by a program,
95347 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
95348 ** The output of the mkkeywordhash.c program is written into a file
95349 ** named keywordhash.h and then included into this source file by
95350 ** the #include below.
95351 */
95352 /************** Include keywordhash.h in the middle of tokenize.c ************/
95353 /************** Begin file keywordhash.h *************************************/
95354 /***** This file contains automatically generated code ******
95355 **
95356 ** The code in this file has been automatically generated by
95357 **
95358 **   sqlite/tool/mkkeywordhash.c
95359 **
95360 ** The code in this file implements a function that determines whether
95361 ** or not a given identifier is really an SQL keyword.  The same thing
95362 ** might be implemented more directly using a hand-written hash table.
95363 ** But by using this automatically generated code, the size of the code
95364 ** is substantially reduced.  This is important for embedded applications
95365 ** on platforms with limited memory.
95366 */
95367 /* Hash score: 175 */
95368 static int keywordCode(const char *z, int n){
95369   /* zText[] encodes 811 bytes of keywords in 541 bytes */
95370   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
95371   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
95372   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
95373   /*   UNIQUERYATTACHAVINGROUPDATEBEGINNERELEASEBETWEENOTNULLIKE          */
95374   /*   CASCADELETECASECOLLATECREATECURRENT_DATEDETACHIMMEDIATEJOIN        */
95375   /*   SERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHENWHERENAME         */
95376   /*   AFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMITCONFLICTCROSS     */
95377   /*   CURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAILFROMFULLGLOBYIF      */
95378   /*   ISNULLORDERESTRICTOUTERIGHTROLLBACKROWUNIONUSINGVACUUMVIEW         */
95379   /*   INITIALLY                                                          */
95380   static const char zText[540] = {
95381     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
95382     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
95383     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
95384     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
95385     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
95386     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
95387     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
95388     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
95389     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
95390     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
95391     'U','E','R','Y','A','T','T','A','C','H','A','V','I','N','G','R','O','U',
95392     'P','D','A','T','E','B','E','G','I','N','N','E','R','E','L','E','A','S',
95393     'E','B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C',
95394     'A','S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L',
95395     'A','T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D',
95396     'A','T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E',
95397     'J','O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A',
95398     'L','Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U',
95399     'E','S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W',
95400     'H','E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C',
95401     'E','A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R',
95402     'E','M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M',
95403     'M','I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U',
95404     'R','R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M',
95405     'A','R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T',
95406     'D','R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L',
95407     'O','B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S',
95408     'T','R','I','C','T','O','U','T','E','R','I','G','H','T','R','O','L','L',
95409     'B','A','C','K','R','O','W','U','N','I','O','N','U','S','I','N','G','V',
95410     'A','C','U','U','M','V','I','E','W','I','N','I','T','I','A','L','L','Y',
95411   };
95412   static const unsigned char aHash[127] = {
95413       72, 101, 114,  70,   0,  45,   0,   0,  78,   0,  73,   0,   0,
95414       42,  12,  74,  15,   0, 113,  81,  50, 108,   0,  19,   0,   0,
95415      118,   0, 116, 111,   0,  22,  89,   0,   9,   0,   0,  66,  67,
95416        0,  65,   6,   0,  48,  86,  98,   0, 115,  97,   0,   0,  44,
95417        0,  99,  24,   0,  17,   0, 119,  49,  23,   0,   5, 106,  25,
95418       92,   0,   0, 121, 102,  56, 120,  53,  28,  51,   0,  87,   0,
95419       96,  26,   0,  95,   0,   0,   0,  91,  88,  93,  84, 105,  14,
95420       39, 104,   0,  77,   0,  18,  85, 107,  32,   0, 117,  76, 109,
95421       58,  46,  80,   0,   0,  90,  40,   0, 112,   0,  36,   0,   0,
95422       29,   0,  82,  59,  60,   0,  20,  57,   0,  52,
95423   };
95424   static const unsigned char aNext[121] = {
95425        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
95426        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
95427        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
95428        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,  43,   3,  47,
95429        0,   0,   0,   0,  30,   0,  54,   0,  38,   0,   0,   0,   1,
95430       62,   0,   0,  63,   0,  41,   0,   0,   0,   0,   0,   0,   0,
95431       61,   0,   0,   0,   0,  31,  55,  16,  34,  10,   0,   0,   0,
95432        0,   0,   0,   0,  11,  68,  75,   0,   8,   0, 100,  94,   0,
95433      103,   0,  83,   0,  71,   0,   0, 110,  27,  37,  69,  79,   0,
95434       35,  64,   0,   0,
95435   };
95436   static const unsigned char aLen[121] = {
95437        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
95438        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
95439       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
95440        4,   6,   2,   3,   9,   4,   2,   6,   5,   6,   6,   5,   6,
95441        5,   5,   7,   7,   7,   3,   2,   4,   4,   7,   3,   6,   4,
95442        7,   6,  12,   6,   9,   4,   6,   5,   4,   7,   6,   5,   6,
95443        7,   5,   4,   5,   6,   5,   7,   3,   7,  13,   2,   2,   4,
95444        6,   6,   8,   5,  17,  12,   7,   8,   8,   2,   4,   4,   4,
95445        4,   4,   2,   2,   6,   5,   8,   5,   5,   8,   3,   5,   5,
95446        6,   4,   9,   3,
95447   };
95448   static const unsigned short int aOffset[121] = {
95449        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
95450       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
95451       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
95452      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 189, 194, 197,
95453      203, 206, 210, 217, 223, 223, 223, 226, 229, 233, 234, 238, 244,
95454      248, 255, 261, 273, 279, 288, 290, 296, 301, 303, 310, 315, 320,
95455      326, 332, 337, 341, 344, 350, 354, 361, 363, 370, 372, 374, 383,
95456      387, 393, 399, 407, 412, 412, 428, 435, 442, 443, 450, 454, 458,
95457      462, 466, 469, 471, 473, 479, 483, 491, 495, 500, 508, 511, 516,
95458      521, 527, 531, 536,
95459   };
95460   static const unsigned char aCode[121] = {
95461     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
95462     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
95463     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
95464     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
95465     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
95466     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
95467     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  
95468     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       
95469     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
95470     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_ATTACH,     TK_HAVING,     
95471     TK_GROUP,      TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RELEASE,    
95472     TK_BETWEEN,    TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       
95473     TK_LIKE_KW,    TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       
95474     TK_COLLATE,    TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  
95475     TK_JOIN,       TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    
95476     TK_PRAGMA,     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      
95477     TK_WHEN,       TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    
95478     TK_AND,        TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         
95479     TK_CAST,       TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    
95480     TK_CTIME_KW,   TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   
95481     TK_IS,         TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    
95482     TK_LIKE_KW,    TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      
95483     TK_RESTRICT,   TK_JOIN_KW,    TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        
95484     TK_UNION,      TK_USING,      TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  
95485     TK_ALL,        
95486   };
95487   int h, i;
95488   if( n<2 ) return TK_ID;
95489   h = ((charMap(z[0])*4) ^
95490       (charMap(z[n-1])*3) ^
95491       n) % 127;
95492   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
95493     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
95494       testcase( i==0 ); /* REINDEX */
95495       testcase( i==1 ); /* INDEXED */
95496       testcase( i==2 ); /* INDEX */
95497       testcase( i==3 ); /* DESC */
95498       testcase( i==4 ); /* ESCAPE */
95499       testcase( i==5 ); /* EACH */
95500       testcase( i==6 ); /* CHECK */
95501       testcase( i==7 ); /* KEY */
95502       testcase( i==8 ); /* BEFORE */
95503       testcase( i==9 ); /* FOREIGN */
95504       testcase( i==10 ); /* FOR */
95505       testcase( i==11 ); /* IGNORE */
95506       testcase( i==12 ); /* REGEXP */
95507       testcase( i==13 ); /* EXPLAIN */
95508       testcase( i==14 ); /* INSTEAD */
95509       testcase( i==15 ); /* ADD */
95510       testcase( i==16 ); /* DATABASE */
95511       testcase( i==17 ); /* AS */
95512       testcase( i==18 ); /* SELECT */
95513       testcase( i==19 ); /* TABLE */
95514       testcase( i==20 ); /* LEFT */
95515       testcase( i==21 ); /* THEN */
95516       testcase( i==22 ); /* END */
95517       testcase( i==23 ); /* DEFERRABLE */
95518       testcase( i==24 ); /* ELSE */
95519       testcase( i==25 ); /* EXCEPT */
95520       testcase( i==26 ); /* TRANSACTION */
95521       testcase( i==27 ); /* ACTION */
95522       testcase( i==28 ); /* ON */
95523       testcase( i==29 ); /* NATURAL */
95524       testcase( i==30 ); /* ALTER */
95525       testcase( i==31 ); /* RAISE */
95526       testcase( i==32 ); /* EXCLUSIVE */
95527       testcase( i==33 ); /* EXISTS */
95528       testcase( i==34 ); /* SAVEPOINT */
95529       testcase( i==35 ); /* INTERSECT */
95530       testcase( i==36 ); /* TRIGGER */
95531       testcase( i==37 ); /* REFERENCES */
95532       testcase( i==38 ); /* CONSTRAINT */
95533       testcase( i==39 ); /* INTO */
95534       testcase( i==40 ); /* OFFSET */
95535       testcase( i==41 ); /* OF */
95536       testcase( i==42 ); /* SET */
95537       testcase( i==43 ); /* TEMPORARY */
95538       testcase( i==44 ); /* TEMP */
95539       testcase( i==45 ); /* OR */
95540       testcase( i==46 ); /* UNIQUE */
95541       testcase( i==47 ); /* QUERY */
95542       testcase( i==48 ); /* ATTACH */
95543       testcase( i==49 ); /* HAVING */
95544       testcase( i==50 ); /* GROUP */
95545       testcase( i==51 ); /* UPDATE */
95546       testcase( i==52 ); /* BEGIN */
95547       testcase( i==53 ); /* INNER */
95548       testcase( i==54 ); /* RELEASE */
95549       testcase( i==55 ); /* BETWEEN */
95550       testcase( i==56 ); /* NOTNULL */
95551       testcase( i==57 ); /* NOT */
95552       testcase( i==58 ); /* NO */
95553       testcase( i==59 ); /* NULL */
95554       testcase( i==60 ); /* LIKE */
95555       testcase( i==61 ); /* CASCADE */
95556       testcase( i==62 ); /* ASC */
95557       testcase( i==63 ); /* DELETE */
95558       testcase( i==64 ); /* CASE */
95559       testcase( i==65 ); /* COLLATE */
95560       testcase( i==66 ); /* CREATE */
95561       testcase( i==67 ); /* CURRENT_DATE */
95562       testcase( i==68 ); /* DETACH */
95563       testcase( i==69 ); /* IMMEDIATE */
95564       testcase( i==70 ); /* JOIN */
95565       testcase( i==71 ); /* INSERT */
95566       testcase( i==72 ); /* MATCH */
95567       testcase( i==73 ); /* PLAN */
95568       testcase( i==74 ); /* ANALYZE */
95569       testcase( i==75 ); /* PRAGMA */
95570       testcase( i==76 ); /* ABORT */
95571       testcase( i==77 ); /* VALUES */
95572       testcase( i==78 ); /* VIRTUAL */
95573       testcase( i==79 ); /* LIMIT */
95574       testcase( i==80 ); /* WHEN */
95575       testcase( i==81 ); /* WHERE */
95576       testcase( i==82 ); /* RENAME */
95577       testcase( i==83 ); /* AFTER */
95578       testcase( i==84 ); /* REPLACE */
95579       testcase( i==85 ); /* AND */
95580       testcase( i==86 ); /* DEFAULT */
95581       testcase( i==87 ); /* AUTOINCREMENT */
95582       testcase( i==88 ); /* TO */
95583       testcase( i==89 ); /* IN */
95584       testcase( i==90 ); /* CAST */
95585       testcase( i==91 ); /* COLUMN */
95586       testcase( i==92 ); /* COMMIT */
95587       testcase( i==93 ); /* CONFLICT */
95588       testcase( i==94 ); /* CROSS */
95589       testcase( i==95 ); /* CURRENT_TIMESTAMP */
95590       testcase( i==96 ); /* CURRENT_TIME */
95591       testcase( i==97 ); /* PRIMARY */
95592       testcase( i==98 ); /* DEFERRED */
95593       testcase( i==99 ); /* DISTINCT */
95594       testcase( i==100 ); /* IS */
95595       testcase( i==101 ); /* DROP */
95596       testcase( i==102 ); /* FAIL */
95597       testcase( i==103 ); /* FROM */
95598       testcase( i==104 ); /* FULL */
95599       testcase( i==105 ); /* GLOB */
95600       testcase( i==106 ); /* BY */
95601       testcase( i==107 ); /* IF */
95602       testcase( i==108 ); /* ISNULL */
95603       testcase( i==109 ); /* ORDER */
95604       testcase( i==110 ); /* RESTRICT */
95605       testcase( i==111 ); /* OUTER */
95606       testcase( i==112 ); /* RIGHT */
95607       testcase( i==113 ); /* ROLLBACK */
95608       testcase( i==114 ); /* ROW */
95609       testcase( i==115 ); /* UNION */
95610       testcase( i==116 ); /* USING */
95611       testcase( i==117 ); /* VACUUM */
95612       testcase( i==118 ); /* VIEW */
95613       testcase( i==119 ); /* INITIALLY */
95614       testcase( i==120 ); /* ALL */
95615       return aCode[i];
95616     }
95617   }
95618   return TK_ID;
95619 }
95620 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
95621   return keywordCode((char*)z, n);
95622 }
95623 #define SQLITE_N_KEYWORD 121
95624
95625 /************** End of keywordhash.h *****************************************/
95626 /************** Continuing where we left off in tokenize.c *******************/
95627
95628
95629 /*
95630 ** If X is a character that can be used in an identifier then
95631 ** IdChar(X) will be true.  Otherwise it is false.
95632 **
95633 ** For ASCII, any character with the high-order bit set is
95634 ** allowed in an identifier.  For 7-bit characters, 
95635 ** sqlite3IsIdChar[X] must be 1.
95636 **
95637 ** For EBCDIC, the rules are more complex but have the same
95638 ** end result.
95639 **
95640 ** Ticket #1066.  the SQL standard does not allow '$' in the
95641 ** middle of identfiers.  But many SQL implementations do. 
95642 ** SQLite will allow '$' in identifiers for compatibility.
95643 ** But the feature is undocumented.
95644 */
95645 #ifdef SQLITE_ASCII
95646 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
95647 #endif
95648 #ifdef SQLITE_EBCDIC
95649 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
95650 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
95651     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
95652     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
95653     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
95654     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
95655     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
95656     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
95657     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
95658     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
95659     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
95660     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
95661     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
95662     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
95663 };
95664 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
95665 #endif
95666
95667
95668 /*
95669 ** Return the length of the token that begins at z[0]. 
95670 ** Store the token type in *tokenType before returning.
95671 */
95672 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
95673   int i, c;
95674   switch( *z ){
95675     case ' ': case '\t': case '\n': case '\f': case '\r': {
95676       testcase( z[0]==' ' );
95677       testcase( z[0]=='\t' );
95678       testcase( z[0]=='\n' );
95679       testcase( z[0]=='\f' );
95680       testcase( z[0]=='\r' );
95681       for(i=1; sqlite3Isspace(z[i]); i++){}
95682       *tokenType = TK_SPACE;
95683       return i;
95684     }
95685     case '-': {
95686       if( z[1]=='-' ){
95687         /* IMP: R-15891-05542 -- syntax diagram for comments */
95688         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
95689         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
95690         return i;
95691       }
95692       *tokenType = TK_MINUS;
95693       return 1;
95694     }
95695     case '(': {
95696       *tokenType = TK_LP;
95697       return 1;
95698     }
95699     case ')': {
95700       *tokenType = TK_RP;
95701       return 1;
95702     }
95703     case ';': {
95704       *tokenType = TK_SEMI;
95705       return 1;
95706     }
95707     case '+': {
95708       *tokenType = TK_PLUS;
95709       return 1;
95710     }
95711     case '*': {
95712       *tokenType = TK_STAR;
95713       return 1;
95714     }
95715     case '/': {
95716       if( z[1]!='*' || z[2]==0 ){
95717         *tokenType = TK_SLASH;
95718         return 1;
95719       }
95720       /* IMP: R-15891-05542 -- syntax diagram for comments */
95721       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
95722       if( c ) i++;
95723       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
95724       return i;
95725     }
95726     case '%': {
95727       *tokenType = TK_REM;
95728       return 1;
95729     }
95730     case '=': {
95731       *tokenType = TK_EQ;
95732       return 1 + (z[1]=='=');
95733     }
95734     case '<': {
95735       if( (c=z[1])=='=' ){
95736         *tokenType = TK_LE;
95737         return 2;
95738       }else if( c=='>' ){
95739         *tokenType = TK_NE;
95740         return 2;
95741       }else if( c=='<' ){
95742         *tokenType = TK_LSHIFT;
95743         return 2;
95744       }else{
95745         *tokenType = TK_LT;
95746         return 1;
95747       }
95748     }
95749     case '>': {
95750       if( (c=z[1])=='=' ){
95751         *tokenType = TK_GE;
95752         return 2;
95753       }else if( c=='>' ){
95754         *tokenType = TK_RSHIFT;
95755         return 2;
95756       }else{
95757         *tokenType = TK_GT;
95758         return 1;
95759       }
95760     }
95761     case '!': {
95762       if( z[1]!='=' ){
95763         *tokenType = TK_ILLEGAL;
95764         return 2;
95765       }else{
95766         *tokenType = TK_NE;
95767         return 2;
95768       }
95769     }
95770     case '|': {
95771       if( z[1]!='|' ){
95772         *tokenType = TK_BITOR;
95773         return 1;
95774       }else{
95775         *tokenType = TK_CONCAT;
95776         return 2;
95777       }
95778     }
95779     case ',': {
95780       *tokenType = TK_COMMA;
95781       return 1;
95782     }
95783     case '&': {
95784       *tokenType = TK_BITAND;
95785       return 1;
95786     }
95787     case '~': {
95788       *tokenType = TK_BITNOT;
95789       return 1;
95790     }
95791     case '`':
95792     case '\'':
95793     case '"': {
95794       int delim = z[0];
95795       testcase( delim=='`' );
95796       testcase( delim=='\'' );
95797       testcase( delim=='"' );
95798       for(i=1; (c=z[i])!=0; i++){
95799         if( c==delim ){
95800           if( z[i+1]==delim ){
95801             i++;
95802           }else{
95803             break;
95804           }
95805         }
95806       }
95807       if( c=='\'' ){
95808         *tokenType = TK_STRING;
95809         return i+1;
95810       }else if( c!=0 ){
95811         *tokenType = TK_ID;
95812         return i+1;
95813       }else{
95814         *tokenType = TK_ILLEGAL;
95815         return i;
95816       }
95817     }
95818     case '.': {
95819 #ifndef SQLITE_OMIT_FLOATING_POINT
95820       if( !sqlite3Isdigit(z[1]) )
95821 #endif
95822       {
95823         *tokenType = TK_DOT;
95824         return 1;
95825       }
95826       /* If the next character is a digit, this is a floating point
95827       ** number that begins with ".".  Fall thru into the next case */
95828     }
95829     case '0': case '1': case '2': case '3': case '4':
95830     case '5': case '6': case '7': case '8': case '9': {
95831       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
95832       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
95833       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
95834       testcase( z[0]=='9' );
95835       *tokenType = TK_INTEGER;
95836       for(i=0; sqlite3Isdigit(z[i]); i++){}
95837 #ifndef SQLITE_OMIT_FLOATING_POINT
95838       if( z[i]=='.' ){
95839         i++;
95840         while( sqlite3Isdigit(z[i]) ){ i++; }
95841         *tokenType = TK_FLOAT;
95842       }
95843       if( (z[i]=='e' || z[i]=='E') &&
95844            ( sqlite3Isdigit(z[i+1]) 
95845             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
95846            )
95847       ){
95848         i += 2;
95849         while( sqlite3Isdigit(z[i]) ){ i++; }
95850         *tokenType = TK_FLOAT;
95851       }
95852 #endif
95853       while( IdChar(z[i]) ){
95854         *tokenType = TK_ILLEGAL;
95855         i++;
95856       }
95857       return i;
95858     }
95859     case '[': {
95860       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
95861       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
95862       return i;
95863     }
95864     case '?': {
95865       *tokenType = TK_VARIABLE;
95866       for(i=1; sqlite3Isdigit(z[i]); i++){}
95867       return i;
95868     }
95869     case '#': {
95870       for(i=1; sqlite3Isdigit(z[i]); i++){}
95871       if( i>1 ){
95872         /* Parameters of the form #NNN (where NNN is a number) are used
95873         ** internally by sqlite3NestedParse.  */
95874         *tokenType = TK_REGISTER;
95875         return i;
95876       }
95877       /* Fall through into the next case if the '#' is not followed by
95878       ** a digit. Try to match #AAAA where AAAA is a parameter name. */
95879     }
95880 #ifndef SQLITE_OMIT_TCL_VARIABLE
95881     case '$':
95882 #endif
95883     case '@':  /* For compatibility with MS SQL Server */
95884     case ':': {
95885       int n = 0;
95886       testcase( z[0]=='$' );  testcase( z[0]=='@' );  testcase( z[0]==':' );
95887       *tokenType = TK_VARIABLE;
95888       for(i=1; (c=z[i])!=0; i++){
95889         if( IdChar(c) ){
95890           n++;
95891 #ifndef SQLITE_OMIT_TCL_VARIABLE
95892         }else if( c=='(' && n>0 ){
95893           do{
95894             i++;
95895           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
95896           if( c==')' ){
95897             i++;
95898           }else{
95899             *tokenType = TK_ILLEGAL;
95900           }
95901           break;
95902         }else if( c==':' && z[i+1]==':' ){
95903           i++;
95904 #endif
95905         }else{
95906           break;
95907         }
95908       }
95909       if( n==0 ) *tokenType = TK_ILLEGAL;
95910       return i;
95911     }
95912 #ifndef SQLITE_OMIT_BLOB_LITERAL
95913     case 'x': case 'X': {
95914       testcase( z[0]=='x' ); testcase( z[0]=='X' );
95915       if( z[1]=='\'' ){
95916         *tokenType = TK_BLOB;
95917         for(i=2; (c=z[i])!=0 && c!='\''; i++){
95918           if( !sqlite3Isxdigit(c) ){
95919             *tokenType = TK_ILLEGAL;
95920           }
95921         }
95922         if( i%2 || !c ) *tokenType = TK_ILLEGAL;
95923         if( c ) i++;
95924         return i;
95925       }
95926       /* Otherwise fall through to the next case */
95927     }
95928 #endif
95929     default: {
95930       if( !IdChar(*z) ){
95931         break;
95932       }
95933       for(i=1; IdChar(z[i]); i++){}
95934       *tokenType = keywordCode((char*)z, i);
95935       return i;
95936     }
95937   }
95938   *tokenType = TK_ILLEGAL;
95939   return 1;
95940 }
95941
95942 /*
95943 ** Run the parser on the given SQL string.  The parser structure is
95944 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
95945 ** then an and attempt is made to write an error message into 
95946 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
95947 ** error message.
95948 */
95949 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
95950   int nErr = 0;                   /* Number of errors encountered */
95951   int i;                          /* Loop counter */
95952   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
95953   int tokenType;                  /* type of the next token */
95954   int lastTokenParsed = -1;       /* type of the previous token */
95955   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
95956   sqlite3 *db = pParse->db;       /* The database connection */
95957   int mxSqlLen;                   /* Max length of an SQL string */
95958
95959
95960   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
95961   if( db->activeVdbeCnt==0 ){
95962     db->u1.isInterrupted = 0;
95963   }
95964   pParse->rc = SQLITE_OK;
95965   pParse->zTail = zSql;
95966   i = 0;
95967   assert( pzErrMsg!=0 );
95968   pEngine = sqlite3ParserAlloc((void*(*)(size_t))sqlite3Malloc);
95969   if( pEngine==0 ){
95970     db->mallocFailed = 1;
95971     return SQLITE_NOMEM;
95972   }
95973   assert( pParse->pNewTable==0 );
95974   assert( pParse->pNewTrigger==0 );
95975   assert( pParse->nVar==0 );
95976   assert( pParse->nVarExpr==0 );
95977   assert( pParse->nVarExprAlloc==0 );
95978   assert( pParse->apVarExpr==0 );
95979   enableLookaside = db->lookaside.bEnabled;
95980   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
95981   while( !db->mallocFailed && zSql[i]!=0 ){
95982     assert( i>=0 );
95983     pParse->sLastToken.z = &zSql[i];
95984     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
95985     i += pParse->sLastToken.n;
95986     if( i>mxSqlLen ){
95987       pParse->rc = SQLITE_TOOBIG;
95988       break;
95989     }
95990     switch( tokenType ){
95991       case TK_SPACE: {
95992         if( db->u1.isInterrupted ){
95993           sqlite3ErrorMsg(pParse, "interrupt");
95994           pParse->rc = SQLITE_INTERRUPT;
95995           goto abort_parse;
95996         }
95997         break;
95998       }
95999       case TK_ILLEGAL: {
96000         sqlite3DbFree(db, *pzErrMsg);
96001         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
96002                         &pParse->sLastToken);
96003         nErr++;
96004         goto abort_parse;
96005       }
96006       case TK_SEMI: {
96007         pParse->zTail = &zSql[i];
96008         /* Fall thru into the default case */
96009       }
96010       default: {
96011         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
96012         lastTokenParsed = tokenType;
96013         if( pParse->rc!=SQLITE_OK ){
96014           goto abort_parse;
96015         }
96016         break;
96017       }
96018     }
96019   }
96020 abort_parse:
96021   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
96022     if( lastTokenParsed!=TK_SEMI ){
96023       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
96024       pParse->zTail = &zSql[i];
96025     }
96026     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
96027   }
96028 #ifdef YYTRACKMAXSTACKDEPTH
96029   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
96030       sqlite3ParserStackPeak(pEngine)
96031   );
96032 #endif /* YYDEBUG */
96033   sqlite3ParserFree(pEngine, sqlite3_free);
96034   db->lookaside.bEnabled = enableLookaside;
96035   if( db->mallocFailed ){
96036     pParse->rc = SQLITE_NOMEM;
96037   }
96038   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
96039     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
96040   }
96041   assert( pzErrMsg!=0 );
96042   if( pParse->zErrMsg ){
96043     *pzErrMsg = pParse->zErrMsg;
96044     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
96045     pParse->zErrMsg = 0;
96046     nErr++;
96047   }
96048   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
96049     sqlite3VdbeDelete(pParse->pVdbe);
96050     pParse->pVdbe = 0;
96051   }
96052 #ifndef SQLITE_OMIT_SHARED_CACHE
96053   if( pParse->nested==0 ){
96054     sqlite3DbFree(db, pParse->aTableLock);
96055     pParse->aTableLock = 0;
96056     pParse->nTableLock = 0;
96057   }
96058 #endif
96059 #ifndef SQLITE_OMIT_VIRTUALTABLE
96060   sqlite3DbFree(db, pParse->apVtabLock);
96061 #endif
96062
96063   if( !IN_DECLARE_VTAB ){
96064     /* If the pParse->declareVtab flag is set, do not delete any table 
96065     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
96066     ** will take responsibility for freeing the Table structure.
96067     */
96068     sqlite3DeleteTable(pParse->pNewTable);
96069   }
96070
96071   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
96072   sqlite3DbFree(db, pParse->apVarExpr);
96073   sqlite3DbFree(db, pParse->aAlias);
96074   while( pParse->pAinc ){
96075     AutoincInfo *p = pParse->pAinc;
96076     pParse->pAinc = p->pNext;
96077     sqlite3DbFree(db, p);
96078   }
96079   while( pParse->pZombieTab ){
96080     Table *p = pParse->pZombieTab;
96081     pParse->pZombieTab = p->pNextZombie;
96082     sqlite3DeleteTable(p);
96083   }
96084   if( nErr>0 && pParse->rc==SQLITE_OK ){
96085     pParse->rc = SQLITE_ERROR;
96086   }
96087   return nErr;
96088 }
96089
96090 /************** End of tokenize.c ********************************************/
96091 /************** Begin file complete.c ****************************************/
96092 /*
96093 ** 2001 September 15
96094 **
96095 ** The author disclaims copyright to this source code.  In place of
96096 ** a legal notice, here is a blessing:
96097 **
96098 **    May you do good and not evil.
96099 **    May you find forgiveness for yourself and forgive others.
96100 **    May you share freely, never taking more than you give.
96101 **
96102 *************************************************************************
96103 ** An tokenizer for SQL
96104 **
96105 ** This file contains C code that implements the sqlite3_complete() API.
96106 ** This code used to be part of the tokenizer.c source file.  But by
96107 ** separating it out, the code will be automatically omitted from
96108 ** static links that do not use it.
96109 */
96110 #ifndef SQLITE_OMIT_COMPLETE
96111
96112 /*
96113 ** This is defined in tokenize.c.  We just have to import the definition.
96114 */
96115 #ifndef SQLITE_AMALGAMATION
96116 #ifdef SQLITE_ASCII
96117 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
96118 #endif
96119 #ifdef SQLITE_EBCDIC
96120 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
96121 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
96122 #endif
96123 #endif /* SQLITE_AMALGAMATION */
96124
96125
96126 /*
96127 ** Token types used by the sqlite3_complete() routine.  See the header
96128 ** comments on that procedure for additional information.
96129 */
96130 #define tkSEMI    0
96131 #define tkWS      1
96132 #define tkOTHER   2
96133 #ifndef SQLITE_OMIT_TRIGGER
96134 #define tkEXPLAIN 3
96135 #define tkCREATE  4
96136 #define tkTEMP    5
96137 #define tkTRIGGER 6
96138 #define tkEND     7
96139 #endif
96140
96141 /*
96142 ** Return TRUE if the given SQL string ends in a semicolon.
96143 **
96144 ** Special handling is require for CREATE TRIGGER statements.
96145 ** Whenever the CREATE TRIGGER keywords are seen, the statement
96146 ** must end with ";END;".
96147 **
96148 ** This implementation uses a state machine with 8 states:
96149 **
96150 **   (0) INVALID   We have not yet seen a non-whitespace character.
96151 **
96152 **   (1) START     At the beginning or end of an SQL statement.  This routine
96153 **                 returns 1 if it ends in the START state and 0 if it ends
96154 **                 in any other state.
96155 **
96156 **   (2) NORMAL    We are in the middle of statement which ends with a single
96157 **                 semicolon.
96158 **
96159 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
96160 **                 a statement.
96161 **
96162 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
96163 **                 statement, possibly preceeded by EXPLAIN and/or followed by
96164 **                 TEMP or TEMPORARY
96165 **
96166 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
96167 **                 ended by a semicolon, the keyword END, and another semicolon.
96168 **
96169 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
96170 **                 the end of a trigger definition.
96171 **
96172 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
96173 **                 of a trigger difinition.
96174 **
96175 ** Transitions between states above are determined by tokens extracted
96176 ** from the input.  The following tokens are significant:
96177 **
96178 **   (0) tkSEMI      A semicolon.
96179 **   (1) tkWS        Whitespace.
96180 **   (2) tkOTHER     Any other SQL token.
96181 **   (3) tkEXPLAIN   The "explain" keyword.
96182 **   (4) tkCREATE    The "create" keyword.
96183 **   (5) tkTEMP      The "temp" or "temporary" keyword.
96184 **   (6) tkTRIGGER   The "trigger" keyword.
96185 **   (7) tkEND       The "end" keyword.
96186 **
96187 ** Whitespace never causes a state transition and is always ignored.
96188 ** This means that a SQL string of all whitespace is invalid.
96189 **
96190 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
96191 ** to recognize the end of a trigger can be omitted.  All we have to do
96192 ** is look for a semicolon that is not part of an string or comment.
96193 */
96194 SQLITE_API int sqlite3_complete(const char *zSql){
96195   u8 state = 0;   /* Current state, using numbers defined in header comment */
96196   u8 token;       /* Value of the next token */
96197
96198 #ifndef SQLITE_OMIT_TRIGGER
96199   /* A complex statement machine used to detect the end of a CREATE TRIGGER
96200   ** statement.  This is the normal case.
96201   */
96202   static const u8 trans[8][8] = {
96203                      /* Token:                                                */
96204      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
96205      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
96206      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
96207      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
96208      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
96209      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
96210      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
96211      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
96212      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
96213   };
96214 #else
96215   /* If triggers are not supported by this compile then the statement machine
96216   ** used to detect the end of a statement is much simplier
96217   */
96218   static const u8 trans[3][3] = {
96219                      /* Token:           */
96220      /* State:       **  SEMI  WS  OTHER */
96221      /* 0 INVALID: */ {    1,  0,     2, },
96222      /* 1   START: */ {    1,  1,     2, },
96223      /* 2  NORMAL: */ {    1,  2,     2, },
96224   };
96225 #endif /* SQLITE_OMIT_TRIGGER */
96226
96227   while( *zSql ){
96228     switch( *zSql ){
96229       case ';': {  /* A semicolon */
96230         token = tkSEMI;
96231         break;
96232       }
96233       case ' ':
96234       case '\r':
96235       case '\t':
96236       case '\n':
96237       case '\f': {  /* White space is ignored */
96238         token = tkWS;
96239         break;
96240       }
96241       case '/': {   /* C-style comments */
96242         if( zSql[1]!='*' ){
96243           token = tkOTHER;
96244           break;
96245         }
96246         zSql += 2;
96247         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
96248         if( zSql[0]==0 ) return 0;
96249         zSql++;
96250         token = tkWS;
96251         break;
96252       }
96253       case '-': {   /* SQL-style comments from "--" to end of line */
96254         if( zSql[1]!='-' ){
96255           token = tkOTHER;
96256           break;
96257         }
96258         while( *zSql && *zSql!='\n' ){ zSql++; }
96259         if( *zSql==0 ) return state==1;
96260         token = tkWS;
96261         break;
96262       }
96263       case '[': {   /* Microsoft-style identifiers in [...] */
96264         zSql++;
96265         while( *zSql && *zSql!=']' ){ zSql++; }
96266         if( *zSql==0 ) return 0;
96267         token = tkOTHER;
96268         break;
96269       }
96270       case '`':     /* Grave-accent quoted symbols used by MySQL */
96271       case '"':     /* single- and double-quoted strings */
96272       case '\'': {
96273         int c = *zSql;
96274         zSql++;
96275         while( *zSql && *zSql!=c ){ zSql++; }
96276         if( *zSql==0 ) return 0;
96277         token = tkOTHER;
96278         break;
96279       }
96280       default: {
96281 #ifdef SQLITE_EBCDIC
96282         unsigned char c;
96283 #endif
96284         if( IdChar((u8)*zSql) ){
96285           /* Keywords and unquoted identifiers */
96286           int nId;
96287           for(nId=1; IdChar(zSql[nId]); nId++){}
96288 #ifdef SQLITE_OMIT_TRIGGER
96289           token = tkOTHER;
96290 #else
96291           switch( *zSql ){
96292             case 'c': case 'C': {
96293               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
96294                 token = tkCREATE;
96295               }else{
96296                 token = tkOTHER;
96297               }
96298               break;
96299             }
96300             case 't': case 'T': {
96301               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
96302                 token = tkTRIGGER;
96303               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
96304                 token = tkTEMP;
96305               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
96306                 token = tkTEMP;
96307               }else{
96308                 token = tkOTHER;
96309               }
96310               break;
96311             }
96312             case 'e':  case 'E': {
96313               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
96314                 token = tkEND;
96315               }else
96316 #ifndef SQLITE_OMIT_EXPLAIN
96317               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
96318                 token = tkEXPLAIN;
96319               }else
96320 #endif
96321               {
96322                 token = tkOTHER;
96323               }
96324               break;
96325             }
96326             default: {
96327               token = tkOTHER;
96328               break;
96329             }
96330           }
96331 #endif /* SQLITE_OMIT_TRIGGER */
96332           zSql += nId-1;
96333         }else{
96334           /* Operators and special symbols */
96335           token = tkOTHER;
96336         }
96337         break;
96338       }
96339     }
96340     state = trans[state][token];
96341     zSql++;
96342   }
96343   return state==1;
96344 }
96345
96346 #ifndef SQLITE_OMIT_UTF16
96347 /*
96348 ** This routine is the same as the sqlite3_complete() routine described
96349 ** above, except that the parameter is required to be UTF-16 encoded, not
96350 ** UTF-8.
96351 */
96352 SQLITE_API int sqlite3_complete16(const void *zSql){
96353   sqlite3_value *pVal;
96354   char const *zSql8;
96355   int rc = SQLITE_NOMEM;
96356
96357 #ifndef SQLITE_OMIT_AUTOINIT
96358   rc = sqlite3_initialize();
96359   if( rc ) return rc;
96360 #endif
96361   pVal = sqlite3ValueNew(0);
96362   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
96363   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
96364   if( zSql8 ){
96365     rc = sqlite3_complete(zSql8);
96366   }else{
96367     rc = SQLITE_NOMEM;
96368   }
96369   sqlite3ValueFree(pVal);
96370   return sqlite3ApiExit(0, rc);
96371 }
96372 #endif /* SQLITE_OMIT_UTF16 */
96373 #endif /* SQLITE_OMIT_COMPLETE */
96374
96375 /************** End of complete.c ********************************************/
96376 /************** Begin file main.c ********************************************/
96377 /*
96378 ** 2001 September 15
96379 **
96380 ** The author disclaims copyright to this source code.  In place of
96381 ** a legal notice, here is a blessing:
96382 **
96383 **    May you do good and not evil.
96384 **    May you find forgiveness for yourself and forgive others.
96385 **    May you share freely, never taking more than you give.
96386 **
96387 *************************************************************************
96388 ** Main file for the SQLite library.  The routines in this file
96389 ** implement the programmer interface to the library.  Routines in
96390 ** other files are for internal use by SQLite and should not be
96391 ** accessed by users of the library.
96392 */
96393
96394 #ifdef SQLITE_ENABLE_FTS3
96395 /************** Include fts3.h in the middle of main.c ***********************/
96396 /************** Begin file fts3.h ********************************************/
96397 /*
96398 ** 2006 Oct 10
96399 **
96400 ** The author disclaims copyright to this source code.  In place of
96401 ** a legal notice, here is a blessing:
96402 **
96403 **    May you do good and not evil.
96404 **    May you find forgiveness for yourself and forgive others.
96405 **    May you share freely, never taking more than you give.
96406 **
96407 ******************************************************************************
96408 **
96409 ** This header file is used by programs that want to link against the
96410 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
96411 */
96412
96413 #if 0
96414 extern "C" {
96415 #endif  /* __cplusplus */
96416
96417 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
96418
96419 #if 0
96420 }  /* extern "C" */
96421 #endif  /* __cplusplus */
96422
96423 /************** End of fts3.h ************************************************/
96424 /************** Continuing where we left off in main.c ***********************/
96425 #endif
96426 #ifdef SQLITE_ENABLE_RTREE
96427 /************** Include rtree.h in the middle of main.c **********************/
96428 /************** Begin file rtree.h *******************************************/
96429 /*
96430 ** 2008 May 26
96431 **
96432 ** The author disclaims copyright to this source code.  In place of
96433 ** a legal notice, here is a blessing:
96434 **
96435 **    May you do good and not evil.
96436 **    May you find forgiveness for yourself and forgive others.
96437 **    May you share freely, never taking more than you give.
96438 **
96439 ******************************************************************************
96440 **
96441 ** This header file is used by programs that want to link against the
96442 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
96443 */
96444
96445 #if 0
96446 extern "C" {
96447 #endif  /* __cplusplus */
96448
96449 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
96450
96451 #if 0
96452 }  /* extern "C" */
96453 #endif  /* __cplusplus */
96454
96455 /************** End of rtree.h ***********************************************/
96456 /************** Continuing where we left off in main.c ***********************/
96457 #endif
96458 #ifdef SQLITE_ENABLE_ICU
96459 /************** Include sqliteicu.h in the middle of main.c ******************/
96460 /************** Begin file sqliteicu.h ***************************************/
96461 /*
96462 ** 2008 May 26
96463 **
96464 ** The author disclaims copyright to this source code.  In place of
96465 ** a legal notice, here is a blessing:
96466 **
96467 **    May you do good and not evil.
96468 **    May you find forgiveness for yourself and forgive others.
96469 **    May you share freely, never taking more than you give.
96470 **
96471 ******************************************************************************
96472 **
96473 ** This header file is used by programs that want to link against the
96474 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
96475 */
96476
96477 #if 0
96478 extern "C" {
96479 #endif  /* __cplusplus */
96480
96481 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
96482
96483 #if 0
96484 }  /* extern "C" */
96485 #endif  /* __cplusplus */
96486
96487
96488 /************** End of sqliteicu.h *******************************************/
96489 /************** Continuing where we left off in main.c ***********************/
96490 #endif
96491
96492 /*
96493 ** The version of the library
96494 */
96495 #ifndef SQLITE_AMALGAMATION
96496 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
96497 #endif
96498 SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
96499 SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
96500 SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
96501 SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
96502
96503 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
96504 /*
96505 ** If the following function pointer is not NULL and if
96506 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
96507 ** I/O active are written using this function.  These messages
96508 ** are intended for debugging activity only.
96509 */
96510 SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
96511 #endif
96512
96513 /*
96514 ** If the following global variable points to a string which is the
96515 ** name of a directory, then that directory will be used to store
96516 ** temporary files.
96517 **
96518 ** See also the "PRAGMA temp_store_directory" SQL command.
96519 */
96520 SQLITE_API char *sqlite3_temp_directory = 0;
96521
96522 /*
96523 ** Initialize SQLite.  
96524 **
96525 ** This routine must be called to initialize the memory allocation,
96526 ** VFS, and mutex subsystems prior to doing any serious work with
96527 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
96528 ** this routine will be called automatically by key routines such as
96529 ** sqlite3_open().  
96530 **
96531 ** This routine is a no-op except on its very first call for the process,
96532 ** or for the first call after a call to sqlite3_shutdown.
96533 **
96534 ** The first thread to call this routine runs the initialization to
96535 ** completion.  If subsequent threads call this routine before the first
96536 ** thread has finished the initialization process, then the subsequent
96537 ** threads must block until the first thread finishes with the initialization.
96538 **
96539 ** The first thread might call this routine recursively.  Recursive
96540 ** calls to this routine should not block, of course.  Otherwise the
96541 ** initialization process would never complete.
96542 **
96543 ** Let X be the first thread to enter this routine.  Let Y be some other
96544 ** thread.  Then while the initial invocation of this routine by X is
96545 ** incomplete, it is required that:
96546 **
96547 **    *  Calls to this routine from Y must block until the outer-most
96548 **       call by X completes.
96549 **
96550 **    *  Recursive calls to this routine from thread X return immediately
96551 **       without blocking.
96552 */
96553 SQLITE_API int sqlite3_initialize(void){
96554   sqlite3_mutex *pMaster;                      /* The main static mutex */
96555   int rc;                                      /* Result code */
96556
96557 #ifdef SQLITE_OMIT_WSD
96558   rc = sqlite3_wsd_init(4096, 24);
96559   if( rc!=SQLITE_OK ){
96560     return rc;
96561   }
96562 #endif
96563
96564   /* If SQLite is already completely initialized, then this call
96565   ** to sqlite3_initialize() should be a no-op.  But the initialization
96566   ** must be complete.  So isInit must not be set until the very end
96567   ** of this routine.
96568   */
96569   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
96570
96571   /* Make sure the mutex subsystem is initialized.  If unable to 
96572   ** initialize the mutex subsystem, return early with the error.
96573   ** If the system is so sick that we are unable to allocate a mutex,
96574   ** there is not much SQLite is going to be able to do.
96575   **
96576   ** The mutex subsystem must take care of serializing its own
96577   ** initialization.
96578   */
96579   rc = sqlite3MutexInit();
96580   if( rc ) return rc;
96581
96582   /* Initialize the malloc() system and the recursive pInitMutex mutex.
96583   ** This operation is protected by the STATIC_MASTER mutex.  Note that
96584   ** MutexAlloc() is called for a static mutex prior to initializing the
96585   ** malloc subsystem - this implies that the allocation of a static
96586   ** mutex must not require support from the malloc subsystem.
96587   */
96588   pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
96589   sqlite3_mutex_enter(pMaster);
96590   sqlite3GlobalConfig.isMutexInit = 1;
96591   if( !sqlite3GlobalConfig.isMallocInit ){
96592     rc = sqlite3MallocInit();
96593   }
96594   if( rc==SQLITE_OK ){
96595     sqlite3GlobalConfig.isMallocInit = 1;
96596     if( !sqlite3GlobalConfig.pInitMutex ){
96597       sqlite3GlobalConfig.pInitMutex =
96598            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
96599       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
96600         rc = SQLITE_NOMEM;
96601       }
96602     }
96603   }
96604   if( rc==SQLITE_OK ){
96605     sqlite3GlobalConfig.nRefInitMutex++;
96606   }
96607   sqlite3_mutex_leave(pMaster);
96608
96609   /* If rc is not SQLITE_OK at this point, then either the malloc
96610   ** subsystem could not be initialized or the system failed to allocate
96611   ** the pInitMutex mutex. Return an error in either case.  */
96612   if( rc!=SQLITE_OK ){
96613     return rc;
96614   }
96615
96616   /* Do the rest of the initialization under the recursive mutex so
96617   ** that we will be able to handle recursive calls into
96618   ** sqlite3_initialize().  The recursive calls normally come through
96619   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
96620   ** recursive calls might also be possible.
96621   */
96622   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
96623   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
96624     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
96625     sqlite3GlobalConfig.inProgress = 1;
96626     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
96627     sqlite3RegisterGlobalFunctions();
96628     if( sqlite3GlobalConfig.isPCacheInit==0 ){
96629       rc = sqlite3PcacheInitialize();
96630     }
96631     if( rc==SQLITE_OK ){
96632       sqlite3GlobalConfig.isPCacheInit = 1;
96633       rc = sqlite3OsInit();
96634     }
96635     if( rc==SQLITE_OK ){
96636       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
96637           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
96638       sqlite3GlobalConfig.isInit = 1;
96639     }
96640     sqlite3GlobalConfig.inProgress = 0;
96641   }
96642   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
96643
96644   /* Go back under the static mutex and clean up the recursive
96645   ** mutex to prevent a resource leak.
96646   */
96647   sqlite3_mutex_enter(pMaster);
96648   sqlite3GlobalConfig.nRefInitMutex--;
96649   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
96650     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
96651     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
96652     sqlite3GlobalConfig.pInitMutex = 0;
96653   }
96654   sqlite3_mutex_leave(pMaster);
96655
96656   /* The following is just a sanity check to make sure SQLite has
96657   ** been compiled correctly.  It is important to run this code, but
96658   ** we don't want to run it too often and soak up CPU cycles for no
96659   ** reason.  So we run it once during initialization.
96660   */
96661 #ifndef NDEBUG
96662 #ifndef SQLITE_OMIT_FLOATING_POINT
96663   /* This section of code's only "output" is via assert() statements. */
96664   if ( rc==SQLITE_OK ){
96665     u64 x = (((u64)1)<<63)-1;
96666     double y;
96667     assert(sizeof(x)==8);
96668     assert(sizeof(x)==sizeof(y));
96669     memcpy(&y, &x, 8);
96670     assert( sqlite3IsNaN(y) );
96671   }
96672 #endif
96673 #endif
96674
96675   return rc;
96676 }
96677
96678 /*
96679 ** Undo the effects of sqlite3_initialize().  Must not be called while
96680 ** there are outstanding database connections or memory allocations or
96681 ** while any part of SQLite is otherwise in use in any thread.  This
96682 ** routine is not threadsafe.  But it is safe to invoke this routine
96683 ** on when SQLite is already shut down.  If SQLite is already shut down
96684 ** when this routine is invoked, then this routine is a harmless no-op.
96685 */
96686 SQLITE_API int sqlite3_shutdown(void){
96687   if( sqlite3GlobalConfig.isInit ){
96688     sqlite3_os_end();
96689     sqlite3_reset_auto_extension();
96690     sqlite3GlobalConfig.isInit = 0;
96691   }
96692   if( sqlite3GlobalConfig.isPCacheInit ){
96693     sqlite3PcacheShutdown();
96694     sqlite3GlobalConfig.isPCacheInit = 0;
96695   }
96696   if( sqlite3GlobalConfig.isMallocInit ){
96697     sqlite3MallocEnd();
96698     sqlite3GlobalConfig.isMallocInit = 0;
96699   }
96700   if( sqlite3GlobalConfig.isMutexInit ){
96701     sqlite3MutexEnd();
96702     sqlite3GlobalConfig.isMutexInit = 0;
96703   }
96704
96705   return SQLITE_OK;
96706 }
96707
96708 /*
96709 ** This API allows applications to modify the global configuration of
96710 ** the SQLite library at run-time.
96711 **
96712 ** This routine should only be called when there are no outstanding
96713 ** database connections or memory allocations.  This routine is not
96714 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
96715 ** behavior.
96716 */
96717 SQLITE_API int sqlite3_config(int op, ...){
96718   va_list ap;
96719   int rc = SQLITE_OK;
96720
96721   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
96722   ** the SQLite library is in use. */
96723   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
96724
96725   va_start(ap, op);
96726   switch( op ){
96727
96728     /* Mutex configuration options are only available in a threadsafe
96729     ** compile. 
96730     */
96731 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
96732     case SQLITE_CONFIG_SINGLETHREAD: {
96733       /* Disable all mutexing */
96734       sqlite3GlobalConfig.bCoreMutex = 0;
96735       sqlite3GlobalConfig.bFullMutex = 0;
96736       break;
96737     }
96738     case SQLITE_CONFIG_MULTITHREAD: {
96739       /* Disable mutexing of database connections */
96740       /* Enable mutexing of core data structures */
96741       sqlite3GlobalConfig.bCoreMutex = 1;
96742       sqlite3GlobalConfig.bFullMutex = 0;
96743       break;
96744     }
96745     case SQLITE_CONFIG_SERIALIZED: {
96746       /* Enable all mutexing */
96747       sqlite3GlobalConfig.bCoreMutex = 1;
96748       sqlite3GlobalConfig.bFullMutex = 1;
96749       break;
96750     }
96751     case SQLITE_CONFIG_MUTEX: {
96752       /* Specify an alternative mutex implementation */
96753       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
96754       break;
96755     }
96756     case SQLITE_CONFIG_GETMUTEX: {
96757       /* Retrieve the current mutex implementation */
96758       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
96759       break;
96760     }
96761 #endif
96762
96763
96764     case SQLITE_CONFIG_MALLOC: {
96765       /* Specify an alternative malloc implementation */
96766       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
96767       break;
96768     }
96769     case SQLITE_CONFIG_GETMALLOC: {
96770       /* Retrieve the current malloc() implementation */
96771       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
96772       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
96773       break;
96774     }
96775     case SQLITE_CONFIG_MEMSTATUS: {
96776       /* Enable or disable the malloc status collection */
96777       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
96778       break;
96779     }
96780     case SQLITE_CONFIG_SCRATCH: {
96781       /* Designate a buffer for scratch memory space */
96782       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
96783       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
96784       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
96785       break;
96786     }
96787     case SQLITE_CONFIG_PAGECACHE: {
96788       /* Designate a buffer for page cache memory space */
96789       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
96790       sqlite3GlobalConfig.szPage = va_arg(ap, int);
96791       sqlite3GlobalConfig.nPage = va_arg(ap, int);
96792       break;
96793     }
96794
96795     case SQLITE_CONFIG_PCACHE: {
96796       /* Specify an alternative page cache implementation */
96797       sqlite3GlobalConfig.pcache = *va_arg(ap, sqlite3_pcache_methods*);
96798       break;
96799     }
96800
96801     case SQLITE_CONFIG_GETPCACHE: {
96802       if( sqlite3GlobalConfig.pcache.xInit==0 ){
96803         sqlite3PCacheSetDefault();
96804       }
96805       *va_arg(ap, sqlite3_pcache_methods*) = sqlite3GlobalConfig.pcache;
96806       break;
96807     }
96808
96809 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
96810     case SQLITE_CONFIG_HEAP: {
96811       /* Designate a buffer for heap memory space */
96812       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
96813       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
96814       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
96815
96816       if( sqlite3GlobalConfig.pHeap==0 ){
96817         /* If the heap pointer is NULL, then restore the malloc implementation
96818         ** back to NULL pointers too.  This will cause the malloc to go
96819         ** back to its default implementation when sqlite3_initialize() is
96820         ** run.
96821         */
96822         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
96823       }else{
96824         /* The heap pointer is not NULL, then install one of the
96825         ** mem5.c/mem3.c methods. If neither ENABLE_MEMSYS3 nor
96826         ** ENABLE_MEMSYS5 is defined, return an error.
96827         */
96828 #ifdef SQLITE_ENABLE_MEMSYS3
96829         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
96830 #endif
96831 #ifdef SQLITE_ENABLE_MEMSYS5
96832         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
96833 #endif
96834       }
96835       break;
96836     }
96837 #endif
96838
96839     case SQLITE_CONFIG_LOOKASIDE: {
96840       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
96841       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
96842       break;
96843     }
96844     
96845     /* Record a pointer to the logger funcction and its first argument.
96846     ** The default is NULL.  Logging is disabled if the function pointer is
96847     ** NULL.
96848     */
96849     case SQLITE_CONFIG_LOG: {
96850       /* MSVC is picky about pulling func ptrs from va lists.
96851       ** http://support.microsoft.com/kb/47961
96852       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
96853       */
96854       typedef void(*LOGFUNC_t)(void*,int,const char*);
96855       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
96856       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
96857       break;
96858     }
96859
96860     default: {
96861       rc = SQLITE_ERROR;
96862       break;
96863     }
96864   }
96865   va_end(ap);
96866   return rc;
96867 }
96868
96869 /*
96870 ** Set up the lookaside buffers for a database connection.
96871 ** Return SQLITE_OK on success.  
96872 ** If lookaside is already active, return SQLITE_BUSY.
96873 **
96874 ** The sz parameter is the number of bytes in each lookaside slot.
96875 ** The cnt parameter is the number of slots.  If pStart is NULL the
96876 ** space for the lookaside memory is obtained from sqlite3_malloc().
96877 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
96878 ** the lookaside memory.
96879 */
96880 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
96881   void *pStart;
96882   if( db->lookaside.nOut ){
96883     return SQLITE_BUSY;
96884   }
96885   /* Free any existing lookaside buffer for this handle before
96886   ** allocating a new one so we don't have to have space for 
96887   ** both at the same time.
96888   */
96889   if( db->lookaside.bMalloced ){
96890     sqlite3_free(db->lookaside.pStart);
96891   }
96892   /* The size of a lookaside slot needs to be larger than a pointer
96893   ** to be useful.
96894   */
96895   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
96896   if( cnt<0 ) cnt = 0;
96897   if( sz==0 || cnt==0 ){
96898     sz = 0;
96899     pStart = 0;
96900   }else if( pBuf==0 ){
96901     sz = ROUND8(sz);
96902     sqlite3BeginBenignMalloc();
96903     pStart = sqlite3Malloc( sz*cnt );
96904     sqlite3EndBenignMalloc();
96905   }else{
96906     sz = ROUNDDOWN8(sz);
96907     pStart = pBuf;
96908   }
96909   db->lookaside.pStart = pStart;
96910   db->lookaside.pFree = 0;
96911   db->lookaside.sz = (u16)sz;
96912   if( pStart ){
96913     int i;
96914     LookasideSlot *p;
96915     assert( sz > (int)sizeof(LookasideSlot*) );
96916     p = (LookasideSlot*)pStart;
96917     for(i=cnt-1; i>=0; i--){
96918       p->pNext = db->lookaside.pFree;
96919       db->lookaside.pFree = p;
96920       p = (LookasideSlot*)&((u8*)p)[sz];
96921     }
96922     db->lookaside.pEnd = p;
96923     db->lookaside.bEnabled = 1;
96924     db->lookaside.bMalloced = pBuf==0 ?1:0;
96925   }else{
96926     db->lookaside.pEnd = 0;
96927     db->lookaside.bEnabled = 0;
96928     db->lookaside.bMalloced = 0;
96929   }
96930   return SQLITE_OK;
96931 }
96932
96933 /*
96934 ** Return the mutex associated with a database connection.
96935 */
96936 SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
96937   return db->mutex;
96938 }
96939
96940 /*
96941 ** Configuration settings for an individual database connection
96942 */
96943 SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
96944   va_list ap;
96945   int rc;
96946   va_start(ap, op);
96947   switch( op ){
96948     case SQLITE_DBCONFIG_LOOKASIDE: {
96949       void *pBuf = va_arg(ap, void*);
96950       int sz = va_arg(ap, int);
96951       int cnt = va_arg(ap, int);
96952       rc = setupLookaside(db, pBuf, sz, cnt);
96953       break;
96954     }
96955     default: {
96956       rc = SQLITE_ERROR;
96957       break;
96958     }
96959   }
96960   va_end(ap);
96961   return rc;
96962 }
96963
96964
96965 /*
96966 ** Return true if the buffer z[0..n-1] contains all spaces.
96967 */
96968 static int allSpaces(const char *z, int n){
96969   while( n>0 && z[n-1]==' ' ){ n--; }
96970   return n==0;
96971 }
96972
96973 /*
96974 ** This is the default collating function named "BINARY" which is always
96975 ** available.
96976 **
96977 ** If the padFlag argument is not NULL then space padding at the end
96978 ** of strings is ignored.  This implements the RTRIM collation.
96979 */
96980 static int binCollFunc(
96981   void *padFlag,
96982   int nKey1, const void *pKey1,
96983   int nKey2, const void *pKey2
96984 ){
96985   int rc, n;
96986   n = nKey1<nKey2 ? nKey1 : nKey2;
96987   rc = memcmp(pKey1, pKey2, n);
96988   if( rc==0 ){
96989     if( padFlag
96990      && allSpaces(((char*)pKey1)+n, nKey1-n)
96991      && allSpaces(((char*)pKey2)+n, nKey2-n)
96992     ){
96993       /* Leave rc unchanged at 0 */
96994     }else{
96995       rc = nKey1 - nKey2;
96996     }
96997   }
96998   return rc;
96999 }
97000
97001 /*
97002 ** Another built-in collating sequence: NOCASE. 
97003 **
97004 ** This collating sequence is intended to be used for "case independant
97005 ** comparison". SQLite's knowledge of upper and lower case equivalents
97006 ** extends only to the 26 characters used in the English language.
97007 **
97008 ** At the moment there is only a UTF-8 implementation.
97009 */
97010 static int nocaseCollatingFunc(
97011   void *NotUsed,
97012   int nKey1, const void *pKey1,
97013   int nKey2, const void *pKey2
97014 ){
97015   int r = sqlite3StrNICmp(
97016       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
97017   UNUSED_PARAMETER(NotUsed);
97018   if( 0==r ){
97019     r = nKey1-nKey2;
97020   }
97021   return r;
97022 }
97023
97024 /*
97025 ** Return the ROWID of the most recent insert
97026 */
97027 SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
97028   return db->lastRowid;
97029 }
97030
97031 /*
97032 ** Return the number of changes in the most recent call to sqlite3_exec().
97033 */
97034 SQLITE_API int sqlite3_changes(sqlite3 *db){
97035   return db->nChange;
97036 }
97037
97038 /*
97039 ** Return the number of changes since the database handle was opened.
97040 */
97041 SQLITE_API int sqlite3_total_changes(sqlite3 *db){
97042   return db->nTotalChange;
97043 }
97044
97045 /*
97046 ** Close all open savepoints. This function only manipulates fields of the
97047 ** database handle object, it does not close any savepoints that may be open
97048 ** at the b-tree/pager level.
97049 */
97050 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
97051   while( db->pSavepoint ){
97052     Savepoint *pTmp = db->pSavepoint;
97053     db->pSavepoint = pTmp->pNext;
97054     sqlite3DbFree(db, pTmp);
97055   }
97056   db->nSavepoint = 0;
97057   db->nStatement = 0;
97058   db->isTransactionSavepoint = 0;
97059 }
97060
97061 /*
97062 ** Close an existing SQLite database
97063 */
97064 SQLITE_API int sqlite3_close(sqlite3 *db){
97065   HashElem *i;
97066   int j;
97067
97068   if( !db ){
97069     return SQLITE_OK;
97070   }
97071   if( !sqlite3SafetyCheckSickOrOk(db) ){
97072     return SQLITE_MISUSE_BKPT;
97073   }
97074   sqlite3_mutex_enter(db->mutex);
97075
97076   sqlite3ResetInternalSchema(db, 0);
97077
97078   /* If a transaction is open, the ResetInternalSchema() call above
97079   ** will not have called the xDisconnect() method on any virtual
97080   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
97081   ** call will do so. We need to do this before the check for active
97082   ** SQL statements below, as the v-table implementation may be storing
97083   ** some prepared statements internally.
97084   */
97085   sqlite3VtabRollback(db);
97086
97087   /* If there are any outstanding VMs, return SQLITE_BUSY. */
97088   if( db->pVdbe ){
97089     sqlite3Error(db, SQLITE_BUSY, 
97090         "unable to close due to unfinalised statements");
97091     sqlite3_mutex_leave(db->mutex);
97092     return SQLITE_BUSY;
97093   }
97094   assert( sqlite3SafetyCheckSickOrOk(db) );
97095
97096   for(j=0; j<db->nDb; j++){
97097     Btree *pBt = db->aDb[j].pBt;
97098     if( pBt && sqlite3BtreeIsInBackup(pBt) ){
97099       sqlite3Error(db, SQLITE_BUSY, 
97100           "unable to close due to unfinished backup operation");
97101       sqlite3_mutex_leave(db->mutex);
97102       return SQLITE_BUSY;
97103     }
97104   }
97105
97106   /* Free any outstanding Savepoint structures. */
97107   sqlite3CloseSavepoints(db);
97108
97109   for(j=0; j<db->nDb; j++){
97110     struct Db *pDb = &db->aDb[j];
97111     if( pDb->pBt ){
97112       sqlite3BtreeClose(pDb->pBt);
97113       pDb->pBt = 0;
97114       if( j!=1 ){
97115         pDb->pSchema = 0;
97116       }
97117     }
97118   }
97119   sqlite3ResetInternalSchema(db, 0);
97120
97121   /* Tell the code in notify.c that the connection no longer holds any
97122   ** locks and does not require any further unlock-notify callbacks.
97123   */
97124   sqlite3ConnectionClosed(db);
97125
97126   assert( db->nDb<=2 );
97127   assert( db->aDb==db->aDbStatic );
97128   for(j=0; j<ArraySize(db->aFunc.a); j++){
97129     FuncDef *pNext, *pHash, *p;
97130     for(p=db->aFunc.a[j]; p; p=pHash){
97131       pHash = p->pHash;
97132       while( p ){
97133         pNext = p->pNext;
97134         sqlite3DbFree(db, p);
97135         p = pNext;
97136       }
97137     }
97138   }
97139   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
97140     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
97141     /* Invoke any destructors registered for collation sequence user data. */
97142     for(j=0; j<3; j++){
97143       if( pColl[j].xDel ){
97144         pColl[j].xDel(pColl[j].pUser);
97145       }
97146     }
97147     sqlite3DbFree(db, pColl);
97148   }
97149   sqlite3HashClear(&db->aCollSeq);
97150 #ifndef SQLITE_OMIT_VIRTUALTABLE
97151   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
97152     Module *pMod = (Module *)sqliteHashData(i);
97153     if( pMod->xDestroy ){
97154       pMod->xDestroy(pMod->pAux);
97155     }
97156     sqlite3DbFree(db, pMod);
97157   }
97158   sqlite3HashClear(&db->aModule);
97159 #endif
97160
97161   sqlite3Error(db, SQLITE_OK, 0); /* Deallocates any cached error strings. */
97162   if( db->pErr ){
97163     sqlite3ValueFree(db->pErr);
97164   }
97165   sqlite3CloseExtensions(db);
97166
97167   db->magic = SQLITE_MAGIC_ERROR;
97168
97169   /* The temp-database schema is allocated differently from the other schema
97170   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
97171   ** So it needs to be freed here. Todo: Why not roll the temp schema into
97172   ** the same sqliteMalloc() as the one that allocates the database 
97173   ** structure?
97174   */
97175   sqlite3DbFree(db, db->aDb[1].pSchema);
97176   sqlite3_mutex_leave(db->mutex);
97177   db->magic = SQLITE_MAGIC_CLOSED;
97178   sqlite3_mutex_free(db->mutex);
97179   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
97180   if( db->lookaside.bMalloced ){
97181     sqlite3_free(db->lookaside.pStart);
97182   }
97183   sqlite3_free(db);
97184   return SQLITE_OK;
97185 }
97186
97187 /*
97188 ** Rollback all database files.
97189 */
97190 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db){
97191   int i;
97192   int inTrans = 0;
97193   assert( sqlite3_mutex_held(db->mutex) );
97194   sqlite3BeginBenignMalloc();
97195   for(i=0; i<db->nDb; i++){
97196     if( db->aDb[i].pBt ){
97197       if( sqlite3BtreeIsInTrans(db->aDb[i].pBt) ){
97198         inTrans = 1;
97199       }
97200       sqlite3BtreeRollback(db->aDb[i].pBt);
97201       db->aDb[i].inTrans = 0;
97202     }
97203   }
97204   sqlite3VtabRollback(db);
97205   sqlite3EndBenignMalloc();
97206
97207   if( db->flags&SQLITE_InternChanges ){
97208     sqlite3ExpirePreparedStatements(db);
97209     sqlite3ResetInternalSchema(db, 0);
97210   }
97211
97212   /* Any deferred constraint violations have now been resolved. */
97213   db->nDeferredCons = 0;
97214
97215   /* If one has been configured, invoke the rollback-hook callback */
97216   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
97217     db->xRollbackCallback(db->pRollbackArg);
97218   }
97219 }
97220
97221 /*
97222 ** Return a static string that describes the kind of error specified in the
97223 ** argument.
97224 */
97225 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
97226   static const char* const aMsg[] = {
97227     /* SQLITE_OK          */ "not an error",
97228     /* SQLITE_ERROR       */ "SQL logic error or missing database",
97229     /* SQLITE_INTERNAL    */ 0,
97230     /* SQLITE_PERM        */ "access permission denied",
97231     /* SQLITE_ABORT       */ "callback requested query abort",
97232     /* SQLITE_BUSY        */ "database is locked",
97233     /* SQLITE_LOCKED      */ "database table is locked",
97234     /* SQLITE_NOMEM       */ "out of memory",
97235     /* SQLITE_READONLY    */ "attempt to write a readonly database",
97236     /* SQLITE_INTERRUPT   */ "interrupted",
97237     /* SQLITE_IOERR       */ "disk I/O error",
97238     /* SQLITE_CORRUPT     */ "database disk image is malformed",
97239     /* SQLITE_NOTFOUND    */ 0,
97240     /* SQLITE_FULL        */ "database or disk is full",
97241     /* SQLITE_CANTOPEN    */ "unable to open database file",
97242     /* SQLITE_PROTOCOL    */ 0,
97243     /* SQLITE_EMPTY       */ "table contains no data",
97244     /* SQLITE_SCHEMA      */ "database schema has changed",
97245     /* SQLITE_TOOBIG      */ "string or blob too big",
97246     /* SQLITE_CONSTRAINT  */ "constraint failed",
97247     /* SQLITE_MISMATCH    */ "datatype mismatch",
97248     /* SQLITE_MISUSE      */ "library routine called out of sequence",
97249     /* SQLITE_NOLFS       */ "large file support is disabled",
97250     /* SQLITE_AUTH        */ "authorization denied",
97251     /* SQLITE_FORMAT      */ "auxiliary database format error",
97252     /* SQLITE_RANGE       */ "bind or column index out of range",
97253     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
97254   };
97255   rc &= 0xff;
97256   if( ALWAYS(rc>=0) && rc<(int)(sizeof(aMsg)/sizeof(aMsg[0])) && aMsg[rc]!=0 ){
97257     return aMsg[rc];
97258   }else{
97259     return "unknown error";
97260   }
97261 }
97262
97263 /*
97264 ** This routine implements a busy callback that sleeps and tries
97265 ** again until a timeout value is reached.  The timeout value is
97266 ** an integer number of milliseconds passed in as the first
97267 ** argument.
97268 */
97269 static int sqliteDefaultBusyCallback(
97270  void *ptr,               /* Database connection */
97271  int count                /* Number of times table has been busy */
97272 ){
97273 #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
97274   static const u8 delays[] =
97275      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
97276   static const u8 totals[] =
97277      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
97278 # define NDELAY (sizeof(delays)/sizeof(delays[0]))
97279   sqlite3 *db = (sqlite3 *)ptr;
97280   int timeout = db->busyTimeout;
97281   int delay, prior;
97282
97283   assert( count>=0 );
97284   if( count < NDELAY ){
97285     delay = delays[count];
97286     prior = totals[count];
97287   }else{
97288     delay = delays[NDELAY-1];
97289     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
97290   }
97291   if( prior + delay > timeout ){
97292     delay = timeout - prior;
97293     if( delay<=0 ) return 0;
97294   }
97295   sqlite3OsSleep(db->pVfs, delay*1000);
97296   return 1;
97297 #else
97298   sqlite3 *db = (sqlite3 *)ptr;
97299   int timeout = ((sqlite3 *)ptr)->busyTimeout;
97300   if( (count+1)*1000 > timeout ){
97301     return 0;
97302   }
97303   sqlite3OsSleep(db->pVfs, 1000000);
97304   return 1;
97305 #endif
97306 }
97307
97308 /*
97309 ** Invoke the given busy handler.
97310 **
97311 ** This routine is called when an operation failed with a lock.
97312 ** If this routine returns non-zero, the lock is retried.  If it
97313 ** returns 0, the operation aborts with an SQLITE_BUSY error.
97314 */
97315 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
97316   int rc;
97317   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
97318   rc = p->xFunc(p->pArg, p->nBusy);
97319   if( rc==0 ){
97320     p->nBusy = -1;
97321   }else{
97322     p->nBusy++;
97323   }
97324   return rc; 
97325 }
97326
97327 /*
97328 ** This routine sets the busy callback for an Sqlite database to the
97329 ** given callback function with the given argument.
97330 */
97331 SQLITE_API int sqlite3_busy_handler(
97332   sqlite3 *db,
97333   int (*xBusy)(void*,int),
97334   void *pArg
97335 ){
97336   sqlite3_mutex_enter(db->mutex);
97337   db->busyHandler.xFunc = xBusy;
97338   db->busyHandler.pArg = pArg;
97339   db->busyHandler.nBusy = 0;
97340   sqlite3_mutex_leave(db->mutex);
97341   return SQLITE_OK;
97342 }
97343
97344 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
97345 /*
97346 ** This routine sets the progress callback for an Sqlite database to the
97347 ** given callback function with the given argument. The progress callback will
97348 ** be invoked every nOps opcodes.
97349 */
97350 SQLITE_API void sqlite3_progress_handler(
97351   sqlite3 *db, 
97352   int nOps,
97353   int (*xProgress)(void*), 
97354   void *pArg
97355 ){
97356   sqlite3_mutex_enter(db->mutex);
97357   if( nOps>0 ){
97358     db->xProgress = xProgress;
97359     db->nProgressOps = nOps;
97360     db->pProgressArg = pArg;
97361   }else{
97362     db->xProgress = 0;
97363     db->nProgressOps = 0;
97364     db->pProgressArg = 0;
97365   }
97366   sqlite3_mutex_leave(db->mutex);
97367 }
97368 #endif
97369
97370
97371 /*
97372 ** This routine installs a default busy handler that waits for the
97373 ** specified number of milliseconds before returning 0.
97374 */
97375 SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
97376   if( ms>0 ){
97377     db->busyTimeout = ms;
97378     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
97379   }else{
97380     sqlite3_busy_handler(db, 0, 0);
97381   }
97382   return SQLITE_OK;
97383 }
97384
97385 /*
97386 ** Cause any pending operation to stop at its earliest opportunity.
97387 */
97388 SQLITE_API void sqlite3_interrupt(sqlite3 *db){
97389   db->u1.isInterrupted = 1;
97390 }
97391
97392
97393 /*
97394 ** This function is exactly the same as sqlite3_create_function(), except
97395 ** that it is designed to be called by internal code. The difference is
97396 ** that if a malloc() fails in sqlite3_create_function(), an error code
97397 ** is returned and the mallocFailed flag cleared. 
97398 */
97399 SQLITE_PRIVATE int sqlite3CreateFunc(
97400   sqlite3 *db,
97401   const char *zFunctionName,
97402   int nArg,
97403   int enc,
97404   void *pUserData,
97405   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
97406   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
97407   void (*xFinal)(sqlite3_context*)
97408 ){
97409   FuncDef *p;
97410   int nName;
97411
97412   assert( sqlite3_mutex_held(db->mutex) );
97413   if( zFunctionName==0 ||
97414       (xFunc && (xFinal || xStep)) || 
97415       (!xFunc && (xFinal && !xStep)) ||
97416       (!xFunc && (!xFinal && xStep)) ||
97417       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
97418       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
97419     return SQLITE_MISUSE_BKPT;
97420   }
97421   
97422 #ifndef SQLITE_OMIT_UTF16
97423   /* If SQLITE_UTF16 is specified as the encoding type, transform this
97424   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
97425   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
97426   **
97427   ** If SQLITE_ANY is specified, add three versions of the function
97428   ** to the hash table.
97429   */
97430   if( enc==SQLITE_UTF16 ){
97431     enc = SQLITE_UTF16NATIVE;
97432   }else if( enc==SQLITE_ANY ){
97433     int rc;
97434     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8,
97435          pUserData, xFunc, xStep, xFinal);
97436     if( rc==SQLITE_OK ){
97437       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE,
97438           pUserData, xFunc, xStep, xFinal);
97439     }
97440     if( rc!=SQLITE_OK ){
97441       return rc;
97442     }
97443     enc = SQLITE_UTF16BE;
97444   }
97445 #else
97446   enc = SQLITE_UTF8;
97447 #endif
97448   
97449   /* Check if an existing function is being overridden or deleted. If so,
97450   ** and there are active VMs, then return SQLITE_BUSY. If a function
97451   ** is being overridden/deleted but there are no active VMs, allow the
97452   ** operation to continue but invalidate all precompiled statements.
97453   */
97454   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
97455   if( p && p->iPrefEnc==enc && p->nArg==nArg ){
97456     if( db->activeVdbeCnt ){
97457       sqlite3Error(db, SQLITE_BUSY, 
97458         "unable to delete/modify user-function due to active statements");
97459       assert( !db->mallocFailed );
97460       return SQLITE_BUSY;
97461     }else{
97462       sqlite3ExpirePreparedStatements(db);
97463     }
97464   }
97465
97466   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
97467   assert(p || db->mallocFailed);
97468   if( !p ){
97469     return SQLITE_NOMEM;
97470   }
97471   p->flags = 0;
97472   p->xFunc = xFunc;
97473   p->xStep = xStep;
97474   p->xFinalize = xFinal;
97475   p->pUserData = pUserData;
97476   p->nArg = (u16)nArg;
97477   return SQLITE_OK;
97478 }
97479
97480 /*
97481 ** Create new user functions.
97482 */
97483 SQLITE_API int sqlite3_create_function(
97484   sqlite3 *db,
97485   const char *zFunctionName,
97486   int nArg,
97487   int enc,
97488   void *p,
97489   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
97490   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
97491   void (*xFinal)(sqlite3_context*)
97492 ){
97493   int rc;
97494   sqlite3_mutex_enter(db->mutex);
97495   rc = sqlite3CreateFunc(db, zFunctionName, nArg, enc, p, xFunc, xStep, xFinal);
97496   rc = sqlite3ApiExit(db, rc);
97497   sqlite3_mutex_leave(db->mutex);
97498   return rc;
97499 }
97500
97501 #ifndef SQLITE_OMIT_UTF16
97502 SQLITE_API int sqlite3_create_function16(
97503   sqlite3 *db,
97504   const void *zFunctionName,
97505   int nArg,
97506   int eTextRep,
97507   void *p,
97508   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
97509   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
97510   void (*xFinal)(sqlite3_context*)
97511 ){
97512   int rc;
97513   char *zFunc8;
97514   sqlite3_mutex_enter(db->mutex);
97515   assert( !db->mallocFailed );
97516   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
97517   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal);
97518   sqlite3DbFree(db, zFunc8);
97519   rc = sqlite3ApiExit(db, rc);
97520   sqlite3_mutex_leave(db->mutex);
97521   return rc;
97522 }
97523 #endif
97524
97525
97526 /*
97527 ** Declare that a function has been overloaded by a virtual table.
97528 **
97529 ** If the function already exists as a regular global function, then
97530 ** this routine is a no-op.  If the function does not exist, then create
97531 ** a new one that always throws a run-time error.  
97532 **
97533 ** When virtual tables intend to provide an overloaded function, they
97534 ** should call this routine to make sure the global function exists.
97535 ** A global function must exist in order for name resolution to work
97536 ** properly.
97537 */
97538 SQLITE_API int sqlite3_overload_function(
97539   sqlite3 *db,
97540   const char *zName,
97541   int nArg
97542 ){
97543   int nName = sqlite3Strlen30(zName);
97544   int rc;
97545   sqlite3_mutex_enter(db->mutex);
97546   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
97547     sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
97548                       0, sqlite3InvalidFunction, 0, 0);
97549   }
97550   rc = sqlite3ApiExit(db, SQLITE_OK);
97551   sqlite3_mutex_leave(db->mutex);
97552   return rc;
97553 }
97554
97555 #ifndef SQLITE_OMIT_TRACE
97556 /*
97557 ** Register a trace function.  The pArg from the previously registered trace
97558 ** is returned.  
97559 **
97560 ** A NULL trace function means that no tracing is executes.  A non-NULL
97561 ** trace is a pointer to a function that is invoked at the start of each
97562 ** SQL statement.
97563 */
97564 SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
97565   void *pOld;
97566   sqlite3_mutex_enter(db->mutex);
97567   pOld = db->pTraceArg;
97568   db->xTrace = xTrace;
97569   db->pTraceArg = pArg;
97570   sqlite3_mutex_leave(db->mutex);
97571   return pOld;
97572 }
97573 /*
97574 ** Register a profile function.  The pArg from the previously registered 
97575 ** profile function is returned.  
97576 **
97577 ** A NULL profile function means that no profiling is executes.  A non-NULL
97578 ** profile is a pointer to a function that is invoked at the conclusion of
97579 ** each SQL statement that is run.
97580 */
97581 SQLITE_API void *sqlite3_profile(
97582   sqlite3 *db,
97583   void (*xProfile)(void*,const char*,sqlite_uint64),
97584   void *pArg
97585 ){
97586   void *pOld;
97587   sqlite3_mutex_enter(db->mutex);
97588   pOld = db->pProfileArg;
97589   db->xProfile = xProfile;
97590   db->pProfileArg = pArg;
97591   sqlite3_mutex_leave(db->mutex);
97592   return pOld;
97593 }
97594 #endif /* SQLITE_OMIT_TRACE */
97595
97596 /*** EXPERIMENTAL ***
97597 **
97598 ** Register a function to be invoked when a transaction comments.
97599 ** If the invoked function returns non-zero, then the commit becomes a
97600 ** rollback.
97601 */
97602 SQLITE_API void *sqlite3_commit_hook(
97603   sqlite3 *db,              /* Attach the hook to this database */
97604   int (*xCallback)(void*),  /* Function to invoke on each commit */
97605   void *pArg                /* Argument to the function */
97606 ){
97607   void *pOld;
97608   sqlite3_mutex_enter(db->mutex);
97609   pOld = db->pCommitArg;
97610   db->xCommitCallback = xCallback;
97611   db->pCommitArg = pArg;
97612   sqlite3_mutex_leave(db->mutex);
97613   return pOld;
97614 }
97615
97616 /*
97617 ** Register a callback to be invoked each time a row is updated,
97618 ** inserted or deleted using this database connection.
97619 */
97620 SQLITE_API void *sqlite3_update_hook(
97621   sqlite3 *db,              /* Attach the hook to this database */
97622   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
97623   void *pArg                /* Argument to the function */
97624 ){
97625   void *pRet;
97626   sqlite3_mutex_enter(db->mutex);
97627   pRet = db->pUpdateArg;
97628   db->xUpdateCallback = xCallback;
97629   db->pUpdateArg = pArg;
97630   sqlite3_mutex_leave(db->mutex);
97631   return pRet;
97632 }
97633
97634 /*
97635 ** Register a callback to be invoked each time a transaction is rolled
97636 ** back by this database connection.
97637 */
97638 SQLITE_API void *sqlite3_rollback_hook(
97639   sqlite3 *db,              /* Attach the hook to this database */
97640   void (*xCallback)(void*), /* Callback function */
97641   void *pArg                /* Argument to the function */
97642 ){
97643   void *pRet;
97644   sqlite3_mutex_enter(db->mutex);
97645   pRet = db->pRollbackArg;
97646   db->xRollbackCallback = xCallback;
97647   db->pRollbackArg = pArg;
97648   sqlite3_mutex_leave(db->mutex);
97649   return pRet;
97650 }
97651
97652 /*
97653 ** This function returns true if main-memory should be used instead of
97654 ** a temporary file for transient pager files and statement journals.
97655 ** The value returned depends on the value of db->temp_store (runtime
97656 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
97657 ** following table describes the relationship between these two values
97658 ** and this functions return value.
97659 **
97660 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
97661 **   -----------------     --------------     ------------------------------
97662 **   0                     any                file      (return 0)
97663 **   1                     1                  file      (return 0)
97664 **   1                     2                  memory    (return 1)
97665 **   1                     0                  file      (return 0)
97666 **   2                     1                  file      (return 0)
97667 **   2                     2                  memory    (return 1)
97668 **   2                     0                  memory    (return 1)
97669 **   3                     any                memory    (return 1)
97670 */
97671 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
97672 #if SQLITE_TEMP_STORE==1
97673   return ( db->temp_store==2 );
97674 #endif
97675 #if SQLITE_TEMP_STORE==2
97676   return ( db->temp_store!=1 );
97677 #endif
97678 #if SQLITE_TEMP_STORE==3
97679   return 1;
97680 #endif
97681 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
97682   return 0;
97683 #endif
97684 }
97685
97686 /*
97687 ** This routine is called to create a connection to a database BTree
97688 ** driver.  If zFilename is the name of a file, then that file is
97689 ** opened and used.  If zFilename is the magic name ":memory:" then
97690 ** the database is stored in memory (and is thus forgotten as soon as
97691 ** the connection is closed.)  If zFilename is NULL then the database
97692 ** is a "virtual" database for transient use only and is deleted as
97693 ** soon as the connection is closed.
97694 **
97695 ** A virtual database can be either a disk file (that is automatically
97696 ** deleted when the file is closed) or it an be held entirely in memory.
97697 ** The sqlite3TempInMemory() function is used to determine which.
97698 */
97699 SQLITE_PRIVATE int sqlite3BtreeFactory(
97700   sqlite3 *db,              /* Main database when opening aux otherwise 0 */
97701   const char *zFilename,    /* Name of the file containing the BTree database */
97702   int omitJournal,          /* if TRUE then do not journal this file */
97703   int nCache,               /* How many pages in the page cache */
97704   int vfsFlags,             /* Flags passed through to vfsOpen */
97705   Btree **ppBtree           /* Pointer to new Btree object written here */
97706 ){
97707   int btFlags = 0;
97708   int rc;
97709   
97710   assert( sqlite3_mutex_held(db->mutex) );
97711   assert( ppBtree != 0);
97712   if( omitJournal ){
97713     btFlags |= BTREE_OMIT_JOURNAL;
97714   }
97715   if( db->flags & SQLITE_NoReadlock ){
97716     btFlags |= BTREE_NO_READLOCK;
97717   }
97718 #ifndef SQLITE_OMIT_MEMORYDB
97719   if( zFilename==0 && sqlite3TempInMemory(db) ){
97720     zFilename = ":memory:";
97721   }
97722 #endif
97723
97724   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (zFilename==0 || *zFilename==0) ){
97725     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
97726   }
97727   rc = sqlite3BtreeOpen(zFilename, (sqlite3 *)db, ppBtree, btFlags, vfsFlags);
97728
97729   /* If the B-Tree was successfully opened, set the pager-cache size to the
97730   ** default value. Except, if the call to BtreeOpen() returned a handle
97731   ** open on an existing shared pager-cache, do not change the pager-cache 
97732   ** size.
97733   */
97734   if( rc==SQLITE_OK && 0==sqlite3BtreeSchema(*ppBtree, 0, 0) ){
97735     sqlite3BtreeSetCacheSize(*ppBtree, nCache);
97736   }
97737   return rc;
97738 }
97739
97740 /*
97741 ** Return UTF-8 encoded English language explanation of the most recent
97742 ** error.
97743 */
97744 SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
97745   const char *z;
97746   if( !db ){
97747     return sqlite3ErrStr(SQLITE_NOMEM);
97748   }
97749   if( !sqlite3SafetyCheckSickOrOk(db) ){
97750     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
97751   }
97752   sqlite3_mutex_enter(db->mutex);
97753   if( db->mallocFailed ){
97754     z = sqlite3ErrStr(SQLITE_NOMEM);
97755   }else{
97756     z = (char*)sqlite3_value_text(db->pErr);
97757     assert( !db->mallocFailed );
97758     if( z==0 ){
97759       z = sqlite3ErrStr(db->errCode);
97760     }
97761   }
97762   sqlite3_mutex_leave(db->mutex);
97763   return z;
97764 }
97765
97766 #ifndef SQLITE_OMIT_UTF16
97767 /*
97768 ** Return UTF-16 encoded English language explanation of the most recent
97769 ** error.
97770 */
97771 SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
97772   static const u16 outOfMem[] = {
97773     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
97774   };
97775   static const u16 misuse[] = {
97776     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 
97777     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 
97778     'c', 'a', 'l', 'l', 'e', 'd', ' ', 
97779     'o', 'u', 't', ' ', 
97780     'o', 'f', ' ', 
97781     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
97782   };
97783
97784   const void *z;
97785   if( !db ){
97786     return (void *)outOfMem;
97787   }
97788   if( !sqlite3SafetyCheckSickOrOk(db) ){
97789     return (void *)misuse;
97790   }
97791   sqlite3_mutex_enter(db->mutex);
97792   if( db->mallocFailed ){
97793     z = (void *)outOfMem;
97794   }else{
97795     z = sqlite3_value_text16(db->pErr);
97796     if( z==0 ){
97797       sqlite3ValueSetStr(db->pErr, -1, sqlite3ErrStr(db->errCode),
97798            SQLITE_UTF8, SQLITE_STATIC);
97799       z = sqlite3_value_text16(db->pErr);
97800     }
97801     /* A malloc() may have failed within the call to sqlite3_value_text16()
97802     ** above. If this is the case, then the db->mallocFailed flag needs to
97803     ** be cleared before returning. Do this directly, instead of via
97804     ** sqlite3ApiExit(), to avoid setting the database handle error message.
97805     */
97806     db->mallocFailed = 0;
97807   }
97808   sqlite3_mutex_leave(db->mutex);
97809   return z;
97810 }
97811 #endif /* SQLITE_OMIT_UTF16 */
97812
97813 /*
97814 ** Return the most recent error code generated by an SQLite routine. If NULL is
97815 ** passed to this function, we assume a malloc() failed during sqlite3_open().
97816 */
97817 SQLITE_API int sqlite3_errcode(sqlite3 *db){
97818   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
97819     return SQLITE_MISUSE_BKPT;
97820   }
97821   if( !db || db->mallocFailed ){
97822     return SQLITE_NOMEM;
97823   }
97824   return db->errCode & db->errMask;
97825 }
97826 SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
97827   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
97828     return SQLITE_MISUSE_BKPT;
97829   }
97830   if( !db || db->mallocFailed ){
97831     return SQLITE_NOMEM;
97832   }
97833   return db->errCode;
97834 }
97835
97836 /*
97837 ** Create a new collating function for database "db".  The name is zName
97838 ** and the encoding is enc.
97839 */
97840 static int createCollation(
97841   sqlite3* db,
97842   const char *zName, 
97843   u8 enc,
97844   u8 collType,
97845   void* pCtx,
97846   int(*xCompare)(void*,int,const void*,int,const void*),
97847   void(*xDel)(void*)
97848 ){
97849   CollSeq *pColl;
97850   int enc2;
97851   int nName = sqlite3Strlen30(zName);
97852   
97853   assert( sqlite3_mutex_held(db->mutex) );
97854
97855   /* If SQLITE_UTF16 is specified as the encoding type, transform this
97856   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
97857   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
97858   */
97859   enc2 = enc;
97860   testcase( enc2==SQLITE_UTF16 );
97861   testcase( enc2==SQLITE_UTF16_ALIGNED );
97862   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
97863     enc2 = SQLITE_UTF16NATIVE;
97864   }
97865   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
97866     return SQLITE_MISUSE_BKPT;
97867   }
97868
97869   /* Check if this call is removing or replacing an existing collation 
97870   ** sequence. If so, and there are active VMs, return busy. If there
97871   ** are no active VMs, invalidate any pre-compiled statements.
97872   */
97873   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
97874   if( pColl && pColl->xCmp ){
97875     if( db->activeVdbeCnt ){
97876       sqlite3Error(db, SQLITE_BUSY, 
97877         "unable to delete/modify collation sequence due to active statements");
97878       return SQLITE_BUSY;
97879     }
97880     sqlite3ExpirePreparedStatements(db);
97881
97882     /* If collation sequence pColl was created directly by a call to
97883     ** sqlite3_create_collation, and not generated by synthCollSeq(),
97884     ** then any copies made by synthCollSeq() need to be invalidated.
97885     ** Also, collation destructor - CollSeq.xDel() - function may need
97886     ** to be called.
97887     */ 
97888     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
97889       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName, nName);
97890       int j;
97891       for(j=0; j<3; j++){
97892         CollSeq *p = &aColl[j];
97893         if( p->enc==pColl->enc ){
97894           if( p->xDel ){
97895             p->xDel(p->pUser);
97896           }
97897           p->xCmp = 0;
97898         }
97899       }
97900     }
97901   }
97902
97903   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
97904   if( pColl ){
97905     pColl->xCmp = xCompare;
97906     pColl->pUser = pCtx;
97907     pColl->xDel = xDel;
97908     pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
97909     pColl->type = collType;
97910   }
97911   sqlite3Error(db, SQLITE_OK, 0);
97912   return SQLITE_OK;
97913 }
97914
97915
97916 /*
97917 ** This array defines hard upper bounds on limit values.  The
97918 ** initializer must be kept in sync with the SQLITE_LIMIT_*
97919 ** #defines in sqlite3.h.
97920 */
97921 static const int aHardLimit[] = {
97922   SQLITE_MAX_LENGTH,
97923   SQLITE_MAX_SQL_LENGTH,
97924   SQLITE_MAX_COLUMN,
97925   SQLITE_MAX_EXPR_DEPTH,
97926   SQLITE_MAX_COMPOUND_SELECT,
97927   SQLITE_MAX_VDBE_OP,
97928   SQLITE_MAX_FUNCTION_ARG,
97929   SQLITE_MAX_ATTACHED,
97930   SQLITE_MAX_LIKE_PATTERN_LENGTH,
97931   SQLITE_MAX_VARIABLE_NUMBER,
97932   SQLITE_MAX_TRIGGER_DEPTH,
97933 };
97934
97935 /*
97936 ** Make sure the hard limits are set to reasonable values
97937 */
97938 #if SQLITE_MAX_LENGTH<100
97939 # error SQLITE_MAX_LENGTH must be at least 100
97940 #endif
97941 #if SQLITE_MAX_SQL_LENGTH<100
97942 # error SQLITE_MAX_SQL_LENGTH must be at least 100
97943 #endif
97944 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
97945 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
97946 #endif
97947 #if SQLITE_MAX_COMPOUND_SELECT<2
97948 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
97949 #endif
97950 #if SQLITE_MAX_VDBE_OP<40
97951 # error SQLITE_MAX_VDBE_OP must be at least 40
97952 #endif
97953 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
97954 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
97955 #endif
97956 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>30
97957 # error SQLITE_MAX_ATTACHED must be between 0 and 30
97958 #endif
97959 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
97960 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
97961 #endif
97962 #if SQLITE_MAX_COLUMN>32767
97963 # error SQLITE_MAX_COLUMN must not exceed 32767
97964 #endif
97965 #if SQLITE_MAX_TRIGGER_DEPTH<1
97966 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
97967 #endif
97968
97969
97970 /*
97971 ** Change the value of a limit.  Report the old value.
97972 ** If an invalid limit index is supplied, report -1.
97973 ** Make no changes but still report the old value if the
97974 ** new limit is negative.
97975 **
97976 ** A new lower limit does not shrink existing constructs.
97977 ** It merely prevents new constructs that exceed the limit
97978 ** from forming.
97979 */
97980 SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
97981   int oldLimit;
97982   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
97983     return -1;
97984   }
97985   oldLimit = db->aLimit[limitId];
97986   if( newLimit>=0 ){
97987     if( newLimit>aHardLimit[limitId] ){
97988       newLimit = aHardLimit[limitId];
97989     }
97990     db->aLimit[limitId] = newLimit;
97991   }
97992   return oldLimit;
97993 }
97994
97995 /*
97996 ** This routine does the work of opening a database on behalf of
97997 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
97998 ** is UTF-8 encoded.
97999 */
98000 static int openDatabase(
98001   const char *zFilename, /* Database filename UTF-8 encoded */
98002   sqlite3 **ppDb,        /* OUT: Returned database handle */
98003   unsigned flags,        /* Operational flags */
98004   const char *zVfs       /* Name of the VFS to use */
98005 ){
98006   sqlite3 *db;
98007   int rc;
98008   int isThreadsafe;
98009
98010   *ppDb = 0;
98011 #ifndef SQLITE_OMIT_AUTOINIT
98012   rc = sqlite3_initialize();
98013   if( rc ) return rc;
98014 #endif
98015
98016   if( sqlite3GlobalConfig.bCoreMutex==0 ){
98017     isThreadsafe = 0;
98018   }else if( flags & SQLITE_OPEN_NOMUTEX ){
98019     isThreadsafe = 0;
98020   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
98021     isThreadsafe = 1;
98022   }else{
98023     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
98024   }
98025   if( flags & SQLITE_OPEN_PRIVATECACHE ){
98026     flags &= ~SQLITE_OPEN_SHAREDCACHE;
98027   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
98028     flags |= SQLITE_OPEN_SHAREDCACHE;
98029   }
98030
98031   /* Remove harmful bits from the flags parameter
98032   **
98033   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
98034   ** dealt with in the previous code block.  Besides these, the only
98035   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
98036   ** SQLITE_OPEN_READWRITE, and SQLITE_OPEN_CREATE.  Silently mask
98037   ** off all other flags.
98038   */
98039   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
98040                SQLITE_OPEN_EXCLUSIVE |
98041                SQLITE_OPEN_MAIN_DB |
98042                SQLITE_OPEN_TEMP_DB | 
98043                SQLITE_OPEN_TRANSIENT_DB | 
98044                SQLITE_OPEN_MAIN_JOURNAL | 
98045                SQLITE_OPEN_TEMP_JOURNAL | 
98046                SQLITE_OPEN_SUBJOURNAL | 
98047                SQLITE_OPEN_MASTER_JOURNAL |
98048                SQLITE_OPEN_NOMUTEX |
98049                SQLITE_OPEN_FULLMUTEX
98050              );
98051
98052   /* Allocate the sqlite data structure */
98053   db = sqlite3MallocZero( sizeof(sqlite3) );
98054   if( db==0 ) goto opendb_out;
98055   if( isThreadsafe ){
98056     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
98057     if( db->mutex==0 ){
98058       sqlite3_free(db);
98059       db = 0;
98060       goto opendb_out;
98061     }
98062   }
98063   sqlite3_mutex_enter(db->mutex);
98064   db->errMask = 0xff;
98065   db->nDb = 2;
98066   db->magic = SQLITE_MAGIC_BUSY;
98067   db->aDb = db->aDbStatic;
98068
98069   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
98070   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
98071   db->autoCommit = 1;
98072   db->nextAutovac = -1;
98073   db->nextPagesize = 0;
98074   db->flags |= SQLITE_ShortColNames
98075 #if SQLITE_DEFAULT_FILE_FORMAT<4
98076                  | SQLITE_LegacyFileFmt
98077 #endif
98078 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
98079                  | SQLITE_LoadExtension
98080 #endif
98081 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
98082                  | SQLITE_RecTriggers
98083 #endif
98084       ;
98085   sqlite3HashInit(&db->aCollSeq);
98086 #ifndef SQLITE_OMIT_VIRTUALTABLE
98087   sqlite3HashInit(&db->aModule);
98088 #endif
98089
98090   db->pVfs = sqlite3_vfs_find(zVfs);
98091   if( !db->pVfs ){
98092     rc = SQLITE_ERROR;
98093     sqlite3Error(db, rc, "no such vfs: %s", zVfs);
98094     goto opendb_out;
98095   }
98096
98097   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
98098   ** and UTF-16, so add a version for each to avoid any unnecessary
98099   ** conversions. The only error that can occur here is a malloc() failure.
98100   */
98101   createCollation(db, "BINARY", SQLITE_UTF8, SQLITE_COLL_BINARY, 0,
98102                   binCollFunc, 0);
98103   createCollation(db, "BINARY", SQLITE_UTF16BE, SQLITE_COLL_BINARY, 0,
98104                   binCollFunc, 0);
98105   createCollation(db, "BINARY", SQLITE_UTF16LE, SQLITE_COLL_BINARY, 0,
98106                   binCollFunc, 0);
98107   createCollation(db, "RTRIM", SQLITE_UTF8, SQLITE_COLL_USER, (void*)1,
98108                   binCollFunc, 0);
98109   if( db->mallocFailed ){
98110     goto opendb_out;
98111   }
98112   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
98113   assert( db->pDfltColl!=0 );
98114
98115   /* Also add a UTF-8 case-insensitive collation sequence. */
98116   createCollation(db, "NOCASE", SQLITE_UTF8, SQLITE_COLL_NOCASE, 0,
98117                   nocaseCollatingFunc, 0);
98118
98119   /* Open the backend database driver */
98120   db->openFlags = flags;
98121   rc = sqlite3BtreeFactory(db, zFilename, 0, SQLITE_DEFAULT_CACHE_SIZE, 
98122                            flags | SQLITE_OPEN_MAIN_DB,
98123                            &db->aDb[0].pBt);
98124   if( rc!=SQLITE_OK ){
98125     if( rc==SQLITE_IOERR_NOMEM ){
98126       rc = SQLITE_NOMEM;
98127     }
98128     sqlite3Error(db, rc, 0);
98129     goto opendb_out;
98130   }
98131   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
98132   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
98133
98134
98135   /* The default safety_level for the main database is 'full'; for the temp
98136   ** database it is 'NONE'. This matches the pager layer defaults.  
98137   */
98138   db->aDb[0].zName = "main";
98139   db->aDb[0].safety_level = 3;
98140   db->aDb[1].zName = "temp";
98141   db->aDb[1].safety_level = 1;
98142
98143   db->magic = SQLITE_MAGIC_OPEN;
98144   if( db->mallocFailed ){
98145     goto opendb_out;
98146   }
98147
98148   /* Register all built-in functions, but do not attempt to read the
98149   ** database schema yet. This is delayed until the first time the database
98150   ** is accessed.
98151   */
98152   sqlite3Error(db, SQLITE_OK, 0);
98153   sqlite3RegisterBuiltinFunctions(db);
98154
98155   /* Load automatic extensions - extensions that have been registered
98156   ** using the sqlite3_automatic_extension() API.
98157   */
98158   sqlite3AutoLoadExtensions(db);
98159   rc = sqlite3_errcode(db);
98160   if( rc!=SQLITE_OK ){
98161     goto opendb_out;
98162   }
98163
98164 #ifdef SQLITE_ENABLE_FTS1
98165   if( !db->mallocFailed ){
98166     extern int sqlite3Fts1Init(sqlite3*);
98167     rc = sqlite3Fts1Init(db);
98168   }
98169 #endif
98170
98171 #ifdef SQLITE_ENABLE_FTS2
98172   if( !db->mallocFailed && rc==SQLITE_OK ){
98173     extern int sqlite3Fts2Init(sqlite3*);
98174     rc = sqlite3Fts2Init(db);
98175   }
98176 #endif
98177
98178 #ifdef SQLITE_ENABLE_FTS3
98179   if( !db->mallocFailed && rc==SQLITE_OK ){
98180     rc = sqlite3Fts3Init(db);
98181   }
98182 #endif
98183
98184 #ifdef SQLITE_ENABLE_ICU
98185   if( !db->mallocFailed && rc==SQLITE_OK ){
98186     rc = sqlite3IcuInit(db);
98187   }
98188 #endif
98189
98190 #ifdef SQLITE_ENABLE_RTREE
98191   if( !db->mallocFailed && rc==SQLITE_OK){
98192     rc = sqlite3RtreeInit(db);
98193   }
98194 #endif
98195
98196   sqlite3Error(db, rc, 0);
98197
98198   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
98199   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
98200   ** mode.  Doing nothing at all also makes NORMAL the default.
98201   */
98202 #ifdef SQLITE_DEFAULT_LOCKING_MODE
98203   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
98204   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
98205                           SQLITE_DEFAULT_LOCKING_MODE);
98206 #endif
98207
98208   /* Enable the lookaside-malloc subsystem */
98209   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
98210                         sqlite3GlobalConfig.nLookaside);
98211
98212 opendb_out:
98213   if( db ){
98214     assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
98215     sqlite3_mutex_leave(db->mutex);
98216   }
98217   rc = sqlite3_errcode(db);
98218   if( rc==SQLITE_NOMEM ){
98219     sqlite3_close(db);
98220     db = 0;
98221   }else if( rc!=SQLITE_OK ){
98222     db->magic = SQLITE_MAGIC_SICK;
98223   }
98224   *ppDb = db;
98225   return sqlite3ApiExit(0, rc);
98226 }
98227
98228 /*
98229 ** Open a new database handle.
98230 */
98231 SQLITE_API int sqlite3_open(
98232   const char *zFilename, 
98233   sqlite3 **ppDb 
98234 ){
98235   return openDatabase(zFilename, ppDb,
98236                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
98237 }
98238 SQLITE_API int sqlite3_open_v2(
98239   const char *filename,   /* Database filename (UTF-8) */
98240   sqlite3 **ppDb,         /* OUT: SQLite db handle */
98241   int flags,              /* Flags */
98242   const char *zVfs        /* Name of VFS module to use */
98243 ){
98244   return openDatabase(filename, ppDb, flags, zVfs);
98245 }
98246
98247 #ifndef SQLITE_OMIT_UTF16
98248 /*
98249 ** Open a new database handle.
98250 */
98251 SQLITE_API int sqlite3_open16(
98252   const void *zFilename, 
98253   sqlite3 **ppDb
98254 ){
98255   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
98256   sqlite3_value *pVal;
98257   int rc;
98258
98259   assert( zFilename );
98260   assert( ppDb );
98261   *ppDb = 0;
98262 #ifndef SQLITE_OMIT_AUTOINIT
98263   rc = sqlite3_initialize();
98264   if( rc ) return rc;
98265 #endif
98266   pVal = sqlite3ValueNew(0);
98267   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
98268   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
98269   if( zFilename8 ){
98270     rc = openDatabase(zFilename8, ppDb,
98271                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
98272     assert( *ppDb || rc==SQLITE_NOMEM );
98273     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
98274       ENC(*ppDb) = SQLITE_UTF16NATIVE;
98275     }
98276   }else{
98277     rc = SQLITE_NOMEM;
98278   }
98279   sqlite3ValueFree(pVal);
98280
98281   return sqlite3ApiExit(0, rc);
98282 }
98283 #endif /* SQLITE_OMIT_UTF16 */
98284
98285 /*
98286 ** Register a new collation sequence with the database handle db.
98287 */
98288 SQLITE_API int sqlite3_create_collation(
98289   sqlite3* db, 
98290   const char *zName, 
98291   int enc, 
98292   void* pCtx,
98293   int(*xCompare)(void*,int,const void*,int,const void*)
98294 ){
98295   int rc;
98296   sqlite3_mutex_enter(db->mutex);
98297   assert( !db->mallocFailed );
98298   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
98299   rc = sqlite3ApiExit(db, rc);
98300   sqlite3_mutex_leave(db->mutex);
98301   return rc;
98302 }
98303
98304 /*
98305 ** Register a new collation sequence with the database handle db.
98306 */
98307 SQLITE_API int sqlite3_create_collation_v2(
98308   sqlite3* db, 
98309   const char *zName, 
98310   int enc, 
98311   void* pCtx,
98312   int(*xCompare)(void*,int,const void*,int,const void*),
98313   void(*xDel)(void*)
98314 ){
98315   int rc;
98316   sqlite3_mutex_enter(db->mutex);
98317   assert( !db->mallocFailed );
98318   rc = createCollation(db, zName, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, xDel);
98319   rc = sqlite3ApiExit(db, rc);
98320   sqlite3_mutex_leave(db->mutex);
98321   return rc;
98322 }
98323
98324 #ifndef SQLITE_OMIT_UTF16
98325 /*
98326 ** Register a new collation sequence with the database handle db.
98327 */
98328 SQLITE_API int sqlite3_create_collation16(
98329   sqlite3* db, 
98330   const void *zName,
98331   int enc, 
98332   void* pCtx,
98333   int(*xCompare)(void*,int,const void*,int,const void*)
98334 ){
98335   int rc = SQLITE_OK;
98336   char *zName8;
98337   sqlite3_mutex_enter(db->mutex);
98338   assert( !db->mallocFailed );
98339   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
98340   if( zName8 ){
98341     rc = createCollation(db, zName8, (u8)enc, SQLITE_COLL_USER, pCtx, xCompare, 0);
98342     sqlite3DbFree(db, zName8);
98343   }
98344   rc = sqlite3ApiExit(db, rc);
98345   sqlite3_mutex_leave(db->mutex);
98346   return rc;
98347 }
98348 #endif /* SQLITE_OMIT_UTF16 */
98349
98350 /*
98351 ** Register a collation sequence factory callback with the database handle
98352 ** db. Replace any previously installed collation sequence factory.
98353 */
98354 SQLITE_API int sqlite3_collation_needed(
98355   sqlite3 *db, 
98356   void *pCollNeededArg, 
98357   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
98358 ){
98359   sqlite3_mutex_enter(db->mutex);
98360   db->xCollNeeded = xCollNeeded;
98361   db->xCollNeeded16 = 0;
98362   db->pCollNeededArg = pCollNeededArg;
98363   sqlite3_mutex_leave(db->mutex);
98364   return SQLITE_OK;
98365 }
98366
98367 #ifndef SQLITE_OMIT_UTF16
98368 /*
98369 ** Register a collation sequence factory callback with the database handle
98370 ** db. Replace any previously installed collation sequence factory.
98371 */
98372 SQLITE_API int sqlite3_collation_needed16(
98373   sqlite3 *db, 
98374   void *pCollNeededArg, 
98375   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
98376 ){
98377   sqlite3_mutex_enter(db->mutex);
98378   db->xCollNeeded = 0;
98379   db->xCollNeeded16 = xCollNeeded16;
98380   db->pCollNeededArg = pCollNeededArg;
98381   sqlite3_mutex_leave(db->mutex);
98382   return SQLITE_OK;
98383 }
98384 #endif /* SQLITE_OMIT_UTF16 */
98385
98386 #ifndef SQLITE_OMIT_GLOBALRECOVER
98387 #ifndef SQLITE_OMIT_DEPRECATED
98388 /*
98389 ** This function is now an anachronism. It used to be used to recover from a
98390 ** malloc() failure, but SQLite now does this automatically.
98391 */
98392 SQLITE_API int sqlite3_global_recover(void){
98393   return SQLITE_OK;
98394 }
98395 #endif
98396 #endif
98397
98398 /*
98399 ** Test to see whether or not the database connection is in autocommit
98400 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
98401 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
98402 ** by the next COMMIT or ROLLBACK.
98403 **
98404 ******* THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ******
98405 */
98406 SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
98407   return db->autoCommit;
98408 }
98409
98410 /*
98411 ** The following routines are subtitutes for constants SQLITE_CORRUPT,
98412 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
98413 ** constants.  They server two purposes:
98414 **
98415 **   1.  Serve as a convenient place to set a breakpoint in a debugger
98416 **       to detect when version error conditions occurs.
98417 **
98418 **   2.  Invoke sqlite3_log() to provide the source code location where
98419 **       a low-level error is first detected.
98420 */
98421 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
98422   testcase( sqlite3GlobalConfig.xLog!=0 );
98423   sqlite3_log(SQLITE_CORRUPT,
98424               "database corruption found by source line %d", lineno);
98425   return SQLITE_CORRUPT;
98426 }
98427 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
98428   testcase( sqlite3GlobalConfig.xLog!=0 );
98429   sqlite3_log(SQLITE_MISUSE, "misuse detected by source line %d", lineno);
98430   return SQLITE_MISUSE;
98431 }
98432 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
98433   testcase( sqlite3GlobalConfig.xLog!=0 );
98434   sqlite3_log(SQLITE_CANTOPEN, "cannot open file at source line %d", lineno);
98435   return SQLITE_CANTOPEN;
98436 }
98437
98438
98439 #ifndef SQLITE_OMIT_DEPRECATED
98440 /*
98441 ** This is a convenience routine that makes sure that all thread-specific
98442 ** data for this thread has been deallocated.
98443 **
98444 ** SQLite no longer uses thread-specific data so this routine is now a
98445 ** no-op.  It is retained for historical compatibility.
98446 */
98447 SQLITE_API void sqlite3_thread_cleanup(void){
98448 }
98449 #endif
98450
98451 /*
98452 ** Return meta information about a specific column of a database table.
98453 ** See comment in sqlite3.h (sqlite.h.in) for details.
98454 */
98455 #ifdef SQLITE_ENABLE_COLUMN_METADATA
98456 SQLITE_API int sqlite3_table_column_metadata(
98457   sqlite3 *db,                /* Connection handle */
98458   const char *zDbName,        /* Database name or NULL */
98459   const char *zTableName,     /* Table name */
98460   const char *zColumnName,    /* Column name */
98461   char const **pzDataType,    /* OUTPUT: Declared data type */
98462   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
98463   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
98464   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
98465   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
98466 ){
98467   int rc;
98468   char *zErrMsg = 0;
98469   Table *pTab = 0;
98470   Column *pCol = 0;
98471   int iCol;
98472
98473   char const *zDataType = 0;
98474   char const *zCollSeq = 0;
98475   int notnull = 0;
98476   int primarykey = 0;
98477   int autoinc = 0;
98478
98479   /* Ensure the database schema has been loaded */
98480   sqlite3_mutex_enter(db->mutex);
98481   sqlite3BtreeEnterAll(db);
98482   rc = sqlite3Init(db, &zErrMsg);
98483   if( SQLITE_OK!=rc ){
98484     goto error_out;
98485   }
98486
98487   /* Locate the table in question */
98488   pTab = sqlite3FindTable(db, zTableName, zDbName);
98489   if( !pTab || pTab->pSelect ){
98490     pTab = 0;
98491     goto error_out;
98492   }
98493
98494   /* Find the column for which info is requested */
98495   if( sqlite3IsRowid(zColumnName) ){
98496     iCol = pTab->iPKey;
98497     if( iCol>=0 ){
98498       pCol = &pTab->aCol[iCol];
98499     }
98500   }else{
98501     for(iCol=0; iCol<pTab->nCol; iCol++){
98502       pCol = &pTab->aCol[iCol];
98503       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
98504         break;
98505       }
98506     }
98507     if( iCol==pTab->nCol ){
98508       pTab = 0;
98509       goto error_out;
98510     }
98511   }
98512
98513   /* The following block stores the meta information that will be returned
98514   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
98515   ** and autoinc. At this point there are two possibilities:
98516   ** 
98517   **     1. The specified column name was rowid", "oid" or "_rowid_" 
98518   **        and there is no explicitly declared IPK column. 
98519   **
98520   **     2. The table is not a view and the column name identified an 
98521   **        explicitly declared column. Copy meta information from *pCol.
98522   */ 
98523   if( pCol ){
98524     zDataType = pCol->zType;
98525     zCollSeq = pCol->zColl;
98526     notnull = pCol->notNull!=0;
98527     primarykey  = pCol->isPrimKey!=0;
98528     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
98529   }else{
98530     zDataType = "INTEGER";
98531     primarykey = 1;
98532   }
98533   if( !zCollSeq ){
98534     zCollSeq = "BINARY";
98535   }
98536
98537 error_out:
98538   sqlite3BtreeLeaveAll(db);
98539
98540   /* Whether the function call succeeded or failed, set the output parameters
98541   ** to whatever their local counterparts contain. If an error did occur,
98542   ** this has the effect of zeroing all output parameters.
98543   */
98544   if( pzDataType ) *pzDataType = zDataType;
98545   if( pzCollSeq ) *pzCollSeq = zCollSeq;
98546   if( pNotNull ) *pNotNull = notnull;
98547   if( pPrimaryKey ) *pPrimaryKey = primarykey;
98548   if( pAutoinc ) *pAutoinc = autoinc;
98549
98550   if( SQLITE_OK==rc && !pTab ){
98551     sqlite3DbFree(db, zErrMsg);
98552     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
98553         zColumnName);
98554     rc = SQLITE_ERROR;
98555   }
98556   sqlite3Error(db, rc, (zErrMsg?"%s":0), zErrMsg);
98557   sqlite3DbFree(db, zErrMsg);
98558   rc = sqlite3ApiExit(db, rc);
98559   sqlite3_mutex_leave(db->mutex);
98560   return rc;
98561 }
98562 #endif
98563
98564 /*
98565 ** Sleep for a little while.  Return the amount of time slept.
98566 */
98567 SQLITE_API int sqlite3_sleep(int ms){
98568   sqlite3_vfs *pVfs;
98569   int rc;
98570   pVfs = sqlite3_vfs_find(0);
98571   if( pVfs==0 ) return 0;
98572
98573   /* This function works in milliseconds, but the underlying OsSleep() 
98574   ** API uses microseconds. Hence the 1000's.
98575   */
98576   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
98577   return rc;
98578 }
98579
98580 /*
98581 ** Enable or disable the extended result codes.
98582 */
98583 SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
98584   sqlite3_mutex_enter(db->mutex);
98585   db->errMask = onoff ? 0xffffffff : 0xff;
98586   sqlite3_mutex_leave(db->mutex);
98587   return SQLITE_OK;
98588 }
98589
98590 /*
98591 ** Invoke the xFileControl method on a particular database.
98592 */
98593 SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
98594   int rc = SQLITE_ERROR;
98595   int iDb;
98596   sqlite3_mutex_enter(db->mutex);
98597   if( zDbName==0 ){
98598     iDb = 0;
98599   }else{
98600     for(iDb=0; iDb<db->nDb; iDb++){
98601       if( strcmp(db->aDb[iDb].zName, zDbName)==0 ) break;
98602     }
98603   }
98604   if( iDb<db->nDb ){
98605     Btree *pBtree = db->aDb[iDb].pBt;
98606     if( pBtree ){
98607       Pager *pPager;
98608       sqlite3_file *fd;
98609       sqlite3BtreeEnter(pBtree);
98610       pPager = sqlite3BtreePager(pBtree);
98611       assert( pPager!=0 );
98612       fd = sqlite3PagerFile(pPager);
98613       assert( fd!=0 );
98614       if( fd->pMethods ){
98615         rc = sqlite3OsFileControl(fd, op, pArg);
98616       }
98617       sqlite3BtreeLeave(pBtree);
98618     }
98619   }
98620   sqlite3_mutex_leave(db->mutex);
98621   return rc;   
98622 }
98623
98624 /*
98625 ** Interface to the testing logic.
98626 */
98627 SQLITE_API int sqlite3_test_control(int op, ...){
98628   int rc = 0;
98629 #ifndef SQLITE_OMIT_BUILTIN_TEST
98630   va_list ap;
98631   va_start(ap, op);
98632   switch( op ){
98633
98634     /*
98635     ** Save the current state of the PRNG.
98636     */
98637     case SQLITE_TESTCTRL_PRNG_SAVE: {
98638       sqlite3PrngSaveState();
98639       break;
98640     }
98641
98642     /*
98643     ** Restore the state of the PRNG to the last state saved using
98644     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
98645     ** this verb acts like PRNG_RESET.
98646     */
98647     case SQLITE_TESTCTRL_PRNG_RESTORE: {
98648       sqlite3PrngRestoreState();
98649       break;
98650     }
98651
98652     /*
98653     ** Reset the PRNG back to its uninitialized state.  The next call
98654     ** to sqlite3_randomness() will reseed the PRNG using a single call
98655     ** to the xRandomness method of the default VFS.
98656     */
98657     case SQLITE_TESTCTRL_PRNG_RESET: {
98658       sqlite3PrngResetState();
98659       break;
98660     }
98661
98662     /*
98663     **  sqlite3_test_control(BITVEC_TEST, size, program)
98664     **
98665     ** Run a test against a Bitvec object of size.  The program argument
98666     ** is an array of integers that defines the test.  Return -1 on a
98667     ** memory allocation error, 0 on success, or non-zero for an error.
98668     ** See the sqlite3BitvecBuiltinTest() for additional information.
98669     */
98670     case SQLITE_TESTCTRL_BITVEC_TEST: {
98671       int sz = va_arg(ap, int);
98672       int *aProg = va_arg(ap, int*);
98673       rc = sqlite3BitvecBuiltinTest(sz, aProg);
98674       break;
98675     }
98676
98677     /*
98678     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
98679     **
98680     ** Register hooks to call to indicate which malloc() failures 
98681     ** are benign.
98682     */
98683     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
98684       typedef void (*void_function)(void);
98685       void_function xBenignBegin;
98686       void_function xBenignEnd;
98687       xBenignBegin = va_arg(ap, void_function);
98688       xBenignEnd = va_arg(ap, void_function);
98689       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
98690       break;
98691     }
98692
98693     /*
98694     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
98695     **
98696     ** Set the PENDING byte to the value in the argument, if X>0.
98697     ** Make no changes if X==0.  Return the value of the pending byte
98698     ** as it existing before this routine was called.
98699     **
98700     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
98701     ** an incompatible database file format.  Changing the PENDING byte
98702     ** while any database connection is open results in undefined and
98703     ** dileterious behavior.
98704     */
98705     case SQLITE_TESTCTRL_PENDING_BYTE: {
98706       unsigned int newVal = va_arg(ap, unsigned int);
98707       rc = sqlite3PendingByte;
98708       if( newVal ) sqlite3PendingByte = newVal;
98709       break;
98710     }
98711
98712     /*
98713     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
98714     **
98715     ** This action provides a run-time test to see whether or not
98716     ** assert() was enabled at compile-time.  If X is true and assert()
98717     ** is enabled, then the return value is true.  If X is true and
98718     ** assert() is disabled, then the return value is zero.  If X is
98719     ** false and assert() is enabled, then the assertion fires and the
98720     ** process aborts.  If X is false and assert() is disabled, then the
98721     ** return value is zero.
98722     */
98723     case SQLITE_TESTCTRL_ASSERT: {
98724       volatile int x = 0;
98725       assert( (x = va_arg(ap,int))!=0 );
98726       rc = x;
98727       break;
98728     }
98729
98730
98731     /*
98732     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
98733     **
98734     ** This action provides a run-time test to see how the ALWAYS and
98735     ** NEVER macros were defined at compile-time.
98736     **
98737     ** The return value is ALWAYS(X).  
98738     **
98739     ** The recommended test is X==2.  If the return value is 2, that means
98740     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
98741     ** default setting.  If the return value is 1, then ALWAYS() is either
98742     ** hard-coded to true or else it asserts if its argument is false.
98743     ** The first behavior (hard-coded to true) is the case if
98744     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
98745     ** behavior (assert if the argument to ALWAYS() is false) is the case if
98746     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
98747     **
98748     ** The run-time test procedure might look something like this:
98749     **
98750     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
98751     **      // ALWAYS() and NEVER() are no-op pass-through macros
98752     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
98753     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
98754     **    }else{
98755     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
98756     **    }
98757     */
98758     case SQLITE_TESTCTRL_ALWAYS: {
98759       int x = va_arg(ap,int);
98760       rc = ALWAYS(x);
98761       break;
98762     }
98763
98764     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
98765     **
98766     ** Set the nReserve size to N for the main database on the database
98767     ** connection db.
98768     */
98769     case SQLITE_TESTCTRL_RESERVE: {
98770       sqlite3 *db = va_arg(ap, sqlite3*);
98771       int x = va_arg(ap,int);
98772       sqlite3_mutex_enter(db->mutex);
98773       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
98774       sqlite3_mutex_leave(db->mutex);
98775       break;
98776     }
98777
98778     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
98779     **
98780     ** Enable or disable various optimizations for testing purposes.  The 
98781     ** argument N is a bitmask of optimizations to be disabled.  For normal
98782     ** operation N should be 0.  The idea is that a test program (like the
98783     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
98784     ** with various optimizations disabled to verify that the same answer
98785     ** is obtained in every case.
98786     */
98787     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
98788       sqlite3 *db = va_arg(ap, sqlite3*);
98789       int x = va_arg(ap,int);
98790       db->flags = (x & SQLITE_OptMask) | (db->flags & ~SQLITE_OptMask);
98791       break;
98792     }
98793
98794 #ifdef SQLITE_N_KEYWORD
98795     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
98796     **
98797     ** If zWord is a keyword recognized by the parser, then return the
98798     ** number of keywords.  Or if zWord is not a keyword, return 0.
98799     ** 
98800     ** This test feature is only available in the amalgamation since
98801     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
98802     ** is built using separate source files.
98803     */
98804     case SQLITE_TESTCTRL_ISKEYWORD: {
98805       const char *zWord = va_arg(ap, const char*);
98806       int n = sqlite3Strlen30(zWord);
98807       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
98808       break;
98809     }
98810 #endif 
98811
98812   }
98813   va_end(ap);
98814 #endif /* SQLITE_OMIT_BUILTIN_TEST */
98815   return rc;
98816 }
98817
98818 /************** End of main.c ************************************************/
98819 /************** Begin file notify.c ******************************************/
98820 /*
98821 ** 2009 March 3
98822 **
98823 ** The author disclaims copyright to this source code.  In place of
98824 ** a legal notice, here is a blessing:
98825 **
98826 **    May you do good and not evil.
98827 **    May you find forgiveness for yourself and forgive others.
98828 **    May you share freely, never taking more than you give.
98829 **
98830 *************************************************************************
98831 **
98832 ** This file contains the implementation of the sqlite3_unlock_notify()
98833 ** API method and its associated functionality.
98834 */
98835
98836 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
98837 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
98838
98839 /*
98840 ** Public interfaces:
98841 **
98842 **   sqlite3ConnectionBlocked()
98843 **   sqlite3ConnectionUnlocked()
98844 **   sqlite3ConnectionClosed()
98845 **   sqlite3_unlock_notify()
98846 */
98847
98848 #define assertMutexHeld() \
98849   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
98850
98851 /*
98852 ** Head of a linked list of all sqlite3 objects created by this process
98853 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
98854 ** is not NULL. This variable may only accessed while the STATIC_MASTER
98855 ** mutex is held.
98856 */
98857 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
98858
98859 #ifndef NDEBUG
98860 /*
98861 ** This function is a complex assert() that verifies the following 
98862 ** properties of the blocked connections list:
98863 **
98864 **   1) Each entry in the list has a non-NULL value for either 
98865 **      pUnlockConnection or pBlockingConnection, or both.
98866 **
98867 **   2) All entries in the list that share a common value for 
98868 **      xUnlockNotify are grouped together.
98869 **
98870 **   3) If the argument db is not NULL, then none of the entries in the
98871 **      blocked connections list have pUnlockConnection or pBlockingConnection
98872 **      set to db. This is used when closing connection db.
98873 */
98874 static void checkListProperties(sqlite3 *db){
98875   sqlite3 *p;
98876   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
98877     int seen = 0;
98878     sqlite3 *p2;
98879
98880     /* Verify property (1) */
98881     assert( p->pUnlockConnection || p->pBlockingConnection );
98882
98883     /* Verify property (2) */
98884     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
98885       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
98886       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
98887       assert( db==0 || p->pUnlockConnection!=db );
98888       assert( db==0 || p->pBlockingConnection!=db );
98889     }
98890   }
98891 }
98892 #else
98893 # define checkListProperties(x)
98894 #endif
98895
98896 /*
98897 ** Remove connection db from the blocked connections list. If connection
98898 ** db is not currently a part of the list, this function is a no-op.
98899 */
98900 static void removeFromBlockedList(sqlite3 *db){
98901   sqlite3 **pp;
98902   assertMutexHeld();
98903   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
98904     if( *pp==db ){
98905       *pp = (*pp)->pNextBlocked;
98906       break;
98907     }
98908   }
98909 }
98910
98911 /*
98912 ** Add connection db to the blocked connections list. It is assumed
98913 ** that it is not already a part of the list.
98914 */
98915 static void addToBlockedList(sqlite3 *db){
98916   sqlite3 **pp;
98917   assertMutexHeld();
98918   for(
98919     pp=&sqlite3BlockedList; 
98920     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
98921     pp=&(*pp)->pNextBlocked
98922   );
98923   db->pNextBlocked = *pp;
98924   *pp = db;
98925 }
98926
98927 /*
98928 ** Obtain the STATIC_MASTER mutex.
98929 */
98930 static void enterMutex(void){
98931   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
98932   checkListProperties(0);
98933 }
98934
98935 /*
98936 ** Release the STATIC_MASTER mutex.
98937 */
98938 static void leaveMutex(void){
98939   assertMutexHeld();
98940   checkListProperties(0);
98941   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
98942 }
98943
98944 /*
98945 ** Register an unlock-notify callback.
98946 **
98947 ** This is called after connection "db" has attempted some operation
98948 ** but has received an SQLITE_LOCKED error because another connection
98949 ** (call it pOther) in the same process was busy using the same shared
98950 ** cache.  pOther is found by looking at db->pBlockingConnection.
98951 **
98952 ** If there is no blocking connection, the callback is invoked immediately,
98953 ** before this routine returns.
98954 **
98955 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
98956 ** a deadlock.
98957 **
98958 ** Otherwise, make arrangements to invoke xNotify when pOther drops
98959 ** its locks.
98960 **
98961 ** Each call to this routine overrides any prior callbacks registered
98962 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
98963 ** cancelled.
98964 */
98965 SQLITE_API int sqlite3_unlock_notify(
98966   sqlite3 *db,
98967   void (*xNotify)(void **, int),
98968   void *pArg
98969 ){
98970   int rc = SQLITE_OK;
98971
98972   sqlite3_mutex_enter(db->mutex);
98973   enterMutex();
98974
98975   if( xNotify==0 ){
98976     removeFromBlockedList(db);
98977     db->pUnlockConnection = 0;
98978     db->xUnlockNotify = 0;
98979     db->pUnlockArg = 0;
98980   }else if( 0==db->pBlockingConnection ){
98981     /* The blocking transaction has been concluded. Or there never was a 
98982     ** blocking transaction. In either case, invoke the notify callback
98983     ** immediately. 
98984     */
98985     xNotify(&pArg, 1);
98986   }else{
98987     sqlite3 *p;
98988
98989     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
98990     if( p ){
98991       rc = SQLITE_LOCKED;              /* Deadlock detected. */
98992     }else{
98993       db->pUnlockConnection = db->pBlockingConnection;
98994       db->xUnlockNotify = xNotify;
98995       db->pUnlockArg = pArg;
98996       removeFromBlockedList(db);
98997       addToBlockedList(db);
98998     }
98999   }
99000
99001   leaveMutex();
99002   assert( !db->mallocFailed );
99003   sqlite3Error(db, rc, (rc?"database is deadlocked":0));
99004   sqlite3_mutex_leave(db->mutex);
99005   return rc;
99006 }
99007
99008 /*
99009 ** This function is called while stepping or preparing a statement 
99010 ** associated with connection db. The operation will return SQLITE_LOCKED
99011 ** to the user because it requires a lock that will not be available
99012 ** until connection pBlocker concludes its current transaction.
99013 */
99014 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
99015   enterMutex();
99016   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
99017     addToBlockedList(db);
99018   }
99019   db->pBlockingConnection = pBlocker;
99020   leaveMutex();
99021 }
99022
99023 /*
99024 ** This function is called when
99025 ** the transaction opened by database db has just finished. Locks held 
99026 ** by database connection db have been released.
99027 **
99028 ** This function loops through each entry in the blocked connections
99029 ** list and does the following:
99030 **
99031 **   1) If the sqlite3.pBlockingConnection member of a list entry is
99032 **      set to db, then set pBlockingConnection=0.
99033 **
99034 **   2) If the sqlite3.pUnlockConnection member of a list entry is
99035 **      set to db, then invoke the configured unlock-notify callback and
99036 **      set pUnlockConnection=0.
99037 **
99038 **   3) If the two steps above mean that pBlockingConnection==0 and
99039 **      pUnlockConnection==0, remove the entry from the blocked connections
99040 **      list.
99041 */
99042 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
99043   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
99044   int nArg = 0;                            /* Number of entries in aArg[] */
99045   sqlite3 **pp;                            /* Iterator variable */
99046   void **aArg;               /* Arguments to the unlock callback */
99047   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
99048   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
99049
99050   aArg = aStatic;
99051   enterMutex();         /* Enter STATIC_MASTER mutex */
99052
99053   /* This loop runs once for each entry in the blocked-connections list. */
99054   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
99055     sqlite3 *p = *pp;
99056
99057     /* Step 1. */
99058     if( p->pBlockingConnection==db ){
99059       p->pBlockingConnection = 0;
99060     }
99061
99062     /* Step 2. */
99063     if( p->pUnlockConnection==db ){
99064       assert( p->xUnlockNotify );
99065       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
99066         xUnlockNotify(aArg, nArg);
99067         nArg = 0;
99068       }
99069
99070       sqlite3BeginBenignMalloc();
99071       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
99072       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
99073       if( (!aDyn && nArg==(int)ArraySize(aStatic))
99074        || (aDyn && nArg==(int)(sqlite3DbMallocSize(db, aDyn)/sizeof(void*)))
99075       ){
99076         /* The aArg[] array needs to grow. */
99077         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
99078         if( pNew ){
99079           memcpy(pNew, aArg, nArg*sizeof(void *));
99080           sqlite3_free(aDyn);
99081           aDyn = aArg = pNew;
99082         }else{
99083           /* This occurs when the array of context pointers that need to
99084           ** be passed to the unlock-notify callback is larger than the
99085           ** aStatic[] array allocated on the stack and the attempt to 
99086           ** allocate a larger array from the heap has failed.
99087           **
99088           ** This is a difficult situation to handle. Returning an error
99089           ** code to the caller is insufficient, as even if an error code
99090           ** is returned the transaction on connection db will still be
99091           ** closed and the unlock-notify callbacks on blocked connections
99092           ** will go unissued. This might cause the application to wait
99093           ** indefinitely for an unlock-notify callback that will never 
99094           ** arrive.
99095           **
99096           ** Instead, invoke the unlock-notify callback with the context
99097           ** array already accumulated. We can then clear the array and
99098           ** begin accumulating any further context pointers without 
99099           ** requiring any dynamic allocation. This is sub-optimal because
99100           ** it means that instead of one callback with a large array of
99101           ** context pointers the application will receive two or more
99102           ** callbacks with smaller arrays of context pointers, which will
99103           ** reduce the applications ability to prioritize multiple 
99104           ** connections. But it is the best that can be done under the
99105           ** circumstances.
99106           */
99107           xUnlockNotify(aArg, nArg);
99108           nArg = 0;
99109         }
99110       }
99111       sqlite3EndBenignMalloc();
99112
99113       aArg[nArg++] = p->pUnlockArg;
99114       xUnlockNotify = p->xUnlockNotify;
99115       p->pUnlockConnection = 0;
99116       p->xUnlockNotify = 0;
99117       p->pUnlockArg = 0;
99118     }
99119
99120     /* Step 3. */
99121     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
99122       /* Remove connection p from the blocked connections list. */
99123       *pp = p->pNextBlocked;
99124       p->pNextBlocked = 0;
99125     }else{
99126       pp = &p->pNextBlocked;
99127     }
99128   }
99129
99130   if( nArg!=0 ){
99131     xUnlockNotify(aArg, nArg);
99132   }
99133   sqlite3_free(aDyn);
99134   leaveMutex();         /* Leave STATIC_MASTER mutex */
99135 }
99136
99137 /*
99138 ** This is called when the database connection passed as an argument is 
99139 ** being closed. The connection is removed from the blocked list.
99140 */
99141 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
99142   sqlite3ConnectionUnlocked(db);
99143   enterMutex();
99144   removeFromBlockedList(db);
99145   checkListProperties(db);
99146   leaveMutex();
99147 }
99148 #endif
99149
99150 /************** End of notify.c **********************************************/
99151 /************** Begin file fts3.c ********************************************/
99152 /*
99153 ** 2006 Oct 10
99154 **
99155 ** The author disclaims copyright to this source code.  In place of
99156 ** a legal notice, here is a blessing:
99157 **
99158 **    May you do good and not evil.
99159 **    May you find forgiveness for yourself and forgive others.
99160 **    May you share freely, never taking more than you give.
99161 **
99162 ******************************************************************************
99163 **
99164 ** This is an SQLite module implementing full-text search.
99165 */
99166
99167 /*
99168 ** The code in this file is only compiled if:
99169 **
99170 **     * The FTS3 module is being built as an extension
99171 **       (in which case SQLITE_CORE is not defined), or
99172 **
99173 **     * The FTS3 module is being built into the core of
99174 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
99175 */
99176
99177 /* The full-text index is stored in a series of b+tree (-like)
99178 ** structures called segments which map terms to doclists.  The
99179 ** structures are like b+trees in layout, but are constructed from the
99180 ** bottom up in optimal fashion and are not updatable.  Since trees
99181 ** are built from the bottom up, things will be described from the
99182 ** bottom up.
99183 **
99184 **
99185 **** Varints ****
99186 ** The basic unit of encoding is a variable-length integer called a
99187 ** varint.  We encode variable-length integers in little-endian order
99188 ** using seven bits * per byte as follows:
99189 **
99190 ** KEY:
99191 **         A = 0xxxxxxx    7 bits of data and one flag bit
99192 **         B = 1xxxxxxx    7 bits of data and one flag bit
99193 **
99194 **  7 bits - A
99195 ** 14 bits - BA
99196 ** 21 bits - BBA
99197 ** and so on.
99198 **
99199 ** This is similar in concept to how sqlite encodes "varints" but
99200 ** the encoding is not the same.  SQLite varints are big-endian
99201 ** are are limited to 9 bytes in length whereas FTS3 varints are
99202 ** little-endian and can be upt to 10 bytes in length (in theory).
99203 **
99204 ** Example encodings:
99205 **
99206 **     1:    0x01
99207 **   127:    0x7f
99208 **   128:    0x81 0x00
99209 **
99210 **
99211 **** Document lists ****
99212 ** A doclist (document list) holds a docid-sorted list of hits for a
99213 ** given term.  Doclists hold docids, and can optionally associate
99214 ** token positions and offsets with docids.  A position is the index
99215 ** of a word within the document.  The first word of the document has
99216 ** a position of 0.
99217 **
99218 ** FTS3 used to optionally store character offsets using a compile-time
99219 ** option.  But that functionality is no longer supported.
99220 **
99221 ** A DL_POSITIONS_OFFSETS doclist is stored like this:
99222 **
99223 ** array {
99224 **   varint docid;
99225 **   array {                (position list for column 0)
99226 **     varint position;     (delta from previous position plus POS_BASE)
99227 **   }
99228 **   array {
99229 **     varint POS_COLUMN;   (marks start of position list for new column)
99230 **     varint column;       (index of new column)
99231 **     array {
99232 **       varint position;   (delta from previous position plus POS_BASE)
99233 **     }
99234 **   }
99235 **   varint POS_END;        (marks end of positions for this document.
99236 ** }
99237 **
99238 ** Here, array { X } means zero or more occurrences of X, adjacent in
99239 ** memory.  A "position" is an index of a token in the token stream
99240 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 
99241 ** in the same logical place as the position element, and act as sentinals
99242 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
99243 ** The positions numbers are not stored literally but rather as two more
99244 ** the difference from the prior position, or the just the position plus
99245 ** 2 for the first position.  Example:
99246 **
99247 **   label:       A B C D E  F  G H   I  J K
99248 **   value:     123 5 9 1 1 14 35 0 234 72 0
99249 **
99250 ** The 123 value is the first docid.  For column zero in this document
99251 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
99252 ** at D signals the start of a new column; the 1 at E indicates that the
99253 ** new column is column number 1.  There are two positions at 12 and 45
99254 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
99255 ** 234 at I is the next docid.  It has one position 72 (72-2) and then
99256 ** terminates with the 0 at K.
99257 **
99258 ** A DL_POSITIONS doclist omits the startOffset and endOffset
99259 ** information.  A DL_DOCIDS doclist omits both the position and
99260 ** offset information, becoming an array of varint-encoded docids.
99261 **
99262 ** On-disk data is stored as type DL_DEFAULT, so we don't serialize
99263 ** the type.  Due to how deletion is implemented in the segmentation
99264 ** system, on-disk doclists MUST store at least positions.
99265 **
99266 **
99267 **** Segment leaf nodes ****
99268 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
99269 ** nodes are written using LeafWriter, and read using LeafReader (to
99270 ** iterate through a single leaf node's data) and LeavesReader (to
99271 ** iterate through a segment's entire leaf layer).  Leaf nodes have
99272 ** the format:
99273 **
99274 ** varint iHeight;             (height from leaf level, always 0)
99275 ** varint nTerm;               (length of first term)
99276 ** char pTerm[nTerm];          (content of first term)
99277 ** varint nDoclist;            (length of term's associated doclist)
99278 ** char pDoclist[nDoclist];    (content of doclist)
99279 ** array {
99280 **                             (further terms are delta-encoded)
99281 **   varint nPrefix;           (length of prefix shared with previous term)
99282 **   varint nSuffix;           (length of unshared suffix)
99283 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
99284 **   varint nDoclist;          (length of term's associated doclist)
99285 **   char pDoclist[nDoclist];  (content of doclist)
99286 ** }
99287 **
99288 ** Here, array { X } means zero or more occurrences of X, adjacent in
99289 ** memory.
99290 **
99291 ** Leaf nodes are broken into blocks which are stored contiguously in
99292 ** the %_segments table in sorted order.  This means that when the end
99293 ** of a node is reached, the next term is in the node with the next
99294 ** greater node id.
99295 **
99296 ** New data is spilled to a new leaf node when the current node
99297 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
99298 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
99299 ** node (a leaf node with a single term and doclist).  The goal of
99300 ** these settings is to pack together groups of small doclists while
99301 ** making it efficient to directly access large doclists.  The
99302 ** assumption is that large doclists represent terms which are more
99303 ** likely to be query targets.
99304 **
99305 ** TODO(shess) It may be useful for blocking decisions to be more
99306 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
99307 ** node rather than splitting into 2k and .5k nodes.  My intuition is
99308 ** that this might extend through 2x or 4x the pagesize.
99309 **
99310 **
99311 **** Segment interior nodes ****
99312 ** Segment interior nodes store blockids for subtree nodes and terms
99313 ** to describe what data is stored by the each subtree.  Interior
99314 ** nodes are written using InteriorWriter, and read using
99315 ** InteriorReader.  InteriorWriters are created as needed when
99316 ** SegmentWriter creates new leaf nodes, or when an interior node
99317 ** itself grows too big and must be split.  The format of interior
99318 ** nodes:
99319 **
99320 ** varint iHeight;           (height from leaf level, always >0)
99321 ** varint iBlockid;          (block id of node's leftmost subtree)
99322 ** optional {
99323 **   varint nTerm;           (length of first term)
99324 **   char pTerm[nTerm];      (content of first term)
99325 **   array {
99326 **                                (further terms are delta-encoded)
99327 **     varint nPrefix;            (length of shared prefix with previous term)
99328 **     varint nSuffix;            (length of unshared suffix)
99329 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
99330 **   }
99331 ** }
99332 **
99333 ** Here, optional { X } means an optional element, while array { X }
99334 ** means zero or more occurrences of X, adjacent in memory.
99335 **
99336 ** An interior node encodes n terms separating n+1 subtrees.  The
99337 ** subtree blocks are contiguous, so only the first subtree's blockid
99338 ** is encoded.  The subtree at iBlockid will contain all terms less
99339 ** than the first term encoded (or all terms if no term is encoded).
99340 ** Otherwise, for terms greater than or equal to pTerm[i] but less
99341 ** than pTerm[i+1], the subtree for that term will be rooted at
99342 ** iBlockid+i.  Interior nodes only store enough term data to
99343 ** distinguish adjacent children (if the rightmost term of the left
99344 ** child is "something", and the leftmost term of the right child is
99345 ** "wicked", only "w" is stored).
99346 **
99347 ** New data is spilled to a new interior node at the same height when
99348 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
99349 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
99350 ** interior nodes and making the tree too skinny.  The interior nodes
99351 ** at a given height are naturally tracked by interior nodes at
99352 ** height+1, and so on.
99353 **
99354 **
99355 **** Segment directory ****
99356 ** The segment directory in table %_segdir stores meta-information for
99357 ** merging and deleting segments, and also the root node of the
99358 ** segment's tree.
99359 **
99360 ** The root node is the top node of the segment's tree after encoding
99361 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
99362 ** This could be either a leaf node or an interior node.  If the top
99363 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
99364 ** and a new root interior node is generated (which should always fit
99365 ** within ROOT_MAX because it only needs space for 2 varints, the
99366 ** height and the blockid of the previous root).
99367 **
99368 ** The meta-information in the segment directory is:
99369 **   level               - segment level (see below)
99370 **   idx                 - index within level
99371 **                       - (level,idx uniquely identify a segment)
99372 **   start_block         - first leaf node
99373 **   leaves_end_block    - last leaf node
99374 **   end_block           - last block (including interior nodes)
99375 **   root                - contents of root node
99376 **
99377 ** If the root node is a leaf node, then start_block,
99378 ** leaves_end_block, and end_block are all 0.
99379 **
99380 **
99381 **** Segment merging ****
99382 ** To amortize update costs, segments are grouped into levels and
99383 ** merged in batches.  Each increase in level represents exponentially
99384 ** more documents.
99385 **
99386 ** New documents (actually, document updates) are tokenized and
99387 ** written individually (using LeafWriter) to a level 0 segment, with
99388 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
99389 ** level 0 segments are merged into a single level 1 segment.  Level 1
99390 ** is populated like level 0, and eventually MERGE_COUNT level 1
99391 ** segments are merged to a single level 2 segment (representing
99392 ** MERGE_COUNT^2 updates), and so on.
99393 **
99394 ** A segment merge traverses all segments at a given level in
99395 ** parallel, performing a straightforward sorted merge.  Since segment
99396 ** leaf nodes are written in to the %_segments table in order, this
99397 ** merge traverses the underlying sqlite disk structures efficiently.
99398 ** After the merge, all segment blocks from the merged level are
99399 ** deleted.
99400 **
99401 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
99402 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
99403 ** very similar performance numbers to 16 on insertion, though they're
99404 ** a tiny bit slower (perhaps due to more overhead in merge-time
99405 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
99406 ** 16, 2 about 66% slower than 16.
99407 **
99408 ** At query time, high MERGE_COUNT increases the number of segments
99409 ** which need to be scanned and merged.  For instance, with 100k docs
99410 ** inserted:
99411 **
99412 **    MERGE_COUNT   segments
99413 **       16           25
99414 **        8           12
99415 **        4           10
99416 **        2            6
99417 **
99418 ** This appears to have only a moderate impact on queries for very
99419 ** frequent terms (which are somewhat dominated by segment merge
99420 ** costs), and infrequent and non-existent terms still seem to be fast
99421 ** even with many segments.
99422 **
99423 ** TODO(shess) That said, it would be nice to have a better query-side
99424 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
99425 ** optimizations to things like doclist merging will swing the sweet
99426 ** spot around.
99427 **
99428 **
99429 **
99430 **** Handling of deletions and updates ****
99431 ** Since we're using a segmented structure, with no docid-oriented
99432 ** index into the term index, we clearly cannot simply update the term
99433 ** index when a document is deleted or updated.  For deletions, we
99434 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
99435 ** we simply write the new doclist.  Segment merges overwrite older
99436 ** data for a particular docid with newer data, so deletes or updates
99437 ** will eventually overtake the earlier data and knock it out.  The
99438 ** query logic likewise merges doclists so that newer data knocks out
99439 ** older data.
99440 **
99441 ** TODO(shess) Provide a VACUUM type operation to clear out all
99442 ** deletions and duplications.  This would basically be a forced merge
99443 ** into a single segment.
99444 */
99445
99446 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
99447
99448 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
99449 # define SQLITE_CORE 1
99450 #endif
99451
99452 /************** Include fts3Int.h in the middle of fts3.c ********************/
99453 /************** Begin file fts3Int.h *****************************************/
99454 /*
99455 ** 2009 Nov 12
99456 **
99457 ** The author disclaims copyright to this source code.  In place of
99458 ** a legal notice, here is a blessing:
99459 **
99460 **    May you do good and not evil.
99461 **    May you find forgiveness for yourself and forgive others.
99462 **    May you share freely, never taking more than you give.
99463 **
99464 ******************************************************************************
99465 **
99466 */
99467
99468 #ifndef _FTSINT_H
99469 #define _FTSINT_H
99470
99471 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
99472 # define NDEBUG 1
99473 #endif
99474
99475 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
99476 /************** Begin file fts3_tokenizer.h **********************************/
99477 /*
99478 ** 2006 July 10
99479 **
99480 ** The author disclaims copyright to this source code.
99481 **
99482 *************************************************************************
99483 ** Defines the interface to tokenizers used by fulltext-search.  There
99484 ** are three basic components:
99485 **
99486 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
99487 ** interface functions.  This is essentially the class structure for
99488 ** tokenizers.
99489 **
99490 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
99491 ** including customization information defined at creation time.
99492 **
99493 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
99494 ** tokens from a particular input.
99495 */
99496 #ifndef _FTS3_TOKENIZER_H_
99497 #define _FTS3_TOKENIZER_H_
99498
99499 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
99500 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
99501 ** we will need a way to register the API consistently.
99502 */
99503
99504 /*
99505 ** Structures used by the tokenizer interface. When a new tokenizer
99506 ** implementation is registered, the caller provides a pointer to
99507 ** an sqlite3_tokenizer_module containing pointers to the callback
99508 ** functions that make up an implementation.
99509 **
99510 ** When an fts3 table is created, it passes any arguments passed to
99511 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
99512 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
99513 ** implementation. The xCreate() function in turn returns an 
99514 ** sqlite3_tokenizer structure representing the specific tokenizer to
99515 ** be used for the fts3 table (customized by the tokenizer clause arguments).
99516 **
99517 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
99518 ** method is called. It returns an sqlite3_tokenizer_cursor object
99519 ** that may be used to tokenize a specific input buffer based on
99520 ** the tokenization rules supplied by a specific sqlite3_tokenizer
99521 ** object.
99522 */
99523 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
99524 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
99525 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
99526
99527 struct sqlite3_tokenizer_module {
99528
99529   /*
99530   ** Structure version. Should always be set to 0.
99531   */
99532   int iVersion;
99533
99534   /*
99535   ** Create a new tokenizer. The values in the argv[] array are the
99536   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
99537   ** TABLE statement that created the fts3 table. For example, if
99538   ** the following SQL is executed:
99539   **
99540   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
99541   **
99542   ** then argc is set to 2, and the argv[] array contains pointers
99543   ** to the strings "arg1" and "arg2".
99544   **
99545   ** This method should return either SQLITE_OK (0), or an SQLite error 
99546   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
99547   ** to point at the newly created tokenizer structure. The generic
99548   ** sqlite3_tokenizer.pModule variable should not be initialised by
99549   ** this callback. The caller will do so.
99550   */
99551   int (*xCreate)(
99552     int argc,                           /* Size of argv array */
99553     const char *const*argv,             /* Tokenizer argument strings */
99554     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
99555   );
99556
99557   /*
99558   ** Destroy an existing tokenizer. The fts3 module calls this method
99559   ** exactly once for each successful call to xCreate().
99560   */
99561   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
99562
99563   /*
99564   ** Create a tokenizer cursor to tokenize an input buffer. The caller
99565   ** is responsible for ensuring that the input buffer remains valid
99566   ** until the cursor is closed (using the xClose() method). 
99567   */
99568   int (*xOpen)(
99569     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
99570     const char *pInput, int nBytes,      /* Input buffer */
99571     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
99572   );
99573
99574   /*
99575   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
99576   ** method exactly once for each successful call to xOpen().
99577   */
99578   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
99579
99580   /*
99581   ** Retrieve the next token from the tokenizer cursor pCursor. This
99582   ** method should either return SQLITE_OK and set the values of the
99583   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
99584   ** the end of the buffer has been reached, or an SQLite error code.
99585   **
99586   ** *ppToken should be set to point at a buffer containing the 
99587   ** normalized version of the token (i.e. after any case-folding and/or
99588   ** stemming has been performed). *pnBytes should be set to the length
99589   ** of this buffer in bytes. The input text that generated the token is
99590   ** identified by the byte offsets returned in *piStartOffset and
99591   ** *piEndOffset. *piStartOffset should be set to the index of the first
99592   ** byte of the token in the input buffer. *piEndOffset should be set
99593   ** to the index of the first byte just past the end of the token in
99594   ** the input buffer.
99595   **
99596   ** The buffer *ppToken is set to point at is managed by the tokenizer
99597   ** implementation. It is only required to be valid until the next call
99598   ** to xNext() or xClose(). 
99599   */
99600   /* TODO(shess) current implementation requires pInput to be
99601   ** nul-terminated.  This should either be fixed, or pInput/nBytes
99602   ** should be converted to zInput.
99603   */
99604   int (*xNext)(
99605     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
99606     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
99607     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
99608     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
99609     int *piPosition      /* OUT: Number of tokens returned before this one */
99610   );
99611 };
99612
99613 struct sqlite3_tokenizer {
99614   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
99615   /* Tokenizer implementations will typically add additional fields */
99616 };
99617
99618 struct sqlite3_tokenizer_cursor {
99619   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
99620   /* Tokenizer implementations will typically add additional fields */
99621 };
99622
99623 int fts3_global_term_cnt(int iTerm, int iCol);
99624 int fts3_term_cnt(int iTerm, int iCol);
99625
99626
99627 #endif /* _FTS3_TOKENIZER_H_ */
99628
99629 /************** End of fts3_tokenizer.h **************************************/
99630 /************** Continuing where we left off in fts3Int.h ********************/
99631 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
99632 /************** Begin file fts3_hash.h ***************************************/
99633 /*
99634 ** 2001 September 22
99635 **
99636 ** The author disclaims copyright to this source code.  In place of
99637 ** a legal notice, here is a blessing:
99638 **
99639 **    May you do good and not evil.
99640 **    May you find forgiveness for yourself and forgive others.
99641 **    May you share freely, never taking more than you give.
99642 **
99643 *************************************************************************
99644 ** This is the header file for the generic hash-table implemenation
99645 ** used in SQLite.  We've modified it slightly to serve as a standalone
99646 ** hash table implementation for the full-text indexing module.
99647 **
99648 */
99649 #ifndef _FTS3_HASH_H_
99650 #define _FTS3_HASH_H_
99651
99652 /* Forward declarations of structures. */
99653 typedef struct Fts3Hash Fts3Hash;
99654 typedef struct Fts3HashElem Fts3HashElem;
99655
99656 /* A complete hash table is an instance of the following structure.
99657 ** The internals of this structure are intended to be opaque -- client
99658 ** code should not attempt to access or modify the fields of this structure
99659 ** directly.  Change this structure only by using the routines below.
99660 ** However, many of the "procedures" and "functions" for modifying and
99661 ** accessing this structure are really macros, so we can't really make
99662 ** this structure opaque.
99663 */
99664 struct Fts3Hash {
99665   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
99666   char copyKey;           /* True if copy of key made on insert */
99667   int count;              /* Number of entries in this table */
99668   Fts3HashElem *first;    /* The first element of the array */
99669   int htsize;             /* Number of buckets in the hash table */
99670   struct _fts3ht {        /* the hash table */
99671     int count;               /* Number of entries with this hash */
99672     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
99673   } *ht;
99674 };
99675
99676 /* Each element in the hash table is an instance of the following 
99677 ** structure.  All elements are stored on a single doubly-linked list.
99678 **
99679 ** Again, this structure is intended to be opaque, but it can't really
99680 ** be opaque because it is used by macros.
99681 */
99682 struct Fts3HashElem {
99683   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
99684   void *data;                /* Data associated with this element */
99685   void *pKey; int nKey;      /* Key associated with this element */
99686 };
99687
99688 /*
99689 ** There are 2 different modes of operation for a hash table:
99690 **
99691 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
99692 **                           (including the null-terminator, if any).  Case
99693 **                           is respected in comparisons.
99694 **
99695 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
99696 **                           memcmp() is used to compare keys.
99697 **
99698 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
99699 */
99700 #define FTS3_HASH_STRING    1
99701 #define FTS3_HASH_BINARY    2
99702
99703 /*
99704 ** Access routines.  To delete, insert a NULL pointer.
99705 */
99706 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
99707 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
99708 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
99709 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
99710 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
99711
99712 /*
99713 ** Shorthand for the functions above
99714 */
99715 #define fts3HashInit     sqlite3Fts3HashInit
99716 #define fts3HashInsert   sqlite3Fts3HashInsert
99717 #define fts3HashFind     sqlite3Fts3HashFind
99718 #define fts3HashClear    sqlite3Fts3HashClear
99719 #define fts3HashFindElem sqlite3Fts3HashFindElem
99720
99721 /*
99722 ** Macros for looping over all elements of a hash table.  The idiom is
99723 ** like this:
99724 **
99725 **   Fts3Hash h;
99726 **   Fts3HashElem *p;
99727 **   ...
99728 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
99729 **     SomeStructure *pData = fts3HashData(p);
99730 **     // do something with pData
99731 **   }
99732 */
99733 #define fts3HashFirst(H)  ((H)->first)
99734 #define fts3HashNext(E)   ((E)->next)
99735 #define fts3HashData(E)   ((E)->data)
99736 #define fts3HashKey(E)    ((E)->pKey)
99737 #define fts3HashKeysize(E) ((E)->nKey)
99738
99739 /*
99740 ** Number of entries in a hash table
99741 */
99742 #define fts3HashCount(H)  ((H)->count)
99743
99744 #endif /* _FTS3_HASH_H_ */
99745
99746 /************** End of fts3_hash.h *******************************************/
99747 /************** Continuing where we left off in fts3Int.h ********************/
99748
99749 /*
99750 ** This constant controls how often segments are merged. Once there are
99751 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
99752 ** segment of level N+1.
99753 */
99754 #define FTS3_MERGE_COUNT 16
99755
99756 /*
99757 ** This is the maximum amount of data (in bytes) to store in the 
99758 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
99759 ** populated as documents are inserted/updated/deleted in a transaction
99760 ** and used to create a new segment when the transaction is committed.
99761 ** However if this limit is reached midway through a transaction, a new 
99762 ** segment is created and the hash table cleared immediately.
99763 */
99764 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
99765
99766 /*
99767 ** Macro to return the number of elements in an array. SQLite has a
99768 ** similar macro called ArraySize(). Use a different name to avoid
99769 ** a collision when building an amalgamation with built-in FTS3.
99770 */
99771 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
99772
99773 /*
99774 ** Maximum length of a varint encoded integer. The varint format is different
99775 ** from that used by SQLite, so the maximum length is 10, not 9.
99776 */
99777 #define FTS3_VARINT_MAX 10
99778
99779 /*
99780 ** This section provides definitions to allow the
99781 ** FTS3 extension to be compiled outside of the 
99782 ** amalgamation.
99783 */
99784 #ifndef SQLITE_AMALGAMATION
99785 /*
99786 ** Macros indicating that conditional expressions are always true or
99787 ** false.
99788 */
99789 # define ALWAYS(x) (x)
99790 # define NEVER(X)  (x)
99791 /*
99792 ** Internal types used by SQLite.
99793 */
99794 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
99795 typedef short int i16;            /* 2-byte (or larger) signed integer */
99796 typedef unsigned int u32;         /* 4-byte unsigned integer */
99797 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
99798 /*
99799 ** Macro used to suppress compiler warnings for unused parameters.
99800 */
99801 #define UNUSED_PARAMETER(x) (void)(x)
99802 #endif
99803
99804 typedef struct Fts3Table Fts3Table;
99805 typedef struct Fts3Cursor Fts3Cursor;
99806 typedef struct Fts3Expr Fts3Expr;
99807 typedef struct Fts3Phrase Fts3Phrase;
99808 typedef struct Fts3SegReader Fts3SegReader;
99809 typedef struct Fts3SegFilter Fts3SegFilter;
99810
99811 /*
99812 ** A connection to a fulltext index is an instance of the following
99813 ** structure. The xCreate and xConnect methods create an instance
99814 ** of this structure and xDestroy and xDisconnect free that instance.
99815 ** All other methods receive a pointer to the structure as one of their
99816 ** arguments.
99817 */
99818 struct Fts3Table {
99819   sqlite3_vtab base;              /* Base class used by SQLite core */
99820   sqlite3 *db;                    /* The database connection */
99821   const char *zDb;                /* logical database name */
99822   const char *zName;              /* virtual table name */
99823   int nColumn;                    /* number of named columns in virtual table */
99824   char **azColumn;                /* column names.  malloced */
99825   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
99826
99827   /* Precompiled statements used by the implementation. Each of these 
99828   ** statements is run and reset within a single virtual table API call. 
99829   */
99830   sqlite3_stmt *aStmt[25];
99831
99832   /* Pointer to string containing the SQL:
99833   **
99834   ** "SELECT block FROM %_segments WHERE blockid BETWEEN ? AND ? 
99835   **    ORDER BY blockid"
99836   */
99837   char *zSelectLeaves;
99838   int nLeavesStmt;                /* Valid statements in aLeavesStmt */
99839   int nLeavesTotal;               /* Total number of prepared leaves stmts */
99840   int nLeavesAlloc;               /* Allocated size of aLeavesStmt */
99841   sqlite3_stmt **aLeavesStmt;     /* Array of prepared zSelectLeaves stmts */
99842
99843   int nNodeSize;                  /* Soft limit for node size */
99844   u8 bHasContent;                 /* True if %_content table exists */
99845   u8 bHasDocsize;                 /* True if %_docsize table exists */
99846
99847   /* The following hash table is used to buffer pending index updates during
99848   ** transactions. Variable nPendingData estimates the memory size of the 
99849   ** pending data, including hash table overhead, but not malloc overhead. 
99850   ** When nPendingData exceeds nMaxPendingData, the buffer is flushed 
99851   ** automatically. Variable iPrevDocid is the docid of the most recently
99852   ** inserted record.
99853   */
99854   int nMaxPendingData;
99855   int nPendingData;
99856   sqlite_int64 iPrevDocid;
99857   Fts3Hash pendingTerms;
99858 };
99859
99860 /*
99861 ** When the core wants to read from the virtual table, it creates a
99862 ** virtual table cursor (an instance of the following structure) using
99863 ** the xOpen method. Cursors are destroyed using the xClose method.
99864 */
99865 struct Fts3Cursor {
99866   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
99867   i16 eSearch;                    /* Search strategy (see below) */
99868   u8 isEof;                       /* True if at End Of Results */
99869   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
99870   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
99871   Fts3Expr *pExpr;                /* Parsed MATCH query string */
99872   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
99873   char *pNextId;                  /* Pointer into the body of aDoclist */
99874   char *aDoclist;                 /* List of docids for full-text queries */
99875   int nDoclist;                   /* Size of buffer at aDoclist */
99876   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
99877   u32 *aMatchinfo;                /* Information about most recent match */
99878 };
99879
99880 /*
99881 ** The Fts3Cursor.eSearch member is always set to one of the following.
99882 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
99883 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
99884 ** of the column to be searched.  For example, in
99885 **
99886 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
99887 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
99888 ** 
99889 ** Because the LHS of the MATCH operator is 2nd column "b",
99890 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
99891 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
99892 ** indicating that all columns should be searched,
99893 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
99894 */
99895 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
99896 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
99897 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
99898
99899 /*
99900 ** A "phrase" is a sequence of one or more tokens that must match in
99901 ** sequence.  A single token is the base case and the most common case.
99902 ** For a sequence of tokens contained in "...", nToken will be the number
99903 ** of tokens in the string.
99904 */
99905 struct Fts3Phrase {
99906   int nToken;                /* Number of tokens in the phrase */
99907   int iColumn;               /* Index of column this phrase must match */
99908   int isNot;                 /* Phrase prefixed by unary not (-) operator */
99909   struct PhraseToken {
99910     char *z;                 /* Text of the token */
99911     int n;                   /* Number of bytes in buffer pointed to by z */
99912     int isPrefix;            /* True if token ends in with a "*" character */
99913   } aToken[1];               /* One entry for each token in the phrase */
99914 };
99915
99916 /*
99917 ** A tree of these objects forms the RHS of a MATCH operator.
99918 **
99919 ** If Fts3Expr.eType is either FTSQUERY_NEAR or FTSQUERY_PHRASE and isLoaded
99920 ** is true, then aDoclist points to a malloced buffer, size nDoclist bytes, 
99921 ** containing the results of the NEAR or phrase query in FTS3 doclist
99922 ** format. As usual, the initial "Length" field found in doclists stored
99923 ** on disk is omitted from this buffer.
99924 **
99925 ** Variable pCurrent always points to the start of a docid field within
99926 ** aDoclist. Since the doclist is usually scanned in docid order, this can
99927 ** be used to accelerate seeking to the required docid within the doclist.
99928 */
99929 struct Fts3Expr {
99930   int eType;                 /* One of the FTSQUERY_XXX values defined below */
99931   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
99932   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
99933   Fts3Expr *pLeft;           /* Left operand */
99934   Fts3Expr *pRight;          /* Right operand */
99935   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
99936
99937   int isLoaded;              /* True if aDoclist/nDoclist are initialized. */
99938   char *aDoclist;            /* Buffer containing doclist */
99939   int nDoclist;              /* Size of aDoclist in bytes */
99940
99941   sqlite3_int64 iCurrent;
99942   char *pCurrent;
99943 };
99944
99945 /*
99946 ** Candidate values for Fts3Query.eType. Note that the order of the first
99947 ** four values is in order of precedence when parsing expressions. For 
99948 ** example, the following:
99949 **
99950 **   "a OR b AND c NOT d NEAR e"
99951 **
99952 ** is equivalent to:
99953 **
99954 **   "a OR (b AND (c NOT (d NEAR e)))"
99955 */
99956 #define FTSQUERY_NEAR   1
99957 #define FTSQUERY_NOT    2
99958 #define FTSQUERY_AND    3
99959 #define FTSQUERY_OR     4
99960 #define FTSQUERY_PHRASE 5
99961
99962
99963 /* fts3_init.c */
99964 SQLITE_PRIVATE int sqlite3Fts3DeleteVtab(int, sqlite3_vtab *);
99965 SQLITE_PRIVATE int sqlite3Fts3InitVtab(int, sqlite3*, void*, int, const char*const*, 
99966                         sqlite3_vtab **, char **);
99967
99968 /* fts3_write.c */
99969 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
99970 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
99971 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
99972 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
99973 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(Fts3Table *,int, sqlite3_int64,
99974   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
99975 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(Fts3Table*,const char*,int,int,Fts3SegReader**);
99976 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *, Fts3SegReader *);
99977 SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
99978   Fts3Table *, Fts3SegReader **, int, Fts3SegFilter *,
99979   int (*)(Fts3Table *, void *, char *, int, char *, int),  void *
99980 );
99981 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char const**, int*);
99982 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, sqlite3_stmt **);
99983 SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeLocal(Fts3Cursor*, u32*);
99984 SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeGlobal(Fts3Cursor*, u32*);
99985
99986 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
99987 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
99988 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
99989 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
99990 #define FTS3_SEGMENT_PREFIX        0x00000008
99991
99992 /* Type passed as 4th argument to SegmentReaderIterate() */
99993 struct Fts3SegFilter {
99994   const char *zTerm;
99995   int nTerm;
99996   int iCol;
99997   int flags;
99998 };
99999
100000 /* fts3.c */
100001 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
100002 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
100003 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
100004 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
100005 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
100006
100007 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(Fts3Expr *, sqlite3_int64, int);
100008 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *, Fts3Expr *);
100009 SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *, Fts3Expr *, int);
100010
100011 /* fts3_tokenizer.c */
100012 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
100013 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
100014 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, 
100015   const char *, sqlite3_tokenizer **, const char **, char **
100016 );
100017
100018 /* fts3_snippet.c */
100019 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
100020 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
100021   const char *, const char *, int, int
100022 );
100023 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *);
100024
100025 /* fts3_expr.c */
100026 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, 
100027   char **, int, int, const char *, int, Fts3Expr **
100028 );
100029 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
100030 #ifdef SQLITE_TEST
100031 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
100032 #endif
100033
100034 #endif /* _FTSINT_H */
100035
100036 /************** End of fts3Int.h *********************************************/
100037 /************** Continuing where we left off in fts3.c ***********************/
100038
100039
100040 #ifndef SQLITE_CORE 
100041   SQLITE_EXTENSION_INIT1
100042 #endif
100043
100044 /* 
100045 ** Write a 64-bit variable-length integer to memory starting at p[0].
100046 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
100047 ** The number of bytes written is returned.
100048 */
100049 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
100050   unsigned char *q = (unsigned char *) p;
100051   sqlite_uint64 vu = v;
100052   do{
100053     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
100054     vu >>= 7;
100055   }while( vu!=0 );
100056   q[-1] &= 0x7f;  /* turn off high bit in final byte */
100057   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
100058   return (int) (q - (unsigned char *)p);
100059 }
100060
100061 /* 
100062 ** Read a 64-bit variable-length integer from memory starting at p[0].
100063 ** Return the number of bytes read, or 0 on error.
100064 ** The value is stored in *v.
100065 */
100066 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
100067   const unsigned char *q = (const unsigned char *) p;
100068   sqlite_uint64 x = 0, y = 1;
100069   while( (*q&0x80)==0x80 && q-(unsigned char *)p<FTS3_VARINT_MAX ){
100070     x += y * (*q++ & 0x7f);
100071     y <<= 7;
100072   }
100073   x += y * (*q++);
100074   *v = (sqlite_int64) x;
100075   return (int) (q - (unsigned char *)p);
100076 }
100077
100078 /*
100079 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
100080 ** 32-bit integer before it is returned.
100081 */
100082 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
100083  sqlite_int64 i;
100084  int ret = sqlite3Fts3GetVarint(p, &i);
100085  *pi = (int) i;
100086  return ret;
100087 }
100088
100089 /*
100090 ** Return the number of bytes required to store the value passed as the
100091 ** first argument in varint form.
100092 */
100093 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
100094   int i = 0;
100095   do{
100096     i++;
100097     v >>= 7;
100098   }while( v!=0 );
100099   return i;
100100 }
100101
100102 /*
100103 ** Convert an SQL-style quoted string into a normal string by removing
100104 ** the quote characters.  The conversion is done in-place.  If the
100105 ** input does not begin with a quote character, then this routine
100106 ** is a no-op.
100107 **
100108 ** Examples:
100109 **
100110 **     "abc"   becomes   abc
100111 **     'xyz'   becomes   xyz
100112 **     [pqr]   becomes   pqr
100113 **     `mno`   becomes   mno
100114 **
100115 */
100116 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
100117   char quote;                     /* Quote character (if any ) */
100118
100119   quote = z[0];
100120   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
100121     int iIn = 1;                  /* Index of next byte to read from input */
100122     int iOut = 0;                 /* Index of next byte to write to output */
100123
100124     /* If the first byte was a '[', then the close-quote character is a ']' */
100125     if( quote=='[' ) quote = ']';  
100126
100127     while( ALWAYS(z[iIn]) ){
100128       if( z[iIn]==quote ){
100129         if( z[iIn+1]!=quote ) break;
100130         z[iOut++] = quote;
100131         iIn += 2;
100132       }else{
100133         z[iOut++] = z[iIn++];
100134       }
100135     }
100136     z[iOut] = '\0';
100137   }
100138 }
100139
100140 /*
100141 ** Read a single varint from the doclist at *pp and advance *pp to point
100142 ** to the next element of the varlist.  Add the value of the varint
100143 ** to *pVal.
100144 */
100145 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
100146   sqlite3_int64 iVal;
100147   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
100148   *pVal += iVal;
100149 }
100150
100151 /*
100152 ** As long as *pp has not reached its end (pEnd), then do the same
100153 ** as fts3GetDeltaVarint(): read a single varint and add it to *pVal.
100154 ** But if we have reached the end of the varint, just set *pp=0 and
100155 ** leave *pVal unchanged.
100156 */
100157 static void fts3GetDeltaVarint2(char **pp, char *pEnd, sqlite3_int64 *pVal){
100158   if( *pp>=pEnd ){
100159     *pp = 0;
100160   }else{
100161     fts3GetDeltaVarint(pp, pVal);
100162   }
100163 }
100164
100165 /*
100166 ** The xDisconnect() virtual table method.
100167 */
100168 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
100169   Fts3Table *p = (Fts3Table *)pVtab;
100170   int i;
100171
100172   assert( p->nPendingData==0 );
100173
100174   /* Free any prepared statements held */
100175   for(i=0; i<SizeofArray(p->aStmt); i++){
100176     sqlite3_finalize(p->aStmt[i]);
100177   }
100178   for(i=0; i<p->nLeavesStmt; i++){
100179     sqlite3_finalize(p->aLeavesStmt[i]);
100180   }
100181   sqlite3_free(p->zSelectLeaves);
100182   sqlite3_free(p->aLeavesStmt);
100183
100184   /* Invoke the tokenizer destructor to free the tokenizer. */
100185   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
100186
100187   sqlite3_free(p);
100188   return SQLITE_OK;
100189 }
100190
100191 /*
100192 ** Construct one or more SQL statements from the format string given
100193 ** and then evaluate those statements.  The success code is writting
100194 ** into *pRc.
100195 **
100196 ** If *pRc is initially non-zero then this routine is a no-op.
100197 */
100198 void fts3DbExec(
100199   int *pRc,              /* Success code */
100200   sqlite3 *db,           /* Database in which to run SQL */
100201   const char *zFormat,   /* Format string for SQL */
100202   ...                    /* Arguments to the format string */
100203 ){
100204   va_list ap;
100205   char *zSql;
100206   if( *pRc ) return;
100207   va_start(ap, zFormat);
100208   zSql = sqlite3_vmprintf(zFormat, ap);
100209   va_end(ap);
100210   if( zSql==0 ){
100211     *pRc = SQLITE_NOMEM;
100212   }else{
100213     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
100214     sqlite3_free(zSql);
100215   }
100216 }
100217
100218 /*
100219 ** The xDestroy() virtual table method.
100220 */
100221 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
100222   int rc = SQLITE_OK;              /* Return code */
100223   Fts3Table *p = (Fts3Table *)pVtab;
100224   sqlite3 *db = p->db;
100225
100226   /* Drop the shadow tables */
100227   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", p->zDb, p->zName);
100228   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", p->zDb,p->zName);
100229   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", p->zDb, p->zName);
100230   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", p->zDb, p->zName);
100231   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", p->zDb, p->zName);
100232
100233   /* If everything has worked, invoke fts3DisconnectMethod() to free the
100234   ** memory associated with the Fts3Table structure and return SQLITE_OK.
100235   ** Otherwise, return an SQLite error code.
100236   */
100237   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
100238 }
100239
100240
100241 /*
100242 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
100243 ** passed as the first argument. This is done as part of the xConnect()
100244 ** and xCreate() methods.
100245 */
100246 static int fts3DeclareVtab(Fts3Table *p){
100247   int i;                          /* Iterator variable */
100248   int rc;                         /* Return code */
100249   char *zSql;                     /* SQL statement passed to declare_vtab() */
100250   char *zCols;                    /* List of user defined columns */
100251
100252   /* Create a list of user columns for the virtual table */
100253   zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
100254   for(i=1; zCols && i<p->nColumn; i++){
100255     zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
100256   }
100257
100258   /* Create the whole "CREATE TABLE" statement to pass to SQLite */
100259   zSql = sqlite3_mprintf(
100260       "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN)", zCols, p->zName
100261   );
100262
100263   if( !zCols || !zSql ){
100264     rc = SQLITE_NOMEM;
100265   }else{
100266     rc = sqlite3_declare_vtab(p->db, zSql);
100267   }
100268
100269   sqlite3_free(zSql);
100270   sqlite3_free(zCols);
100271   return rc;
100272 }
100273
100274 /*
100275 ** Create the backing store tables (%_content, %_segments and %_segdir)
100276 ** required by the FTS3 table passed as the only argument. This is done
100277 ** as part of the vtab xCreate() method.
100278 */
100279 static int fts3CreateTables(Fts3Table *p){
100280   int rc = SQLITE_OK;             /* Return code */
100281   int i;                          /* Iterator variable */
100282   char *zContentCols;             /* Columns of %_content table */
100283   sqlite3 *db = p->db;            /* The database connection */
100284
100285   /* Create a list of user columns for the content table */
100286   if( p->bHasContent ){
100287     zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
100288     for(i=0; zContentCols && i<p->nColumn; i++){
100289       char *z = p->azColumn[i];
100290       zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
100291     }
100292     if( zContentCols==0 ) rc = SQLITE_NOMEM;
100293
100294     /* Create the content table */
100295     fts3DbExec(&rc, db, 
100296        "CREATE TABLE %Q.'%q_content'(%s)",
100297        p->zDb, p->zName, zContentCols
100298     );
100299     sqlite3_free(zContentCols);
100300   }
100301   /* Create other tables */
100302   fts3DbExec(&rc, db, 
100303       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
100304       p->zDb, p->zName
100305   );
100306   fts3DbExec(&rc, db, 
100307       "CREATE TABLE %Q.'%q_segdir'("
100308         "level INTEGER,"
100309         "idx INTEGER,"
100310         "start_block INTEGER,"
100311         "leaves_end_block INTEGER,"
100312         "end_block INTEGER,"
100313         "root BLOB,"
100314         "PRIMARY KEY(level, idx)"
100315       ");",
100316       p->zDb, p->zName
100317   );
100318   if( p->bHasDocsize ){
100319     fts3DbExec(&rc, db, 
100320         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
100321         p->zDb, p->zName
100322     );
100323     fts3DbExec(&rc, db, 
100324         "CREATE TABLE %Q.'%q_stat'(id INTEGER PRIMARY KEY, value BLOB);",
100325         p->zDb, p->zName
100326     );
100327   }
100328   return rc;
100329 }
100330
100331 /*
100332 ** An sqlite3_exec() callback for fts3TableExists.
100333 */
100334 static int fts3TableExistsCallback(void *pArg, int n, char **pp1, char **pp2){
100335   *(int*)pArg = 1;
100336   return 1;
100337 }
100338
100339 /*
100340 ** Determine if a table currently exists in the database.
100341 */
100342 static void fts3TableExists(
100343   int *pRc,             /* Success code */
100344   sqlite3 *db,          /* The database connection to test */
100345   const char *zDb,      /* ATTACHed database within the connection */
100346   const char *zName,    /* Name of the FTS3 table */
100347   const char *zSuffix,  /* Shadow table extension */
100348   u8 *pResult           /* Write results here */
100349 ){
100350   int rc = SQLITE_OK;
100351   int res = 0;
100352   char *zSql;
100353   if( *pRc ) return;
100354   zSql = sqlite3_mprintf(
100355     "SELECT 1 FROM %Q.sqlite_master WHERE name='%q%s'",
100356     zDb, zName, zSuffix
100357   );    
100358   rc = sqlite3_exec(db, zSql, fts3TableExistsCallback, &res, 0);
100359   sqlite3_free(zSql);
100360   *pResult = res & 0xff;
100361   if( rc!=SQLITE_ABORT ) *pRc = rc;
100362 }
100363
100364 /*
100365 ** This function is the implementation of both the xConnect and xCreate
100366 ** methods of the FTS3 virtual table.
100367 **
100368 ** The argv[] array contains the following:
100369 **
100370 **   argv[0]   -> module name
100371 **   argv[1]   -> database name
100372 **   argv[2]   -> table name
100373 **   argv[...] -> "column name" and other module argument fields.
100374 */
100375 static int fts3InitVtab(
100376   int isCreate,                   /* True for xCreate, false for xConnect */
100377   sqlite3 *db,                    /* The SQLite database connection */
100378   void *pAux,                     /* Hash table containing tokenizers */
100379   int argc,                       /* Number of elements in argv array */
100380   const char * const *argv,       /* xCreate/xConnect argument array */
100381   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
100382   char **pzErr                    /* Write any error message here */
100383 ){
100384   Fts3Hash *pHash = (Fts3Hash *)pAux;
100385   Fts3Table *p;                   /* Pointer to allocated vtab */
100386   int rc;                         /* Return code */
100387   int i;                          /* Iterator variable */
100388   int nByte;                      /* Size of allocation used for *p */
100389   int iCol;
100390   int nString = 0;
100391   int nCol = 0;
100392   char *zCsr;
100393   int nDb;
100394   int nName;
100395
100396   const char *zTokenizer = 0;               /* Name of tokenizer to use */
100397   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
100398
100399   nDb = (int)strlen(argv[1]) + 1;
100400   nName = (int)strlen(argv[2]) + 1;
100401   for(i=3; i<argc; i++){
100402     char const *z = argv[i];
100403     rc = sqlite3Fts3InitTokenizer(pHash, z, &pTokenizer, &zTokenizer, pzErr);
100404     if( rc!=SQLITE_OK ){
100405       return rc;
100406     }
100407     if( z!=zTokenizer ){
100408       nString += (int)(strlen(z) + 1);
100409     }
100410   }
100411   nCol = argc - 3 - (zTokenizer!=0);
100412   if( zTokenizer==0 ){
100413     rc = sqlite3Fts3InitTokenizer(pHash, 0, &pTokenizer, 0, pzErr);
100414     if( rc!=SQLITE_OK ){
100415       return rc;
100416     }
100417     assert( pTokenizer );
100418   }
100419
100420   if( nCol==0 ){
100421     nCol = 1;
100422   }
100423
100424   /* Allocate and populate the Fts3Table structure. */
100425   nByte = sizeof(Fts3Table) +              /* Fts3Table */
100426           nCol * sizeof(char *) +              /* azColumn */
100427           nName +                              /* zName */
100428           nDb +                                /* zDb */
100429           nString;                             /* Space for azColumn strings */
100430   p = (Fts3Table*)sqlite3_malloc(nByte);
100431   if( p==0 ){
100432     rc = SQLITE_NOMEM;
100433     goto fts3_init_out;
100434   }
100435   memset(p, 0, nByte);
100436
100437   p->db = db;
100438   p->nColumn = nCol;
100439   p->nPendingData = 0;
100440   p->azColumn = (char **)&p[1];
100441   p->pTokenizer = pTokenizer;
100442   p->nNodeSize = 1000;
100443   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
100444   zCsr = (char *)&p->azColumn[nCol];
100445
100446   fts3HashInit(&p->pendingTerms, FTS3_HASH_STRING, 1);
100447
100448   /* Fill in the zName and zDb fields of the vtab structure. */
100449   p->zName = zCsr;
100450   memcpy(zCsr, argv[2], nName);
100451   zCsr += nName;
100452   p->zDb = zCsr;
100453   memcpy(zCsr, argv[1], nDb);
100454   zCsr += nDb;
100455
100456   /* Fill in the azColumn array */
100457   iCol = 0;
100458   for(i=3; i<argc; i++){
100459     if( argv[i]!=zTokenizer ){
100460       char *z; 
100461       int n;
100462       z = (char *)sqlite3Fts3NextToken(argv[i], &n);
100463       memcpy(zCsr, z, n);
100464       zCsr[n] = '\0';
100465       sqlite3Fts3Dequote(zCsr);
100466       p->azColumn[iCol++] = zCsr;
100467       zCsr += n+1;
100468       assert( zCsr <= &((char *)p)[nByte] );
100469     }
100470   }
100471   if( iCol==0 ){
100472     assert( nCol==1 );
100473     p->azColumn[0] = "content";
100474   }
100475
100476   /* If this is an xCreate call, create the underlying tables in the 
100477   ** database. TODO: For xConnect(), it could verify that said tables exist.
100478   */
100479   if( isCreate ){
100480     p->bHasContent = 1;
100481     p->bHasDocsize = argv[0][3]=='4';
100482     rc = fts3CreateTables(p);
100483   }else{
100484     rc = SQLITE_OK;
100485     fts3TableExists(&rc, db, argv[1], argv[2], "_content", &p->bHasContent);
100486     fts3TableExists(&rc, db, argv[1], argv[2], "_docsize", &p->bHasDocsize);
100487   }
100488   if( rc!=SQLITE_OK ) goto fts3_init_out;
100489
100490   rc = fts3DeclareVtab(p);
100491   if( rc!=SQLITE_OK ) goto fts3_init_out;
100492
100493   *ppVTab = &p->base;
100494
100495 fts3_init_out:
100496   assert( p || (pTokenizer && rc!=SQLITE_OK) );
100497   if( rc!=SQLITE_OK ){
100498     if( p ){
100499       fts3DisconnectMethod((sqlite3_vtab *)p);
100500     }else{
100501       pTokenizer->pModule->xDestroy(pTokenizer);
100502     }
100503   }
100504   return rc;
100505 }
100506
100507 /*
100508 ** The xConnect() and xCreate() methods for the virtual table. All the
100509 ** work is done in function fts3InitVtab().
100510 */
100511 static int fts3ConnectMethod(
100512   sqlite3 *db,                    /* Database connection */
100513   void *pAux,                     /* Pointer to tokenizer hash table */
100514   int argc,                       /* Number of elements in argv array */
100515   const char * const *argv,       /* xCreate/xConnect argument array */
100516   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
100517   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
100518 ){
100519   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
100520 }
100521 static int fts3CreateMethod(
100522   sqlite3 *db,                    /* Database connection */
100523   void *pAux,                     /* Pointer to tokenizer hash table */
100524   int argc,                       /* Number of elements in argv array */
100525   const char * const *argv,       /* xCreate/xConnect argument array */
100526   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
100527   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
100528 ){
100529   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
100530 }
100531
100532 /* 
100533 ** Implementation of the xBestIndex method for FTS3 tables. There
100534 ** are three possible strategies, in order of preference:
100535 **
100536 **   1. Direct lookup by rowid or docid. 
100537 **   2. Full-text search using a MATCH operator on a non-docid column.
100538 **   3. Linear scan of %_content table.
100539 */
100540 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
100541   Fts3Table *p = (Fts3Table *)pVTab;
100542   int i;                          /* Iterator variable */
100543   int iCons = -1;                 /* Index of constraint to use */
100544
100545   /* By default use a full table scan. This is an expensive option,
100546   ** so search through the constraints to see if a more efficient 
100547   ** strategy is possible.
100548   */
100549   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
100550   pInfo->estimatedCost = 500000;
100551   for(i=0; i<pInfo->nConstraint; i++){
100552     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
100553     if( pCons->usable==0 ) continue;
100554
100555     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
100556     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
100557      && (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1 )
100558     ){
100559       pInfo->idxNum = FTS3_DOCID_SEARCH;
100560       pInfo->estimatedCost = 1.0;
100561       iCons = i;
100562     }
100563
100564     /* A MATCH constraint. Use a full-text search.
100565     **
100566     ** If there is more than one MATCH constraint available, use the first
100567     ** one encountered. If there is both a MATCH constraint and a direct
100568     ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
100569     ** though the rowid/docid lookup is faster than a MATCH query, selecting
100570     ** it would lead to an "unable to use function MATCH in the requested 
100571     ** context" error.
100572     */
100573     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH 
100574      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
100575     ){
100576       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
100577       pInfo->estimatedCost = 2.0;
100578       iCons = i;
100579       break;
100580     }
100581   }
100582
100583   if( iCons>=0 ){
100584     pInfo->aConstraintUsage[iCons].argvIndex = 1;
100585     pInfo->aConstraintUsage[iCons].omit = 1;
100586   } 
100587   return SQLITE_OK;
100588 }
100589
100590 /*
100591 ** Implementation of xOpen method.
100592 */
100593 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
100594   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
100595
100596   UNUSED_PARAMETER(pVTab);
100597
100598   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
100599   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, 
100600   ** if the allocation fails, return SQLITE_NOMEM.
100601   */
100602   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
100603   if( !pCsr ){
100604     return SQLITE_NOMEM;
100605   }
100606   memset(pCsr, 0, sizeof(Fts3Cursor));
100607   return SQLITE_OK;
100608 }
100609
100610 /*
100611 ** Close the cursor.  For additional information see the documentation
100612 ** on the xClose method of the virtual table interface.
100613 */
100614 static int fulltextClose(sqlite3_vtab_cursor *pCursor){
100615   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
100616   sqlite3_finalize(pCsr->pStmt);
100617   sqlite3Fts3ExprFree(pCsr->pExpr);
100618   sqlite3_free(pCsr->aDoclist);
100619   sqlite3_free(pCsr->aMatchinfo);
100620   sqlite3_free(pCsr);
100621   return SQLITE_OK;
100622 }
100623
100624 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
100625   if( pCsr->isRequireSeek ){
100626     pCsr->isRequireSeek = 0;
100627     sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
100628     if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
100629       return SQLITE_OK;
100630     }else{
100631       int rc = sqlite3_reset(pCsr->pStmt);
100632       if( rc==SQLITE_OK ){
100633         /* If no row was found and no error has occured, then the %_content
100634         ** table is missing a row that is present in the full-text index.
100635         ** The data structures are corrupt.
100636         */
100637         rc = SQLITE_CORRUPT;
100638       }
100639       pCsr->isEof = 1;
100640       if( pContext ){
100641         sqlite3_result_error_code(pContext, rc);
100642       }
100643       return rc;
100644     }
100645   }else{
100646     return SQLITE_OK;
100647   }
100648 }
100649
100650 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
100651   int rc = SQLITE_OK;             /* Return code */
100652   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
100653
100654   if( pCsr->aDoclist==0 ){
100655     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
100656       pCsr->isEof = 1;
100657       rc = sqlite3_reset(pCsr->pStmt);
100658     }
100659   }else if( pCsr->pNextId>=&pCsr->aDoclist[pCsr->nDoclist] ){
100660     pCsr->isEof = 1;
100661   }else{
100662     sqlite3_reset(pCsr->pStmt);
100663     fts3GetDeltaVarint(&pCsr->pNextId, &pCsr->iPrevId);
100664     pCsr->isRequireSeek = 1;
100665     pCsr->isMatchinfoNeeded = 1;
100666   }
100667   return rc;
100668 }
100669
100670
100671 /*
100672 ** The buffer pointed to by argument zNode (size nNode bytes) contains the
100673 ** root node of a b-tree segment. The segment is guaranteed to be at least
100674 ** one level high (i.e. the root node is not also a leaf). If successful,
100675 ** this function locates the leaf node of the segment that may contain the 
100676 ** term specified by arguments zTerm and nTerm and writes its block number 
100677 ** to *piLeaf.
100678 **
100679 ** It is possible that the returned leaf node does not contain the specified
100680 ** term. However, if the segment does contain said term, it is stored on
100681 ** the identified leaf node. Because this function only inspects interior
100682 ** segment nodes (and never loads leaf nodes into memory), it is not possible
100683 ** to be sure.
100684 **
100685 ** If an error occurs, an error code other than SQLITE_OK is returned.
100686 */ 
100687 static int fts3SelectLeaf(
100688   Fts3Table *p,                   /* Virtual table handle */
100689   const char *zTerm,              /* Term to select leaves for */
100690   int nTerm,                      /* Size of term zTerm in bytes */
100691   const char *zNode,              /* Buffer containing segment interior node */
100692   int nNode,                      /* Size of buffer at zNode */
100693   sqlite3_int64 *piLeaf           /* Selected leaf node */
100694 ){
100695   int rc = SQLITE_OK;             /* Return code */
100696   const char *zCsr = zNode;       /* Cursor to iterate through node */
100697   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
100698   char *zBuffer = 0;              /* Buffer to load terms into */
100699   int nAlloc = 0;                 /* Size of allocated buffer */
100700
100701   while( 1 ){
100702     int isFirstTerm = 1;          /* True when processing first term on page */
100703     int iHeight;                  /* Height of this node in tree */
100704     sqlite3_int64 iChild;         /* Block id of child node to descend to */
100705     int nBlock;                   /* Size of child node in bytes */
100706
100707     zCsr += sqlite3Fts3GetVarint32(zCsr, &iHeight);
100708     zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
100709   
100710     while( zCsr<zEnd ){
100711       int cmp;                    /* memcmp() result */
100712       int nSuffix;                /* Size of term suffix */
100713       int nPrefix = 0;            /* Size of term prefix */
100714       int nBuffer;                /* Total term size */
100715   
100716       /* Load the next term on the node into zBuffer */
100717       if( !isFirstTerm ){
100718         zCsr += sqlite3Fts3GetVarint32(zCsr, &nPrefix);
100719       }
100720       isFirstTerm = 0;
100721       zCsr += sqlite3Fts3GetVarint32(zCsr, &nSuffix);
100722       if( nPrefix+nSuffix>nAlloc ){
100723         char *zNew;
100724         nAlloc = (nPrefix+nSuffix) * 2;
100725         zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
100726         if( !zNew ){
100727           sqlite3_free(zBuffer);
100728           return SQLITE_NOMEM;
100729         }
100730         zBuffer = zNew;
100731       }
100732       memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
100733       nBuffer = nPrefix + nSuffix;
100734       zCsr += nSuffix;
100735   
100736       /* Compare the term we are searching for with the term just loaded from
100737       ** the interior node. If the specified term is greater than or equal
100738       ** to the term from the interior node, then all terms on the sub-tree 
100739       ** headed by node iChild are smaller than zTerm. No need to search 
100740       ** iChild.
100741       **
100742       ** If the interior node term is larger than the specified term, then
100743       ** the tree headed by iChild may contain the specified term.
100744       */
100745       cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
100746       if( cmp<0 || (cmp==0 && nBuffer>nTerm) ) break;
100747       iChild++;
100748     };
100749
100750     /* If (iHeight==1), the children of this interior node are leaves. The
100751     ** specified term may be present on leaf node iChild.
100752     */
100753     if( iHeight==1 ){
100754       *piLeaf = iChild;
100755       break;
100756     }
100757
100758     /* Descend to interior node iChild. */
100759     rc = sqlite3Fts3ReadBlock(p, iChild, &zCsr, &nBlock);
100760     if( rc!=SQLITE_OK ) break;
100761     zEnd = &zCsr[nBlock];
100762   }
100763   sqlite3_free(zBuffer);
100764   return rc;
100765 }
100766
100767 /*
100768 ** This function is used to create delta-encoded serialized lists of FTS3 
100769 ** varints. Each call to this function appends a single varint to a list.
100770 */
100771 static void fts3PutDeltaVarint(
100772   char **pp,                      /* IN/OUT: Output pointer */
100773   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
100774   sqlite3_int64 iVal              /* Write this value to the list */
100775 ){
100776   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
100777   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
100778   *piPrev = iVal;
100779 }
100780
100781 /*
100782 ** When this function is called, *ppPoslist is assumed to point to the 
100783 ** start of a position-list. After it returns, *ppPoslist points to the
100784 ** first byte after the position-list.
100785 **
100786 ** If pp is not NULL, then the contents of the position list are copied
100787 ** to *pp. *pp is set to point to the first byte past the last byte copied
100788 ** before this function returns.
100789 */
100790 static void fts3PoslistCopy(char **pp, char **ppPoslist){
100791   char *pEnd = *ppPoslist;
100792   char c = 0;
100793
100794   /* The end of a position list is marked by a zero encoded as an FTS3 
100795   ** varint. A single 0x00 byte. Except, if the 0x00 byte is preceded by
100796   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
100797   ** of some other, multi-byte, value.
100798   **
100799   ** The following block moves pEnd to point to the first byte that is not 
100800   ** immediately preceded by a byte with the 0x80 bit set. Then increments
100801   ** pEnd once more so that it points to the byte immediately following the
100802   ** last byte in the position-list.
100803   */
100804   while( *pEnd | c ) c = *pEnd++ & 0x80;
100805   pEnd++;
100806
100807   if( pp ){
100808     int n = (int)(pEnd - *ppPoslist);
100809     char *p = *pp;
100810     memcpy(p, *ppPoslist, n);
100811     p += n;
100812     *pp = p;
100813   }
100814   *ppPoslist = pEnd;
100815 }
100816
100817 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
100818   char *pEnd = *ppPoslist;
100819   char c = 0;
100820
100821   /* A column-list is terminated by either a 0x01 or 0x00. */
100822   while( 0xFE & (*pEnd | c) ) c = *pEnd++ & 0x80;
100823   if( pp ){
100824     int n = (int)(pEnd - *ppPoslist);
100825     char *p = *pp;
100826     memcpy(p, *ppPoslist, n);
100827     p += n;
100828     *pp = p;
100829   }
100830   *ppPoslist = pEnd;
100831 }
100832
100833 /*
100834 ** Value used to signify the end of an offset-list. This is safe because
100835 ** it is not possible to have a document with 2^31 terms.
100836 */
100837 #define OFFSET_LIST_END 0x7fffffff
100838
100839 /*
100840 ** This function is used to help parse offset-lists. When this function is
100841 ** called, *pp may point to the start of the next varint in the offset-list
100842 ** being parsed, or it may point to 1 byte past the end of the offset-list
100843 ** (in which case **pp will be 0x00 or 0x01).
100844 **
100845 ** If *pp points past the end of the current offset list, set *pi to 
100846 ** OFFSET_LIST_END and return. Otherwise, read the next varint from *pp,
100847 ** increment the current value of *pi by the value read, and set *pp to
100848 ** point to the next value before returning.
100849 */
100850 static void fts3ReadNextPos(
100851   char **pp,                      /* IN/OUT: Pointer into offset-list buffer */
100852   sqlite3_int64 *pi               /* IN/OUT: Value read from offset-list */
100853 ){
100854   if( **pp&0xFE ){
100855     fts3GetDeltaVarint(pp, pi);
100856     *pi -= 2;
100857   }else{
100858     *pi = OFFSET_LIST_END;
100859   }
100860 }
100861
100862 /*
100863 ** If parameter iCol is not 0, write an 0x01 byte followed by the value of
100864 ** iCol encoded as a varint to *pp. 
100865 **
100866 ** Set *pp to point to the byte just after the last byte written before 
100867 ** returning (do not modify it if iCol==0). Return the total number of bytes
100868 ** written (0 if iCol==0).
100869 */
100870 static int fts3PutColNumber(char **pp, int iCol){
100871   int n = 0;                      /* Number of bytes written */
100872   if( iCol ){
100873     char *p = *pp;                /* Output pointer */
100874     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
100875     *p = 0x01;
100876     *pp = &p[n];
100877   }
100878   return n;
100879 }
100880
100881 /*
100882 **
100883 */
100884 static void fts3PoslistMerge(
100885   char **pp,                      /* Output buffer */
100886   char **pp1,                     /* Left input list */
100887   char **pp2                      /* Right input list */
100888 ){
100889   char *p = *pp;
100890   char *p1 = *pp1;
100891   char *p2 = *pp2;
100892
100893   while( *p1 || *p2 ){
100894     int iCol1;
100895     int iCol2;
100896
100897     if( *p1==0x01 ) sqlite3Fts3GetVarint32(&p1[1], &iCol1);
100898     else if( *p1==0x00 ) iCol1 = OFFSET_LIST_END;
100899     else iCol1 = 0;
100900
100901     if( *p2==0x01 ) sqlite3Fts3GetVarint32(&p2[1], &iCol2);
100902     else if( *p2==0x00 ) iCol2 = OFFSET_LIST_END;
100903     else iCol2 = 0;
100904
100905     if( iCol1==iCol2 ){
100906       sqlite3_int64 i1 = 0;
100907       sqlite3_int64 i2 = 0;
100908       sqlite3_int64 iPrev = 0;
100909       int n = fts3PutColNumber(&p, iCol1);
100910       p1 += n;
100911       p2 += n;
100912
100913       /* At this point, both p1 and p2 point to the start of offset-lists.
100914       ** An offset-list is a list of non-negative delta-encoded varints, each 
100915       ** incremented by 2 before being stored. Each list is terminated by a 0 
100916       ** or 1 value (0x00 or 0x01). The following block merges the two lists
100917       ** and writes the results to buffer p. p is left pointing to the byte
100918       ** after the list written. No terminator (0x00 or 0x01) is written to
100919       ** the output.
100920       */
100921       fts3GetDeltaVarint(&p1, &i1);
100922       fts3GetDeltaVarint(&p2, &i2);
100923       do {
100924         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
100925         iPrev -= 2;
100926         if( i1==i2 ){
100927           fts3ReadNextPos(&p1, &i1);
100928           fts3ReadNextPos(&p2, &i2);
100929         }else if( i1<i2 ){
100930           fts3ReadNextPos(&p1, &i1);
100931         }else{
100932           fts3ReadNextPos(&p2, &i2);
100933         }
100934       }while( i1!=OFFSET_LIST_END || i2!=OFFSET_LIST_END );
100935     }else if( iCol1<iCol2 ){
100936       p1 += fts3PutColNumber(&p, iCol1);
100937       fts3ColumnlistCopy(&p, &p1);
100938     }else{
100939       p2 += fts3PutColNumber(&p, iCol2);
100940       fts3ColumnlistCopy(&p, &p2);
100941     }
100942   }
100943
100944   *p++ = '\0';
100945   *pp = p;
100946   *pp1 = p1 + 1;
100947   *pp2 = p2 + 1;
100948 }
100949
100950 /*
100951 ** nToken==1 searches for adjacent positions.
100952 */
100953 static int fts3PoslistPhraseMerge(
100954   char **pp,                      /* Output buffer */
100955   int nToken,                     /* Maximum difference in token positions */
100956   int isSaveLeft,                 /* Save the left position */
100957   char **pp1,                     /* Left input list */
100958   char **pp2                      /* Right input list */
100959 ){
100960   char *p = (pp ? *pp : 0);
100961   char *p1 = *pp1;
100962   char *p2 = *pp2;
100963
100964   int iCol1 = 0;
100965   int iCol2 = 0;
100966   assert( *p1!=0 && *p2!=0 );
100967   if( *p1==0x01 ){ 
100968     p1++;
100969     p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
100970   }
100971   if( *p2==0x01 ){ 
100972     p2++;
100973     p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
100974   }
100975
100976   while( 1 ){
100977     if( iCol1==iCol2 ){
100978       char *pSave = p;
100979       sqlite3_int64 iPrev = 0;
100980       sqlite3_int64 iPos1 = 0;
100981       sqlite3_int64 iPos2 = 0;
100982
100983       if( pp && iCol1 ){
100984         *p++ = 0x01;
100985         p += sqlite3Fts3PutVarint(p, iCol1);
100986       }
100987
100988       assert( *p1!=0x00 && *p2!=0x00 && *p1!=0x01 && *p2!=0x01 );
100989       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
100990       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
100991
100992       while( 1 ){
100993         if( iPos2>iPos1 && iPos2<=iPos1+nToken ){
100994           sqlite3_int64 iSave;
100995           if( !pp ){
100996             fts3PoslistCopy(0, &p2);
100997             fts3PoslistCopy(0, &p1);
100998             *pp1 = p1;
100999             *pp2 = p2;
101000             return 1;
101001           }
101002           iSave = isSaveLeft ? iPos1 : iPos2;
101003           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
101004           pSave = 0;
101005         }
101006         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
101007           if( (*p2&0xFE)==0 ) break;
101008           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
101009         }else{
101010           if( (*p1&0xFE)==0 ) break;
101011           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
101012         }
101013       }
101014
101015       if( pSave ){
101016         assert( pp && p );
101017         p = pSave;
101018       }
101019
101020       fts3ColumnlistCopy(0, &p1);
101021       fts3ColumnlistCopy(0, &p2);
101022       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
101023       if( 0==*p1 || 0==*p2 ) break;
101024
101025       p1++;
101026       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
101027       p2++;
101028       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
101029     }
101030
101031     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
101032     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
101033     ** end of the position list, or the 0x01 that precedes the next 
101034     ** column-number in the position list. 
101035     */
101036     else if( iCol1<iCol2 ){
101037       fts3ColumnlistCopy(0, &p1);
101038       if( 0==*p1 ) break;
101039       p1++;
101040       p1 += sqlite3Fts3GetVarint32(p1, &iCol1);
101041     }else{
101042       fts3ColumnlistCopy(0, &p2);
101043       if( 0==*p2 ) break;
101044       p2++;
101045       p2 += sqlite3Fts3GetVarint32(p2, &iCol2);
101046     }
101047   }
101048
101049   fts3PoslistCopy(0, &p2);
101050   fts3PoslistCopy(0, &p1);
101051   *pp1 = p1;
101052   *pp2 = p2;
101053   if( !pp || *pp==p ){
101054     return 0;
101055   }
101056   *p++ = 0x00;
101057   *pp = p;
101058   return 1;
101059 }
101060
101061 /*
101062 ** Merge two position-lists as required by the NEAR operator.
101063 */
101064 static int fts3PoslistNearMerge(
101065   char **pp,                      /* Output buffer */
101066   char *aTmp,                     /* Temporary buffer space */
101067   int nRight,                     /* Maximum difference in token positions */
101068   int nLeft,                      /* Maximum difference in token positions */
101069   char **pp1,                     /* IN/OUT: Left input list */
101070   char **pp2                      /* IN/OUT: Right input list */
101071 ){
101072   char *p1 = *pp1;
101073   char *p2 = *pp2;
101074
101075   if( !pp ){
101076     if( fts3PoslistPhraseMerge(0, nRight, 0, pp1, pp2) ) return 1;
101077     *pp1 = p1;
101078     *pp2 = p2;
101079     return fts3PoslistPhraseMerge(0, nLeft, 0, pp2, pp1);
101080   }else{
101081     char *pTmp1 = aTmp;
101082     char *pTmp2;
101083     char *aTmp2;
101084     int res = 1;
101085
101086     fts3PoslistPhraseMerge(&pTmp1, nRight, 0, pp1, pp2);
101087     aTmp2 = pTmp2 = pTmp1;
101088     *pp1 = p1;
101089     *pp2 = p2;
101090     fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, pp2, pp1);
101091     if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
101092       fts3PoslistMerge(pp, &aTmp, &aTmp2);
101093     }else if( pTmp1!=aTmp ){
101094       fts3PoslistCopy(pp, &aTmp);
101095     }else if( pTmp2!=aTmp2 ){
101096       fts3PoslistCopy(pp, &aTmp2);
101097     }else{
101098       res = 0;
101099     }
101100
101101     return res;
101102   }
101103 }
101104
101105 /*
101106 ** Values that may be used as the first parameter to fts3DoclistMerge().
101107 */
101108 #define MERGE_NOT        2        /* D + D -> D */
101109 #define MERGE_AND        3        /* D + D -> D */
101110 #define MERGE_OR         4        /* D + D -> D */
101111 #define MERGE_POS_OR     5        /* P + P -> P */
101112 #define MERGE_PHRASE     6        /* P + P -> D */
101113 #define MERGE_POS_PHRASE 7        /* P + P -> P */
101114 #define MERGE_NEAR       8        /* P + P -> D */
101115 #define MERGE_POS_NEAR   9        /* P + P -> P */
101116
101117 /*
101118 ** Merge the two doclists passed in buffer a1 (size n1 bytes) and a2
101119 ** (size n2 bytes). The output is written to pre-allocated buffer aBuffer,
101120 ** which is guaranteed to be large enough to hold the results. The number
101121 ** of bytes written to aBuffer is stored in *pnBuffer before returning.
101122 **
101123 ** If successful, SQLITE_OK is returned. Otherwise, if a malloc error
101124 ** occurs while allocating a temporary buffer as part of the merge operation,
101125 ** SQLITE_NOMEM is returned.
101126 */
101127 static int fts3DoclistMerge(
101128   int mergetype,                  /* One of the MERGE_XXX constants */
101129   int nParam1,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
101130   int nParam2,                    /* Used by MERGE_NEAR and MERGE_POS_NEAR */
101131   char *aBuffer,                  /* Pre-allocated output buffer */
101132   int *pnBuffer,                  /* OUT: Bytes written to aBuffer */
101133   char *a1,                       /* Buffer containing first doclist */
101134   int n1,                         /* Size of buffer a1 */
101135   char *a2,                       /* Buffer containing second doclist */
101136   int n2                          /* Size of buffer a2 */
101137 ){
101138   sqlite3_int64 i1 = 0;
101139   sqlite3_int64 i2 = 0;
101140   sqlite3_int64 iPrev = 0;
101141
101142   char *p = aBuffer;
101143   char *p1 = a1;
101144   char *p2 = a2;
101145   char *pEnd1 = &a1[n1];
101146   char *pEnd2 = &a2[n2];
101147
101148   assert( mergetype==MERGE_OR     || mergetype==MERGE_POS_OR 
101149        || mergetype==MERGE_AND    || mergetype==MERGE_NOT
101150        || mergetype==MERGE_PHRASE || mergetype==MERGE_POS_PHRASE
101151        || mergetype==MERGE_NEAR   || mergetype==MERGE_POS_NEAR
101152   );
101153
101154   if( !aBuffer ){
101155     *pnBuffer = 0;
101156     return SQLITE_NOMEM;
101157   }
101158
101159   /* Read the first docid from each doclist */
101160   fts3GetDeltaVarint2(&p1, pEnd1, &i1);
101161   fts3GetDeltaVarint2(&p2, pEnd2, &i2);
101162
101163   switch( mergetype ){
101164     case MERGE_OR:
101165     case MERGE_POS_OR:
101166       while( p1 || p2 ){
101167         if( p2 && p1 && i1==i2 ){
101168           fts3PutDeltaVarint(&p, &iPrev, i1);
101169           if( mergetype==MERGE_POS_OR ) fts3PoslistMerge(&p, &p1, &p2);
101170           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
101171           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
101172         }else if( !p2 || (p1 && i1<i2) ){
101173           fts3PutDeltaVarint(&p, &iPrev, i1);
101174           if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p1);
101175           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
101176         }else{
101177           fts3PutDeltaVarint(&p, &iPrev, i2);
101178           if( mergetype==MERGE_POS_OR ) fts3PoslistCopy(&p, &p2);
101179           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
101180         }
101181       }
101182       break;
101183
101184     case MERGE_AND:
101185       while( p1 && p2 ){
101186         if( i1==i2 ){
101187           fts3PutDeltaVarint(&p, &iPrev, i1);
101188           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
101189           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
101190         }else if( i1<i2 ){
101191           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
101192         }else{
101193           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
101194         }
101195       }
101196       break;
101197
101198     case MERGE_NOT:
101199       while( p1 ){
101200         if( p2 && i1==i2 ){
101201           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
101202           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
101203         }else if( !p2 || i1<i2 ){
101204           fts3PutDeltaVarint(&p, &iPrev, i1);
101205           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
101206         }else{
101207           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
101208         }
101209       }
101210       break;
101211
101212     case MERGE_POS_PHRASE:
101213     case MERGE_PHRASE: {
101214       char **ppPos = (mergetype==MERGE_PHRASE ? 0 : &p);
101215       while( p1 && p2 ){
101216         if( i1==i2 ){
101217           char *pSave = p;
101218           sqlite3_int64 iPrevSave = iPrev;
101219           fts3PutDeltaVarint(&p, &iPrev, i1);
101220           if( 0==fts3PoslistPhraseMerge(ppPos, 1, 0, &p1, &p2) ){
101221             p = pSave;
101222             iPrev = iPrevSave;
101223           }
101224           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
101225           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
101226         }else if( i1<i2 ){
101227           fts3PoslistCopy(0, &p1);
101228           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
101229         }else{
101230           fts3PoslistCopy(0, &p2);
101231           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
101232         }
101233       }
101234       break;
101235     }
101236
101237     default: assert( mergetype==MERGE_POS_NEAR || mergetype==MERGE_NEAR ); {
101238       char *aTmp = 0;
101239       char **ppPos = 0;
101240       if( mergetype==MERGE_POS_NEAR ){
101241         ppPos = &p;
101242         aTmp = sqlite3_malloc(2*(n1+n2+1));
101243         if( !aTmp ){
101244           return SQLITE_NOMEM;
101245         }
101246       }
101247
101248       while( p1 && p2 ){
101249         if( i1==i2 ){
101250           char *pSave = p;
101251           sqlite3_int64 iPrevSave = iPrev;
101252           fts3PutDeltaVarint(&p, &iPrev, i1);
101253
101254           if( !fts3PoslistNearMerge(ppPos, aTmp, nParam1, nParam2, &p1, &p2) ){
101255             iPrev = iPrevSave;
101256             p = pSave;
101257           }
101258
101259           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
101260           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
101261         }else if( i1<i2 ){
101262           fts3PoslistCopy(0, &p1);
101263           fts3GetDeltaVarint2(&p1, pEnd1, &i1);
101264         }else{
101265           fts3PoslistCopy(0, &p2);
101266           fts3GetDeltaVarint2(&p2, pEnd2, &i2);
101267         }
101268       }
101269       sqlite3_free(aTmp);
101270       break;
101271     }
101272   }
101273
101274   *pnBuffer = (int)(p-aBuffer);
101275   return SQLITE_OK;
101276 }
101277
101278 /* 
101279 ** A pointer to an instance of this structure is used as the context 
101280 ** argument to sqlite3Fts3SegReaderIterate()
101281 */
101282 typedef struct TermSelect TermSelect;
101283 struct TermSelect {
101284   int isReqPos;
101285   char *aOutput;                  /* Malloc'd output buffer */
101286   int nOutput;                    /* Size of output in bytes */
101287 };
101288
101289 /*
101290 ** This function is used as the sqlite3Fts3SegReaderIterate() callback when
101291 ** querying the full-text index for a doclist associated with a term or
101292 ** term-prefix.
101293 */
101294 static int fts3TermSelectCb(
101295   Fts3Table *p,                   /* Virtual table object */
101296   void *pContext,                 /* Pointer to TermSelect structure */
101297   char *zTerm,
101298   int nTerm,
101299   char *aDoclist,
101300   int nDoclist
101301 ){
101302   TermSelect *pTS = (TermSelect *)pContext;
101303   int nNew = pTS->nOutput + nDoclist;
101304   char *aNew = sqlite3_malloc(nNew);
101305
101306   UNUSED_PARAMETER(p);
101307   UNUSED_PARAMETER(zTerm);
101308   UNUSED_PARAMETER(nTerm);
101309
101310   if( !aNew ){
101311     return SQLITE_NOMEM;
101312   }
101313
101314   if( pTS->nOutput==0 ){
101315     /* If this is the first term selected, copy the doclist to the output
101316     ** buffer using memcpy(). TODO: Add a way to transfer control of the
101317     ** aDoclist buffer from the caller so as to avoid the memcpy().
101318     */
101319     memcpy(aNew, aDoclist, nDoclist);
101320   }else{
101321     /* The output buffer is not empty. Merge doclist aDoclist with the
101322     ** existing output. This can only happen with prefix-searches (as
101323     ** searches for exact terms return exactly one doclist).
101324     */
101325     int mergetype = (pTS->isReqPos ? MERGE_POS_OR : MERGE_OR);
101326     fts3DoclistMerge(mergetype, 0, 0,
101327         aNew, &nNew, pTS->aOutput, pTS->nOutput, aDoclist, nDoclist
101328     );
101329   }
101330
101331   sqlite3_free(pTS->aOutput);
101332   pTS->aOutput = aNew;
101333   pTS->nOutput = nNew;
101334
101335   return SQLITE_OK;
101336 }
101337
101338 /*
101339 ** This function retreives the doclist for the specified term (or term
101340 ** prefix) from the database. 
101341 **
101342 ** The returned doclist may be in one of two formats, depending on the 
101343 ** value of parameter isReqPos. If isReqPos is zero, then the doclist is
101344 ** a sorted list of delta-compressed docids. If isReqPos is non-zero, 
101345 ** then the returned list is in the same format as is stored in the
101346 ** database without the found length specifier at the start of on-disk
101347 ** doclists.
101348 */
101349 static int fts3TermSelect(
101350   Fts3Table *p,                   /* Virtual table handle */
101351   int iColumn,                    /* Column to query (or -ve for all columns) */
101352   const char *zTerm,              /* Term to query for */
101353   int nTerm,                      /* Size of zTerm in bytes */
101354   int isPrefix,                   /* True for a prefix search */
101355   int isReqPos,                   /* True to include position lists in output */
101356   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
101357   char **ppOut                    /* OUT: Malloced result buffer */
101358 ){
101359   int i;
101360   TermSelect tsc;
101361   Fts3SegFilter filter;           /* Segment term filter configuration */
101362   Fts3SegReader **apSegment;      /* Array of segments to read data from */
101363   int nSegment = 0;               /* Size of apSegment array */
101364   int nAlloc = 16;                /* Allocated size of segment array */
101365   int rc;                         /* Return code */
101366   sqlite3_stmt *pStmt = 0;        /* SQL statement to scan %_segdir table */
101367   int iAge = 0;                   /* Used to assign ages to segments */
101368
101369   apSegment = (Fts3SegReader **)sqlite3_malloc(sizeof(Fts3SegReader*)*nAlloc);
101370   if( !apSegment ) return SQLITE_NOMEM;
101371   rc = sqlite3Fts3SegReaderPending(p, zTerm, nTerm, isPrefix, &apSegment[0]);
101372   if( rc!=SQLITE_OK ) goto finished;
101373   if( apSegment[0] ){
101374     nSegment = 1;
101375   }
101376
101377   /* Loop through the entire %_segdir table. For each segment, create a
101378   ** Fts3SegReader to iterate through the subset of the segment leaves
101379   ** that may contain a term that matches zTerm/nTerm. For non-prefix
101380   ** searches, this is always a single leaf. For prefix searches, this
101381   ** may be a contiguous block of leaves.
101382   **
101383   ** The code in this loop does not actually load any leaves into memory
101384   ** (unless the root node happens to be a leaf). It simply examines the
101385   ** b-tree structure to determine which leaves need to be inspected.
101386   */
101387   rc = sqlite3Fts3AllSegdirs(p, &pStmt);
101388   while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
101389     Fts3SegReader *pNew = 0;
101390     int nRoot = sqlite3_column_bytes(pStmt, 4);
101391     char const *zRoot = sqlite3_column_blob(pStmt, 4);
101392     if( sqlite3_column_int64(pStmt, 1)==0 ){
101393       /* The entire segment is stored on the root node (which must be a
101394       ** leaf). Do not bother inspecting any data in this case, just
101395       ** create a Fts3SegReader to scan the single leaf. 
101396       */
101397       rc = sqlite3Fts3SegReaderNew(p, iAge, 0, 0, 0, zRoot, nRoot, &pNew);
101398     }else{
101399       int rc2;                    /* Return value of sqlite3Fts3ReadBlock() */
101400       sqlite3_int64 i1;           /* Blockid of leaf that may contain zTerm */
101401       rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &i1);
101402       if( rc==SQLITE_OK ){
101403         sqlite3_int64 i2 = sqlite3_column_int64(pStmt, 2);
101404         rc = sqlite3Fts3SegReaderNew(p, iAge, i1, i2, 0, 0, 0, &pNew);
101405       }
101406
101407       /* The following call to ReadBlock() serves to reset the SQL statement
101408       ** used to retrieve blocks of data from the %_segments table. If it is
101409       ** not reset here, then it may remain classified as an active statement 
101410       ** by SQLite, which may lead to "DROP TABLE" or "DETACH" commands 
101411       ** failing.
101412       */ 
101413       rc2 = sqlite3Fts3ReadBlock(p, 0, 0, 0);
101414       if( rc==SQLITE_OK ){
101415         rc = rc2;
101416       }
101417     }
101418     iAge++;
101419
101420     /* If a new Fts3SegReader was allocated, add it to the apSegment array. */
101421     assert( pNew!=0 || rc!=SQLITE_OK );
101422     if( pNew ){
101423       if( nSegment==nAlloc ){
101424         Fts3SegReader **pArray;
101425         nAlloc += 16;
101426         pArray = (Fts3SegReader **)sqlite3_realloc(
101427             apSegment, nAlloc*sizeof(Fts3SegReader *)
101428         );
101429         if( !pArray ){
101430           sqlite3Fts3SegReaderFree(p, pNew);
101431           rc = SQLITE_NOMEM;
101432           goto finished;
101433         }
101434         apSegment = pArray;
101435       }
101436       apSegment[nSegment++] = pNew;
101437     }
101438   }
101439   if( rc!=SQLITE_DONE ){
101440     assert( rc!=SQLITE_OK );
101441     goto finished;
101442   }
101443
101444   memset(&tsc, 0, sizeof(TermSelect));
101445   tsc.isReqPos = isReqPos;
101446
101447   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY 
101448         | (isPrefix ? FTS3_SEGMENT_PREFIX : 0)
101449         | (isReqPos ? FTS3_SEGMENT_REQUIRE_POS : 0)
101450         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
101451   filter.iCol = iColumn;
101452   filter.zTerm = zTerm;
101453   filter.nTerm = nTerm;
101454
101455   rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment, &filter,
101456       fts3TermSelectCb, (void *)&tsc
101457   );
101458
101459   if( rc==SQLITE_OK ){
101460     *ppOut = tsc.aOutput;
101461     *pnOut = tsc.nOutput;
101462   }else{
101463     sqlite3_free(tsc.aOutput);
101464   }
101465
101466 finished:
101467   sqlite3_reset(pStmt);
101468   for(i=0; i<nSegment; i++){
101469     sqlite3Fts3SegReaderFree(p, apSegment[i]);
101470   }
101471   sqlite3_free(apSegment);
101472   return rc;
101473 }
101474
101475
101476 /* 
101477 ** Return a DocList corresponding to the phrase *pPhrase.
101478 */
101479 static int fts3PhraseSelect(
101480   Fts3Table *p,                   /* Virtual table handle */
101481   Fts3Phrase *pPhrase,            /* Phrase to return a doclist for */
101482   int isReqPos,                   /* True if output should contain positions */
101483   char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
101484   int *pnOut                      /* OUT: Size of buffer at *paOut */
101485 ){
101486   char *pOut = 0;
101487   int nOut = 0;
101488   int rc = SQLITE_OK;
101489   int ii;
101490   int iCol = pPhrase->iColumn;
101491   int isTermPos = (pPhrase->nToken>1 || isReqPos);
101492
101493   for(ii=0; ii<pPhrase->nToken; ii++){
101494     struct PhraseToken *pTok = &pPhrase->aToken[ii];
101495     char *z = pTok->z;            /* Next token of the phrase */
101496     int n = pTok->n;              /* Size of z in bytes */
101497     int isPrefix = pTok->isPrefix;/* True if token is a prefix */
101498     char *pList;                  /* Pointer to token doclist */
101499     int nList;                    /* Size of buffer at pList */
101500
101501     rc = fts3TermSelect(p, iCol, z, n, isPrefix, isTermPos, &nList, &pList);
101502     if( rc!=SQLITE_OK ) break;
101503
101504     if( ii==0 ){
101505       pOut = pList;
101506       nOut = nList;
101507     }else{
101508       /* Merge the new term list and the current output. If this is the
101509       ** last term in the phrase, and positions are not required in the
101510       ** output of this function, the positions can be dropped as part
101511       ** of this merge. Either way, the result of this merge will be
101512       ** smaller than nList bytes. The code in fts3DoclistMerge() is written
101513       ** so that it is safe to use pList as the output as well as an input
101514       ** in this case.
101515       */
101516       int mergetype = MERGE_POS_PHRASE;
101517       if( ii==pPhrase->nToken-1 && !isReqPos ){
101518         mergetype = MERGE_PHRASE;
101519       }
101520       fts3DoclistMerge(mergetype, 0, 0, pList, &nOut, pOut, nOut, pList, nList);
101521       sqlite3_free(pOut);
101522       pOut = pList;
101523     }
101524     assert( nOut==0 || pOut!=0 );
101525   }
101526
101527   if( rc==SQLITE_OK ){
101528     *paOut = pOut;
101529     *pnOut = nOut;
101530   }else{
101531     sqlite3_free(pOut);
101532   }
101533   return rc;
101534 }
101535
101536 static int fts3NearMerge(
101537   int mergetype,                  /* MERGE_POS_NEAR or MERGE_NEAR */
101538   int nNear,                      /* Parameter to NEAR operator */
101539   int nTokenLeft,                 /* Number of tokens in LHS phrase arg */
101540   char *aLeft,                    /* Doclist for LHS (incl. positions) */
101541   int nLeft,                      /* Size of LHS doclist in bytes */
101542   int nTokenRight,                /* As nTokenLeft */
101543   char *aRight,                   /* As aLeft */
101544   int nRight,                     /* As nRight */
101545   char **paOut,                   /* OUT: Results of merge (malloced) */
101546   int *pnOut                      /* OUT: Sized of output buffer */
101547 ){
101548   char *aOut;
101549   int rc;
101550
101551   assert( mergetype==MERGE_POS_NEAR || MERGE_NEAR );
101552
101553   aOut = sqlite3_malloc(nLeft+nRight+1);
101554   if( aOut==0 ){
101555     rc = SQLITE_NOMEM;
101556   }else{
101557     rc = fts3DoclistMerge(mergetype, nNear+nTokenRight, nNear+nTokenLeft, 
101558       aOut, pnOut, aLeft, nLeft, aRight, nRight
101559     );
101560     if( rc!=SQLITE_OK ){
101561       sqlite3_free(aOut);
101562       aOut = 0;
101563     }
101564   }
101565
101566   *paOut = aOut;
101567   return rc;
101568 }
101569
101570 SQLITE_PRIVATE int sqlite3Fts3ExprNearTrim(Fts3Expr *pLeft, Fts3Expr *pRight, int nNear){
101571   int rc;
101572   if( pLeft->aDoclist==0 || pRight->aDoclist==0 ){
101573     sqlite3_free(pLeft->aDoclist);
101574     sqlite3_free(pRight->aDoclist);
101575     pRight->aDoclist = 0;
101576     pLeft->aDoclist = 0;
101577     rc = SQLITE_OK;
101578   }else{
101579     char *aOut;
101580     int nOut;
101581
101582     rc = fts3NearMerge(MERGE_POS_NEAR, nNear, 
101583         pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
101584         pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
101585         &aOut, &nOut
101586     );
101587     if( rc!=SQLITE_OK ) return rc;
101588     sqlite3_free(pRight->aDoclist);
101589     pRight->aDoclist = aOut;
101590     pRight->nDoclist = nOut;
101591
101592     rc = fts3NearMerge(MERGE_POS_NEAR, nNear, 
101593         pRight->pPhrase->nToken, pRight->aDoclist, pRight->nDoclist,
101594         pLeft->pPhrase->nToken, pLeft->aDoclist, pLeft->nDoclist,
101595         &aOut, &nOut
101596     );
101597     sqlite3_free(pLeft->aDoclist);
101598     pLeft->aDoclist = aOut;
101599     pLeft->nDoclist = nOut;
101600   }
101601   return rc;
101602 }
101603
101604 /*
101605 ** Evaluate the full-text expression pExpr against fts3 table pTab. Store
101606 ** the resulting doclist in *paOut and *pnOut.
101607 */
101608 static int evalFts3Expr(
101609   Fts3Table *p,                   /* Virtual table handle */
101610   Fts3Expr *pExpr,                /* Parsed fts3 expression */
101611   char **paOut,                   /* OUT: Pointer to malloc'd result buffer */
101612   int *pnOut,                     /* OUT: Size of buffer at *paOut */
101613   int isReqPos                    /* Require positions in output buffer */
101614 ){
101615   int rc = SQLITE_OK;             /* Return code */
101616
101617   /* Zero the output parameters. */
101618   *paOut = 0;
101619   *pnOut = 0;
101620
101621   if( pExpr ){
101622     assert( pExpr->eType==FTSQUERY_PHRASE 
101623          || pExpr->eType==FTSQUERY_NEAR 
101624          || isReqPos==0
101625     );
101626     if( pExpr->eType==FTSQUERY_PHRASE ){
101627       rc = fts3PhraseSelect(p, pExpr->pPhrase, 
101628           isReqPos || (pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR),
101629           paOut, pnOut
101630       );
101631     }else{
101632       char *aLeft;
101633       char *aRight;
101634       int nLeft;
101635       int nRight;
101636
101637       if( 0==(rc = evalFts3Expr(p, pExpr->pRight, &aRight, &nRight, isReqPos))
101638        && 0==(rc = evalFts3Expr(p, pExpr->pLeft, &aLeft, &nLeft, isReqPos))
101639       ){
101640         assert( pExpr->eType==FTSQUERY_NEAR || pExpr->eType==FTSQUERY_OR     
101641             || pExpr->eType==FTSQUERY_AND  || pExpr->eType==FTSQUERY_NOT
101642         );
101643         switch( pExpr->eType ){
101644           case FTSQUERY_NEAR: {
101645             Fts3Expr *pLeft;
101646             Fts3Expr *pRight;
101647             int mergetype = isReqPos ? MERGE_POS_NEAR : MERGE_NEAR;
101648            
101649             if( pExpr->pParent && pExpr->pParent->eType==FTSQUERY_NEAR ){
101650               mergetype = MERGE_POS_NEAR;
101651             }
101652             pLeft = pExpr->pLeft;
101653             while( pLeft->eType==FTSQUERY_NEAR ){ 
101654               pLeft=pLeft->pRight;
101655             }
101656             pRight = pExpr->pRight;
101657             assert( pRight->eType==FTSQUERY_PHRASE );
101658             assert( pLeft->eType==FTSQUERY_PHRASE );
101659
101660             rc = fts3NearMerge(mergetype, pExpr->nNear, 
101661                 pLeft->pPhrase->nToken, aLeft, nLeft,
101662                 pRight->pPhrase->nToken, aRight, nRight,
101663                 paOut, pnOut
101664             );
101665             sqlite3_free(aLeft);
101666             break;
101667           }
101668
101669           case FTSQUERY_OR: {
101670             /* Allocate a buffer for the output. The maximum size is the
101671             ** sum of the sizes of the two input buffers. The +1 term is
101672             ** so that a buffer of zero bytes is never allocated - this can
101673             ** cause fts3DoclistMerge() to incorrectly return SQLITE_NOMEM.
101674             */
101675             char *aBuffer = sqlite3_malloc(nRight+nLeft+1);
101676             rc = fts3DoclistMerge(MERGE_OR, 0, 0, aBuffer, pnOut,
101677                 aLeft, nLeft, aRight, nRight
101678             );
101679             *paOut = aBuffer;
101680             sqlite3_free(aLeft);
101681             break;
101682           }
101683
101684           default: {
101685             assert( FTSQUERY_NOT==MERGE_NOT && FTSQUERY_AND==MERGE_AND );
101686             fts3DoclistMerge(pExpr->eType, 0, 0, aLeft, pnOut,
101687                 aLeft, nLeft, aRight, nRight
101688             );
101689             *paOut = aLeft;
101690             break;
101691           }
101692         }
101693       }
101694       sqlite3_free(aRight);
101695     }
101696   }
101697
101698   return rc;
101699 }
101700
101701 /*
101702 ** This is the xFilter interface for the virtual table.  See
101703 ** the virtual table xFilter method documentation for additional
101704 ** information.
101705 **
101706 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
101707 ** the %_content table.
101708 **
101709 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
101710 ** in the %_content table.
101711 **
101712 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
101713 ** column on the left-hand side of the MATCH operator is column
101714 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
101715 ** side of the MATCH operator.
101716 */
101717 /* TODO(shess) Upgrade the cursor initialization and destruction to
101718 ** account for fts3FilterMethod() being called multiple times on the
101719 ** same cursor. The current solution is very fragile. Apply fix to
101720 ** fts3 as appropriate.
101721 */
101722 static int fts3FilterMethod(
101723   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
101724   int idxNum,                     /* Strategy index */
101725   const char *idxStr,             /* Unused */
101726   int nVal,                       /* Number of elements in apVal */
101727   sqlite3_value **apVal           /* Arguments for the indexing scheme */
101728 ){
101729   const char *azSql[] = {
101730     "SELECT * FROM %Q.'%q_content' WHERE docid = ?", /* non-full-table-scan */
101731     "SELECT * FROM %Q.'%q_content'",                 /* full-table-scan */
101732   };
101733   int rc;                         /* Return code */
101734   char *zSql;                     /* SQL statement used to access %_content */
101735   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
101736   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
101737
101738   UNUSED_PARAMETER(idxStr);
101739   UNUSED_PARAMETER(nVal);
101740
101741   assert( idxNum>=0 && idxNum<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
101742   assert( nVal==0 || nVal==1 );
101743   assert( (nVal==0)==(idxNum==FTS3_FULLSCAN_SEARCH) );
101744
101745   /* In case the cursor has been used before, clear it now. */
101746   sqlite3_finalize(pCsr->pStmt);
101747   sqlite3_free(pCsr->aDoclist);
101748   sqlite3Fts3ExprFree(pCsr->pExpr);
101749   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
101750
101751   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
101752   ** statement loops through all rows of the %_content table. For a
101753   ** full-text query or docid lookup, the statement retrieves a single
101754   ** row by docid.
101755   */
101756   zSql = sqlite3_mprintf(azSql[idxNum==FTS3_FULLSCAN_SEARCH], p->zDb, p->zName);
101757   if( !zSql ){
101758     rc = SQLITE_NOMEM;
101759   }else{
101760     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
101761     sqlite3_free(zSql);
101762   }
101763   if( rc!=SQLITE_OK ) return rc;
101764   pCsr->eSearch = (i16)idxNum;
101765
101766   if( idxNum==FTS3_DOCID_SEARCH ){
101767     rc = sqlite3_bind_value(pCsr->pStmt, 1, apVal[0]);
101768   }else if( idxNum!=FTS3_FULLSCAN_SEARCH ){
101769     int iCol = idxNum-FTS3_FULLTEXT_SEARCH;
101770     const char *zQuery = (const char *)sqlite3_value_text(apVal[0]);
101771
101772     if( zQuery==0 && sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
101773       return SQLITE_NOMEM;
101774     }
101775
101776     rc = sqlite3Fts3ExprParse(p->pTokenizer, p->azColumn, p->nColumn, 
101777         iCol, zQuery, -1, &pCsr->pExpr
101778     );
101779     if( rc!=SQLITE_OK ){
101780       if( rc==SQLITE_ERROR ){
101781         p->base.zErrMsg = sqlite3_mprintf("malformed MATCH expression: [%s]",
101782                                           zQuery);
101783       }
101784       return rc;
101785     }
101786
101787     rc = evalFts3Expr(p, pCsr->pExpr, &pCsr->aDoclist, &pCsr->nDoclist, 0);
101788     pCsr->pNextId = pCsr->aDoclist;
101789     pCsr->iPrevId = 0;
101790   }
101791
101792   if( rc!=SQLITE_OK ) return rc;
101793   return fts3NextMethod(pCursor);
101794 }
101795
101796 /* 
101797 ** This is the xEof method of the virtual table. SQLite calls this 
101798 ** routine to find out if it has reached the end of a result set.
101799 */
101800 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
101801   return ((Fts3Cursor *)pCursor)->isEof;
101802 }
101803
101804 /* 
101805 ** This is the xRowid method. The SQLite core calls this routine to
101806 ** retrieve the rowid for the current row of the result set. fts3
101807 ** exposes %_content.docid as the rowid for the virtual table. The
101808 ** rowid should be written to *pRowid.
101809 */
101810 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
101811   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
101812   if( pCsr->aDoclist ){
101813     *pRowid = pCsr->iPrevId;
101814   }else{
101815     *pRowid = sqlite3_column_int64(pCsr->pStmt, 0);
101816   }
101817   return SQLITE_OK;
101818 }
101819
101820 /* 
101821 ** This is the xColumn method, called by SQLite to request a value from
101822 ** the row that the supplied cursor currently points to.
101823 */
101824 static int fts3ColumnMethod(
101825   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
101826   sqlite3_context *pContext,      /* Context for sqlite3_result_xxx() calls */
101827   int iCol                        /* Index of column to read value from */
101828 ){
101829   int rc;                         /* Return Code */
101830   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
101831   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
101832
101833   /* The column value supplied by SQLite must be in range. */
101834   assert( iCol>=0 && iCol<=p->nColumn+1 );
101835
101836   if( iCol==p->nColumn+1 ){
101837     /* This call is a request for the "docid" column. Since "docid" is an 
101838     ** alias for "rowid", use the xRowid() method to obtain the value.
101839     */
101840     sqlite3_int64 iRowid;
101841     rc = fts3RowidMethod(pCursor, &iRowid);
101842     sqlite3_result_int64(pContext, iRowid);
101843   }else if( iCol==p->nColumn ){
101844     /* The extra column whose name is the same as the table.
101845     ** Return a blob which is a pointer to the cursor.
101846     */
101847     sqlite3_result_blob(pContext, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
101848     rc = SQLITE_OK;
101849   }else{
101850     rc = fts3CursorSeek(0, pCsr);
101851     if( rc==SQLITE_OK ){
101852       sqlite3_result_value(pContext, sqlite3_column_value(pCsr->pStmt, iCol+1));
101853     }
101854   }
101855   return rc;
101856 }
101857
101858 /* 
101859 ** This function is the implementation of the xUpdate callback used by 
101860 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
101861 ** inserted, updated or deleted.
101862 */
101863 static int fts3UpdateMethod(
101864   sqlite3_vtab *pVtab,            /* Virtual table handle */
101865   int nArg,                       /* Size of argument array */
101866   sqlite3_value **apVal,          /* Array of arguments */
101867   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
101868 ){
101869   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
101870 }
101871
101872 /*
101873 ** Implementation of xSync() method. Flush the contents of the pending-terms
101874 ** hash-table to the database.
101875 */
101876 static int fts3SyncMethod(sqlite3_vtab *pVtab){
101877   return sqlite3Fts3PendingTermsFlush((Fts3Table *)pVtab);
101878 }
101879
101880 /*
101881 ** Implementation of xBegin() method. This is a no-op.
101882 */
101883 static int fts3BeginMethod(sqlite3_vtab *pVtab){
101884   UNUSED_PARAMETER(pVtab);
101885   assert( ((Fts3Table *)pVtab)->nPendingData==0 );
101886   return SQLITE_OK;
101887 }
101888
101889 /*
101890 ** Implementation of xCommit() method. This is a no-op. The contents of
101891 ** the pending-terms hash-table have already been flushed into the database
101892 ** by fts3SyncMethod().
101893 */
101894 static int fts3CommitMethod(sqlite3_vtab *pVtab){
101895   UNUSED_PARAMETER(pVtab);
101896   assert( ((Fts3Table *)pVtab)->nPendingData==0 );
101897   return SQLITE_OK;
101898 }
101899
101900 /*
101901 ** Implementation of xRollback(). Discard the contents of the pending-terms
101902 ** hash-table. Any changes made to the database are reverted by SQLite.
101903 */
101904 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
101905   sqlite3Fts3PendingTermsClear((Fts3Table *)pVtab);
101906   return SQLITE_OK;
101907 }
101908
101909 /*
101910 ** Load the doclist associated with expression pExpr to pExpr->aDoclist.
101911 ** The loaded doclist contains positions as well as the document ids.
101912 ** This is used by the matchinfo(), snippet() and offsets() auxillary
101913 ** functions.
101914 */
101915 SQLITE_PRIVATE int sqlite3Fts3ExprLoadDoclist(Fts3Table *pTab, Fts3Expr *pExpr){
101916   return evalFts3Expr(pTab, pExpr, &pExpr->aDoclist, &pExpr->nDoclist, 1);
101917 }
101918
101919 /*
101920 ** After ExprLoadDoclist() (see above) has been called, this function is
101921 ** used to iterate/search through the position lists that make up the doclist
101922 ** stored in pExpr->aDoclist.
101923 */
101924 SQLITE_PRIVATE char *sqlite3Fts3FindPositions(
101925   Fts3Expr *pExpr,                /* Access this expressions doclist */
101926   sqlite3_int64 iDocid,           /* Docid associated with requested pos-list */
101927   int iCol                        /* Column of requested pos-list */
101928 ){
101929   assert( pExpr->isLoaded );
101930   if( pExpr->aDoclist ){
101931     char *pEnd = &pExpr->aDoclist[pExpr->nDoclist];
101932     char *pCsr = pExpr->pCurrent;
101933
101934     assert( pCsr );
101935     while( pCsr<pEnd ){
101936       if( pExpr->iCurrent<iDocid ){
101937         fts3PoslistCopy(0, &pCsr);
101938         if( pCsr<pEnd ){
101939           fts3GetDeltaVarint(&pCsr, &pExpr->iCurrent);
101940         }
101941         pExpr->pCurrent = pCsr;
101942       }else{
101943         if( pExpr->iCurrent==iDocid ){
101944           int iThis = 0;
101945           if( iCol<0 ){
101946             /* If iCol is negative, return a pointer to the start of the
101947             ** position-list (instead of a pointer to the start of a list
101948             ** of offsets associated with a specific column).
101949             */
101950             return pCsr;
101951           }
101952           while( iThis<iCol ){
101953             fts3ColumnlistCopy(0, &pCsr);
101954             if( *pCsr==0x00 ) return 0;
101955             pCsr++;
101956             pCsr += sqlite3Fts3GetVarint32(pCsr, &iThis);
101957           }
101958           if( iCol==iThis && (*pCsr&0xFE) ) return pCsr;
101959         }
101960         return 0;
101961       }
101962     }
101963   }
101964
101965   return 0;
101966 }
101967
101968 /*
101969 ** Helper function used by the implementation of the overloaded snippet(),
101970 ** offsets() and optimize() SQL functions.
101971 **
101972 ** If the value passed as the third argument is a blob of size
101973 ** sizeof(Fts3Cursor*), then the blob contents are copied to the 
101974 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
101975 ** message is written to context pContext and SQLITE_ERROR returned. The
101976 ** string passed via zFunc is used as part of the error message.
101977 */
101978 static int fts3FunctionArg(
101979   sqlite3_context *pContext,      /* SQL function call context */
101980   const char *zFunc,              /* Function name */
101981   sqlite3_value *pVal,            /* argv[0] passed to function */
101982   Fts3Cursor **ppCsr         /* OUT: Store cursor handle here */
101983 ){
101984   Fts3Cursor *pRet;
101985   if( sqlite3_value_type(pVal)!=SQLITE_BLOB 
101986    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
101987   ){
101988     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
101989     sqlite3_result_error(pContext, zErr, -1);
101990     sqlite3_free(zErr);
101991     return SQLITE_ERROR;
101992   }
101993   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
101994   *ppCsr = pRet;
101995   return SQLITE_OK;
101996 }
101997
101998 /*
101999 ** Implementation of the snippet() function for FTS3
102000 */
102001 static void fts3SnippetFunc(
102002   sqlite3_context *pContext,      /* SQLite function call context */
102003   int nVal,                       /* Size of apVal[] array */
102004   sqlite3_value **apVal           /* Array of arguments */
102005 ){
102006   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
102007   const char *zStart = "<b>";
102008   const char *zEnd = "</b>";
102009   const char *zEllipsis = "<b>...</b>";
102010   int iCol = -1;
102011   int nToken = 15;                /* Default number of tokens in snippet */
102012
102013   /* There must be at least one argument passed to this function (otherwise
102014   ** the non-overloaded version would have been called instead of this one).
102015   */
102016   assert( nVal>=1 );
102017
102018   if( nVal>6 ){
102019     sqlite3_result_error(pContext, 
102020         "wrong number of arguments to function snippet()", -1);
102021     return;
102022   }
102023   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
102024
102025   switch( nVal ){
102026     case 6: nToken = sqlite3_value_int(apVal[5]);
102027     case 5: iCol = sqlite3_value_int(apVal[4]);
102028     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
102029     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
102030     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
102031   }
102032   if( !zEllipsis || !zEnd || !zStart ){
102033     sqlite3_result_error_nomem(pContext);
102034   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
102035     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
102036   }
102037 }
102038
102039 /*
102040 ** Implementation of the offsets() function for FTS3
102041 */
102042 static void fts3OffsetsFunc(
102043   sqlite3_context *pContext,      /* SQLite function call context */
102044   int nVal,                       /* Size of argument array */
102045   sqlite3_value **apVal           /* Array of arguments */
102046 ){
102047   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
102048
102049   UNUSED_PARAMETER(nVal);
102050
102051   assert( nVal==1 );
102052   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
102053   assert( pCsr );
102054   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
102055     sqlite3Fts3Offsets(pContext, pCsr);
102056   }
102057 }
102058
102059 /* 
102060 ** Implementation of the special optimize() function for FTS3. This 
102061 ** function merges all segments in the database to a single segment.
102062 ** Example usage is:
102063 **
102064 **   SELECT optimize(t) FROM t LIMIT 1;
102065 **
102066 ** where 't' is the name of an FTS3 table.
102067 */
102068 static void fts3OptimizeFunc(
102069   sqlite3_context *pContext,      /* SQLite function call context */
102070   int nVal,                       /* Size of argument array */
102071   sqlite3_value **apVal           /* Array of arguments */
102072 ){
102073   int rc;                         /* Return code */
102074   Fts3Table *p;                   /* Virtual table handle */
102075   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
102076
102077   UNUSED_PARAMETER(nVal);
102078
102079   assert( nVal==1 );
102080   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
102081   p = (Fts3Table *)pCursor->base.pVtab;
102082   assert( p );
102083
102084   rc = sqlite3Fts3Optimize(p);
102085
102086   switch( rc ){
102087     case SQLITE_OK:
102088       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
102089       break;
102090     case SQLITE_DONE:
102091       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
102092       break;
102093     default:
102094       sqlite3_result_error_code(pContext, rc);
102095       break;
102096   }
102097 }
102098
102099 /*
102100 ** Implementation of the matchinfo() function for FTS3
102101 */
102102 static void fts3MatchinfoFunc(
102103   sqlite3_context *pContext,      /* SQLite function call context */
102104   int nVal,                       /* Size of argument array */
102105   sqlite3_value **apVal           /* Array of arguments */
102106 ){
102107   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
102108
102109   if( nVal!=1 ){
102110     sqlite3_result_error(pContext,
102111         "wrong number of arguments to function matchinfo()", -1);
102112     return;
102113   }
102114
102115   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
102116     sqlite3Fts3Matchinfo(pContext, pCsr);
102117   }
102118 }
102119
102120 /*
102121 ** This routine implements the xFindFunction method for the FTS3
102122 ** virtual table.
102123 */
102124 static int fts3FindFunctionMethod(
102125   sqlite3_vtab *pVtab,            /* Virtual table handle */
102126   int nArg,                       /* Number of SQL function arguments */
102127   const char *zName,              /* Name of SQL function */
102128   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
102129   void **ppArg                    /* Unused */
102130 ){
102131   struct Overloaded {
102132     const char *zName;
102133     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
102134   } aOverload[] = {
102135     { "snippet", fts3SnippetFunc },
102136     { "offsets", fts3OffsetsFunc },
102137     { "optimize", fts3OptimizeFunc },
102138     { "matchinfo", fts3MatchinfoFunc },
102139   };
102140   int i;                          /* Iterator variable */
102141
102142   UNUSED_PARAMETER(pVtab);
102143   UNUSED_PARAMETER(nArg);
102144   UNUSED_PARAMETER(ppArg);
102145
102146   for(i=0; i<SizeofArray(aOverload); i++){
102147     if( strcmp(zName, aOverload[i].zName)==0 ){
102148       *pxFunc = aOverload[i].xFunc;
102149       return 1;
102150     }
102151   }
102152
102153   /* No function of the specified name was found. Return 0. */
102154   return 0;
102155 }
102156
102157 /*
102158 ** Implementation of FTS3 xRename method. Rename an fts3 table.
102159 */
102160 static int fts3RenameMethod(
102161   sqlite3_vtab *pVtab,            /* Virtual table handle */
102162   const char *zName               /* New name of table */
102163 ){
102164   Fts3Table *p = (Fts3Table *)pVtab;
102165   sqlite3 *db;                    /* Database connection */
102166   int rc;                         /* Return Code */
102167  
102168   db = p->db;
102169   rc = SQLITE_OK;
102170   fts3DbExec(&rc, db,
102171     "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
102172     p->zDb, p->zName, zName
102173   );
102174   if( rc==SQLITE_ERROR ) rc = SQLITE_OK;
102175   if( p->bHasDocsize ){
102176     fts3DbExec(&rc, db,
102177       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
102178       p->zDb, p->zName, zName
102179     );
102180     fts3DbExec(&rc, db,
102181       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
102182       p->zDb, p->zName, zName
102183     );
102184   }
102185   fts3DbExec(&rc, db,
102186     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
102187     p->zDb, p->zName, zName
102188   );
102189   fts3DbExec(&rc, db,
102190     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
102191     p->zDb, p->zName, zName
102192   );
102193   return rc;
102194 }
102195
102196 static const sqlite3_module fts3Module = {
102197   /* iVersion      */ 0,
102198   /* xCreate       */ fts3CreateMethod,
102199   /* xConnect      */ fts3ConnectMethod,
102200   /* xBestIndex    */ fts3BestIndexMethod,
102201   /* xDisconnect   */ fts3DisconnectMethod,
102202   /* xDestroy      */ fts3DestroyMethod,
102203   /* xOpen         */ fts3OpenMethod,
102204   /* xClose        */ fulltextClose,
102205   /* xFilter       */ fts3FilterMethod,
102206   /* xNext         */ fts3NextMethod,
102207   /* xEof          */ fts3EofMethod,
102208   /* xColumn       */ fts3ColumnMethod,
102209   /* xRowid        */ fts3RowidMethod,
102210   /* xUpdate       */ fts3UpdateMethod,
102211   /* xBegin        */ fts3BeginMethod,
102212   /* xSync         */ fts3SyncMethod,
102213   /* xCommit       */ fts3CommitMethod,
102214   /* xRollback     */ fts3RollbackMethod,
102215   /* xFindFunction */ fts3FindFunctionMethod,
102216   /* xRename */       fts3RenameMethod,
102217 };
102218
102219 /*
102220 ** This function is registered as the module destructor (called when an
102221 ** FTS3 enabled database connection is closed). It frees the memory
102222 ** allocated for the tokenizer hash table.
102223 */
102224 static void hashDestroy(void *p){
102225   Fts3Hash *pHash = (Fts3Hash *)p;
102226   sqlite3Fts3HashClear(pHash);
102227   sqlite3_free(pHash);
102228 }
102229
102230 /*
102231 ** The fts3 built-in tokenizers - "simple" and "porter" - are implemented
102232 ** in files fts3_tokenizer1.c and fts3_porter.c respectively. The following
102233 ** two forward declarations are for functions declared in these files
102234 ** used to retrieve the respective implementations.
102235 **
102236 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
102237 ** to by the argument to point a the "simple" tokenizer implementation.
102238 ** Function ...PorterTokenizerModule() sets *pModule to point to the
102239 ** porter tokenizer/stemmer implementation.
102240 */
102241 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
102242 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
102243 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
102244
102245 /*
102246 ** Initialise the fts3 extension. If this extension is built as part
102247 ** of the sqlite library, then this function is called directly by
102248 ** SQLite. If fts3 is built as a dynamically loadable extension, this
102249 ** function is called by the sqlite3_extension_init() entry point.
102250 */
102251 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
102252   int rc = SQLITE_OK;
102253   Fts3Hash *pHash = 0;
102254   const sqlite3_tokenizer_module *pSimple = 0;
102255   const sqlite3_tokenizer_module *pPorter = 0;
102256
102257 #ifdef SQLITE_ENABLE_ICU
102258   const sqlite3_tokenizer_module *pIcu = 0;
102259   sqlite3Fts3IcuTokenizerModule(&pIcu);
102260 #endif
102261
102262   sqlite3Fts3SimpleTokenizerModule(&pSimple);
102263   sqlite3Fts3PorterTokenizerModule(&pPorter);
102264
102265   /* Allocate and initialise the hash-table used to store tokenizers. */
102266   pHash = sqlite3_malloc(sizeof(Fts3Hash));
102267   if( !pHash ){
102268     rc = SQLITE_NOMEM;
102269   }else{
102270     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
102271   }
102272
102273   /* Load the built-in tokenizers into the hash table */
102274   if( rc==SQLITE_OK ){
102275     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
102276      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
102277 #ifdef SQLITE_ENABLE_ICU
102278      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
102279 #endif
102280     ){
102281       rc = SQLITE_NOMEM;
102282     }
102283   }
102284
102285 #ifdef SQLITE_TEST
102286   if( rc==SQLITE_OK ){
102287     rc = sqlite3Fts3ExprInitTestInterface(db);
102288   }
102289 #endif
102290
102291   /* Create the virtual table wrapper around the hash-table and overload 
102292   ** the two scalar functions. If this is successful, register the
102293   ** module with sqlite.
102294   */
102295   if( SQLITE_OK==rc 
102296    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
102297    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
102298    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
102299    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", -1))
102300    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
102301   ){
102302     rc = sqlite3_create_module_v2(
102303         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
102304     );
102305     if( rc==SQLITE_OK ){
102306       rc = sqlite3_create_module_v2(
102307           db, "fts4", &fts3Module, (void *)pHash, 0
102308       );
102309     }
102310     return rc;
102311   }
102312
102313   /* An error has occurred. Delete the hash table and return the error code. */
102314   assert( rc!=SQLITE_OK );
102315   if( pHash ){
102316     sqlite3Fts3HashClear(pHash);
102317     sqlite3_free(pHash);
102318   }
102319   return rc;
102320 }
102321
102322 #if !SQLITE_CORE
102323 SQLITE_API int sqlite3_extension_init(
102324   sqlite3 *db, 
102325   char **pzErrMsg,
102326   const sqlite3_api_routines *pApi
102327 ){
102328   SQLITE_EXTENSION_INIT2(pApi)
102329   return sqlite3Fts3Init(db);
102330 }
102331 #endif
102332
102333 #endif
102334
102335 /************** End of fts3.c ************************************************/
102336 /************** Begin file fts3_expr.c ***************************************/
102337 /*
102338 ** 2008 Nov 28
102339 **
102340 ** The author disclaims copyright to this source code.  In place of
102341 ** a legal notice, here is a blessing:
102342 **
102343 **    May you do good and not evil.
102344 **    May you find forgiveness for yourself and forgive others.
102345 **    May you share freely, never taking more than you give.
102346 **
102347 ******************************************************************************
102348 **
102349 ** This module contains code that implements a parser for fts3 query strings
102350 ** (the right-hand argument to the MATCH operator). Because the supported 
102351 ** syntax is relatively simple, the whole tokenizer/parser system is
102352 ** hand-coded. 
102353 */
102354 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
102355
102356 /*
102357 ** By default, this module parses the legacy syntax that has been 
102358 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
102359 ** is defined, then it uses the new syntax. The differences between
102360 ** the new and the old syntaxes are:
102361 **
102362 **  a) The new syntax supports parenthesis. The old does not.
102363 **
102364 **  b) The new syntax supports the AND and NOT operators. The old does not.
102365 **
102366 **  c) The old syntax supports the "-" token qualifier. This is not 
102367 **     supported by the new syntax (it is replaced by the NOT operator).
102368 **
102369 **  d) When using the old syntax, the OR operator has a greater precedence
102370 **     than an implicit AND. When using the new, both implicity and explicit
102371 **     AND operators have a higher precedence than OR.
102372 **
102373 ** If compiled with SQLITE_TEST defined, then this module exports the
102374 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
102375 ** to zero causes the module to use the old syntax. If it is set to 
102376 ** non-zero the new syntax is activated. This is so both syntaxes can
102377 ** be tested using a single build of testfixture.
102378 **
102379 ** The following describes the syntax supported by the fts3 MATCH
102380 ** operator in a similar format to that used by the lemon parser
102381 ** generator. This module does not use actually lemon, it uses a
102382 ** custom parser.
102383 **
102384 **   query ::= andexpr (OR andexpr)*.
102385 **
102386 **   andexpr ::= notexpr (AND? notexpr)*.
102387 **
102388 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
102389 **   notexpr ::= LP query RP.
102390 **
102391 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
102392 **
102393 **   distance_opt ::= .
102394 **   distance_opt ::= / INTEGER.
102395 **
102396 **   phrase ::= TOKEN.
102397 **   phrase ::= COLUMN:TOKEN.
102398 **   phrase ::= "TOKEN TOKEN TOKEN...".
102399 */
102400
102401 #ifdef SQLITE_TEST
102402 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
102403 #else
102404 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
102405 #  define sqlite3_fts3_enable_parentheses 1
102406 # else
102407 #  define sqlite3_fts3_enable_parentheses 0
102408 # endif
102409 #endif
102410
102411 /*
102412 ** Default span for NEAR operators.
102413 */
102414 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
102415
102416
102417 typedef struct ParseContext ParseContext;
102418 struct ParseContext {
102419   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
102420   const char **azCol;                 /* Array of column names for fts3 table */
102421   int nCol;                           /* Number of entries in azCol[] */
102422   int iDefaultCol;                    /* Default column to query */
102423   sqlite3_context *pCtx;              /* Write error message here */
102424   int nNest;                          /* Number of nested brackets */
102425 };
102426
102427 /*
102428 ** This function is equivalent to the standard isspace() function. 
102429 **
102430 ** The standard isspace() can be awkward to use safely, because although it
102431 ** is defined to accept an argument of type int, its behaviour when passed
102432 ** an integer that falls outside of the range of the unsigned char type
102433 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
102434 ** is defined to accept an argument of type char, and always returns 0 for
102435 ** any values that fall outside of the range of the unsigned char type (i.e.
102436 ** negative values).
102437 */
102438 static int fts3isspace(char c){
102439   return (c&0x80)==0 ? isspace(c) : 0;
102440 }
102441
102442 /*
102443 ** Extract the next token from buffer z (length n) using the tokenizer
102444 ** and other information (column names etc.) in pParse. Create an Fts3Expr
102445 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
102446 ** single token and set *ppExpr to point to it. If the end of the buffer is
102447 ** reached before a token is found, set *ppExpr to zero. It is the
102448 ** responsibility of the caller to eventually deallocate the allocated 
102449 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
102450 **
102451 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
102452 ** fails.
102453 */
102454 static int getNextToken(
102455   ParseContext *pParse,                   /* fts3 query parse context */
102456   int iCol,                               /* Value for Fts3Phrase.iColumn */
102457   const char *z, int n,                   /* Input string */
102458   Fts3Expr **ppExpr,                      /* OUT: expression */
102459   int *pnConsumed                         /* OUT: Number of bytes consumed */
102460 ){
102461   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
102462   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
102463   int rc;
102464   sqlite3_tokenizer_cursor *pCursor;
102465   Fts3Expr *pRet = 0;
102466   int nConsumed = 0;
102467
102468   rc = pModule->xOpen(pTokenizer, z, n, &pCursor);
102469   if( rc==SQLITE_OK ){
102470     const char *zToken;
102471     int nToken, iStart, iEnd, iPosition;
102472     int nByte;                               /* total space to allocate */
102473
102474     pCursor->pTokenizer = pTokenizer;
102475     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
102476
102477     if( rc==SQLITE_OK ){
102478       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
102479       pRet = (Fts3Expr *)sqlite3_malloc(nByte);
102480       if( !pRet ){
102481         rc = SQLITE_NOMEM;
102482       }else{
102483         memset(pRet, 0, nByte);
102484         pRet->eType = FTSQUERY_PHRASE;
102485         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
102486         pRet->pPhrase->nToken = 1;
102487         pRet->pPhrase->iColumn = iCol;
102488         pRet->pPhrase->aToken[0].n = nToken;
102489         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
102490         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
102491
102492         if( iEnd<n && z[iEnd]=='*' ){
102493           pRet->pPhrase->aToken[0].isPrefix = 1;
102494           iEnd++;
102495         }
102496         if( !sqlite3_fts3_enable_parentheses && iStart>0 && z[iStart-1]=='-' ){
102497           pRet->pPhrase->isNot = 1;
102498         }
102499       }
102500       nConsumed = iEnd;
102501     }
102502
102503     pModule->xClose(pCursor);
102504   }
102505   
102506   *pnConsumed = nConsumed;
102507   *ppExpr = pRet;
102508   return rc;
102509 }
102510
102511
102512 /*
102513 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
102514 ** then free the old allocation.
102515 */
102516 static void *fts3ReallocOrFree(void *pOrig, int nNew){
102517   void *pRet = sqlite3_realloc(pOrig, nNew);
102518   if( !pRet ){
102519     sqlite3_free(pOrig);
102520   }
102521   return pRet;
102522 }
102523
102524 /*
102525 ** Buffer zInput, length nInput, contains the contents of a quoted string
102526 ** that appeared as part of an fts3 query expression. Neither quote character
102527 ** is included in the buffer. This function attempts to tokenize the entire
102528 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
102529 ** containing the results.
102530 **
102531 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
102532 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
102533 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
102534 ** to 0.
102535 */
102536 static int getNextString(
102537   ParseContext *pParse,                   /* fts3 query parse context */
102538   const char *zInput, int nInput,         /* Input string */
102539   Fts3Expr **ppExpr                       /* OUT: expression */
102540 ){
102541   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
102542   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
102543   int rc;
102544   Fts3Expr *p = 0;
102545   sqlite3_tokenizer_cursor *pCursor = 0;
102546   char *zTemp = 0;
102547   int nTemp = 0;
102548
102549   rc = pModule->xOpen(pTokenizer, zInput, nInput, &pCursor);
102550   if( rc==SQLITE_OK ){
102551     int ii;
102552     pCursor->pTokenizer = pTokenizer;
102553     for(ii=0; rc==SQLITE_OK; ii++){
102554       const char *zToken;
102555       int nToken, iBegin, iEnd, iPos;
102556       rc = pModule->xNext(pCursor, &zToken, &nToken, &iBegin, &iEnd, &iPos);
102557       if( rc==SQLITE_OK ){
102558         int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
102559         p = fts3ReallocOrFree(p, nByte+ii*sizeof(struct PhraseToken));
102560         zTemp = fts3ReallocOrFree(zTemp, nTemp + nToken);
102561         if( !p || !zTemp ){
102562           goto no_mem;
102563         }
102564         if( ii==0 ){
102565           memset(p, 0, nByte);
102566           p->pPhrase = (Fts3Phrase *)&p[1];
102567         }
102568         p->pPhrase = (Fts3Phrase *)&p[1];
102569         p->pPhrase->nToken = ii+1;
102570         p->pPhrase->aToken[ii].n = nToken;
102571         memcpy(&zTemp[nTemp], zToken, nToken);
102572         nTemp += nToken;
102573         if( iEnd<nInput && zInput[iEnd]=='*' ){
102574           p->pPhrase->aToken[ii].isPrefix = 1;
102575         }else{
102576           p->pPhrase->aToken[ii].isPrefix = 0;
102577         }
102578       }
102579     }
102580
102581     pModule->xClose(pCursor);
102582     pCursor = 0;
102583   }
102584
102585   if( rc==SQLITE_DONE ){
102586     int jj;
102587     char *zNew = NULL;
102588     int nNew = 0;
102589     int nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
102590     nByte += (p?(p->pPhrase->nToken-1):0) * sizeof(struct PhraseToken);
102591     p = fts3ReallocOrFree(p, nByte + nTemp);
102592     if( !p ){
102593       goto no_mem;
102594     }
102595     if( zTemp ){
102596       zNew = &(((char *)p)[nByte]);
102597       memcpy(zNew, zTemp, nTemp);
102598     }else{
102599       memset(p, 0, nByte+nTemp);
102600     }
102601     p->pPhrase = (Fts3Phrase *)&p[1];
102602     for(jj=0; jj<p->pPhrase->nToken; jj++){
102603       p->pPhrase->aToken[jj].z = &zNew[nNew];
102604       nNew += p->pPhrase->aToken[jj].n;
102605     }
102606     sqlite3_free(zTemp);
102607     p->eType = FTSQUERY_PHRASE;
102608     p->pPhrase->iColumn = pParse->iDefaultCol;
102609     rc = SQLITE_OK;
102610   }
102611
102612   *ppExpr = p;
102613   return rc;
102614 no_mem:
102615
102616   if( pCursor ){
102617     pModule->xClose(pCursor);
102618   }
102619   sqlite3_free(zTemp);
102620   sqlite3_free(p);
102621   *ppExpr = 0;
102622   return SQLITE_NOMEM;
102623 }
102624
102625 /*
102626 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
102627 ** call fts3ExprParse(). So this forward declaration is required.
102628 */
102629 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
102630
102631 /*
102632 ** The output variable *ppExpr is populated with an allocated Fts3Expr 
102633 ** structure, or set to 0 if the end of the input buffer is reached.
102634 **
102635 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
102636 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
102637 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
102638 */
102639 static int getNextNode(
102640   ParseContext *pParse,                   /* fts3 query parse context */
102641   const char *z, int n,                   /* Input string */
102642   Fts3Expr **ppExpr,                      /* OUT: expression */
102643   int *pnConsumed                         /* OUT: Number of bytes consumed */
102644 ){
102645   static const struct Fts3Keyword {
102646     char *z;                              /* Keyword text */
102647     unsigned char n;                      /* Length of the keyword */
102648     unsigned char parenOnly;              /* Only valid in paren mode */
102649     unsigned char eType;                  /* Keyword code */
102650   } aKeyword[] = {
102651     { "OR" ,  2, 0, FTSQUERY_OR   },
102652     { "AND",  3, 1, FTSQUERY_AND  },
102653     { "NOT",  3, 1, FTSQUERY_NOT  },
102654     { "NEAR", 4, 0, FTSQUERY_NEAR }
102655   };
102656   int ii;
102657   int iCol;
102658   int iColLen;
102659   int rc;
102660   Fts3Expr *pRet = 0;
102661
102662   const char *zInput = z;
102663   int nInput = n;
102664
102665   /* Skip over any whitespace before checking for a keyword, an open or
102666   ** close bracket, or a quoted string. 
102667   */
102668   while( nInput>0 && fts3isspace(*zInput) ){
102669     nInput--;
102670     zInput++;
102671   }
102672   if( nInput==0 ){
102673     return SQLITE_DONE;
102674   }
102675
102676   /* See if we are dealing with a keyword. */
102677   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
102678     const struct Fts3Keyword *pKey = &aKeyword[ii];
102679
102680     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
102681       continue;
102682     }
102683
102684     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
102685       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
102686       int nKey = pKey->n;
102687       char cNext;
102688
102689       /* If this is a "NEAR" keyword, check for an explicit nearness. */
102690       if( pKey->eType==FTSQUERY_NEAR ){
102691         assert( nKey==4 );
102692         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
102693           nNear = 0;
102694           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
102695             nNear = nNear * 10 + (zInput[nKey] - '0');
102696           }
102697         }
102698       }
102699
102700       /* At this point this is probably a keyword. But for that to be true,
102701       ** the next byte must contain either whitespace, an open or close
102702       ** parenthesis, a quote character, or EOF. 
102703       */
102704       cNext = zInput[nKey];
102705       if( fts3isspace(cNext) 
102706        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
102707       ){
102708         pRet = (Fts3Expr *)sqlite3_malloc(sizeof(Fts3Expr));
102709         if( !pRet ){
102710           return SQLITE_NOMEM;
102711         }
102712         memset(pRet, 0, sizeof(Fts3Expr));
102713         pRet->eType = pKey->eType;
102714         pRet->nNear = nNear;
102715         *ppExpr = pRet;
102716         *pnConsumed = (int)((zInput - z) + nKey);
102717         return SQLITE_OK;
102718       }
102719
102720       /* Turns out that wasn't a keyword after all. This happens if the
102721       ** user has supplied a token such as "ORacle". Continue.
102722       */
102723     }
102724   }
102725
102726   /* Check for an open bracket. */
102727   if( sqlite3_fts3_enable_parentheses ){
102728     if( *zInput=='(' ){
102729       int nConsumed;
102730       int rc;
102731       pParse->nNest++;
102732       rc = fts3ExprParse(pParse, &zInput[1], nInput-1, ppExpr, &nConsumed);
102733       if( rc==SQLITE_OK && !*ppExpr ){
102734         rc = SQLITE_DONE;
102735       }
102736       *pnConsumed = (int)((zInput - z) + 1 + nConsumed);
102737       return rc;
102738     }
102739   
102740     /* Check for a close bracket. */
102741     if( *zInput==')' ){
102742       pParse->nNest--;
102743       *pnConsumed = (int)((zInput - z) + 1);
102744       return SQLITE_DONE;
102745     }
102746   }
102747
102748   /* See if we are dealing with a quoted phrase. If this is the case, then
102749   ** search for the closing quote and pass the whole string to getNextString()
102750   ** for processing. This is easy to do, as fts3 has no syntax for escaping
102751   ** a quote character embedded in a string.
102752   */
102753   if( *zInput=='"' ){
102754     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
102755     *pnConsumed = (int)((zInput - z) + ii + 1);
102756     if( ii==nInput ){
102757       return SQLITE_ERROR;
102758     }
102759     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
102760   }
102761
102762
102763   /* If control flows to this point, this must be a regular token, or 
102764   ** the end of the input. Read a regular token using the sqlite3_tokenizer
102765   ** interface. Before doing so, figure out if there is an explicit
102766   ** column specifier for the token. 
102767   **
102768   ** TODO: Strangely, it is not possible to associate a column specifier
102769   ** with a quoted phrase, only with a single token. Not sure if this was
102770   ** an implementation artifact or an intentional decision when fts3 was
102771   ** first implemented. Whichever it was, this module duplicates the 
102772   ** limitation.
102773   */
102774   iCol = pParse->iDefaultCol;
102775   iColLen = 0;
102776   for(ii=0; ii<pParse->nCol; ii++){
102777     const char *zStr = pParse->azCol[ii];
102778     int nStr = (int)strlen(zStr);
102779     if( nInput>nStr && zInput[nStr]==':' 
102780      && sqlite3_strnicmp(zStr, zInput, nStr)==0 
102781     ){
102782       iCol = ii;
102783       iColLen = (int)((zInput - z) + nStr + 1);
102784       break;
102785     }
102786   }
102787   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
102788   *pnConsumed += iColLen;
102789   return rc;
102790 }
102791
102792 /*
102793 ** The argument is an Fts3Expr structure for a binary operator (any type
102794 ** except an FTSQUERY_PHRASE). Return an integer value representing the
102795 ** precedence of the operator. Lower values have a higher precedence (i.e.
102796 ** group more tightly). For example, in the C language, the == operator
102797 ** groups more tightly than ||, and would therefore have a higher precedence.
102798 **
102799 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
102800 ** is defined), the order of the operators in precedence from highest to
102801 ** lowest is:
102802 **
102803 **   NEAR
102804 **   NOT
102805 **   AND (including implicit ANDs)
102806 **   OR
102807 **
102808 ** Note that when using the old query syntax, the OR operator has a higher
102809 ** precedence than the AND operator.
102810 */
102811 static int opPrecedence(Fts3Expr *p){
102812   assert( p->eType!=FTSQUERY_PHRASE );
102813   if( sqlite3_fts3_enable_parentheses ){
102814     return p->eType;
102815   }else if( p->eType==FTSQUERY_NEAR ){
102816     return 1;
102817   }else if( p->eType==FTSQUERY_OR ){
102818     return 2;
102819   }
102820   assert( p->eType==FTSQUERY_AND );
102821   return 3;
102822 }
102823
102824 /*
102825 ** Argument ppHead contains a pointer to the current head of a query 
102826 ** expression tree being parsed. pPrev is the expression node most recently
102827 ** inserted into the tree. This function adds pNew, which is always a binary
102828 ** operator node, into the expression tree based on the relative precedence
102829 ** of pNew and the existing nodes of the tree. This may result in the head
102830 ** of the tree changing, in which case *ppHead is set to the new root node.
102831 */
102832 static void insertBinaryOperator(
102833   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
102834   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
102835   Fts3Expr *pNew           /* New binary node to insert into expression tree */
102836 ){
102837   Fts3Expr *pSplit = pPrev;
102838   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
102839     pSplit = pSplit->pParent;
102840   }
102841
102842   if( pSplit->pParent ){
102843     assert( pSplit->pParent->pRight==pSplit );
102844     pSplit->pParent->pRight = pNew;
102845     pNew->pParent = pSplit->pParent;
102846   }else{
102847     *ppHead = pNew;
102848   }
102849   pNew->pLeft = pSplit;
102850   pSplit->pParent = pNew;
102851 }
102852
102853 /*
102854 ** Parse the fts3 query expression found in buffer z, length n. This function
102855 ** returns either when the end of the buffer is reached or an unmatched 
102856 ** closing bracket - ')' - is encountered.
102857 **
102858 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
102859 ** parsed form of the expression and *pnConsumed is set to the number of
102860 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
102861 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
102862 */
102863 static int fts3ExprParse(
102864   ParseContext *pParse,                   /* fts3 query parse context */
102865   const char *z, int n,                   /* Text of MATCH query */
102866   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
102867   int *pnConsumed                         /* OUT: Number of bytes consumed */
102868 ){
102869   Fts3Expr *pRet = 0;
102870   Fts3Expr *pPrev = 0;
102871   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
102872   int nIn = n;
102873   const char *zIn = z;
102874   int rc = SQLITE_OK;
102875   int isRequirePhrase = 1;
102876
102877   while( rc==SQLITE_OK ){
102878     Fts3Expr *p = 0;
102879     int nByte = 0;
102880     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
102881     if( rc==SQLITE_OK ){
102882       int isPhrase;
102883
102884       if( !sqlite3_fts3_enable_parentheses 
102885        && p->eType==FTSQUERY_PHRASE && p->pPhrase->isNot 
102886       ){
102887         /* Create an implicit NOT operator. */
102888         Fts3Expr *pNot = sqlite3_malloc(sizeof(Fts3Expr));
102889         if( !pNot ){
102890           sqlite3Fts3ExprFree(p);
102891           rc = SQLITE_NOMEM;
102892           goto exprparse_out;
102893         }
102894         memset(pNot, 0, sizeof(Fts3Expr));
102895         pNot->eType = FTSQUERY_NOT;
102896         pNot->pRight = p;
102897         if( pNotBranch ){
102898           pNot->pLeft = pNotBranch;
102899         }
102900         pNotBranch = pNot;
102901         p = pPrev;
102902       }else{
102903         int eType = p->eType;
102904         assert( eType!=FTSQUERY_PHRASE || !p->pPhrase->isNot );
102905         isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
102906
102907         /* The isRequirePhrase variable is set to true if a phrase or
102908         ** an expression contained in parenthesis is required. If a
102909         ** binary operator (AND, OR, NOT or NEAR) is encounted when
102910         ** isRequirePhrase is set, this is a syntax error.
102911         */
102912         if( !isPhrase && isRequirePhrase ){
102913           sqlite3Fts3ExprFree(p);
102914           rc = SQLITE_ERROR;
102915           goto exprparse_out;
102916         }
102917   
102918         if( isPhrase && !isRequirePhrase ){
102919           /* Insert an implicit AND operator. */
102920           Fts3Expr *pAnd;
102921           assert( pRet && pPrev );
102922           pAnd = sqlite3_malloc(sizeof(Fts3Expr));
102923           if( !pAnd ){
102924             sqlite3Fts3ExprFree(p);
102925             rc = SQLITE_NOMEM;
102926             goto exprparse_out;
102927           }
102928           memset(pAnd, 0, sizeof(Fts3Expr));
102929           pAnd->eType = FTSQUERY_AND;
102930           insertBinaryOperator(&pRet, pPrev, pAnd);
102931           pPrev = pAnd;
102932         }
102933
102934         /* This test catches attempts to make either operand of a NEAR
102935         ** operator something other than a phrase. For example, either of
102936         ** the following:
102937         **
102938         **    (bracketed expression) NEAR phrase
102939         **    phrase NEAR (bracketed expression)
102940         **
102941         ** Return an error in either case.
102942         */
102943         if( pPrev && (
102944             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
102945          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
102946         )){
102947           sqlite3Fts3ExprFree(p);
102948           rc = SQLITE_ERROR;
102949           goto exprparse_out;
102950         }
102951   
102952         if( isPhrase ){
102953           if( pRet ){
102954             assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
102955             pPrev->pRight = p;
102956             p->pParent = pPrev;
102957           }else{
102958             pRet = p;
102959           }
102960         }else{
102961           insertBinaryOperator(&pRet, pPrev, p);
102962         }
102963         isRequirePhrase = !isPhrase;
102964       }
102965       assert( nByte>0 );
102966     }
102967     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
102968     nIn -= nByte;
102969     zIn += nByte;
102970     pPrev = p;
102971   }
102972
102973   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
102974     rc = SQLITE_ERROR;
102975   }
102976
102977   if( rc==SQLITE_DONE ){
102978     rc = SQLITE_OK;
102979     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
102980       if( !pRet ){
102981         rc = SQLITE_ERROR;
102982       }else{
102983         Fts3Expr *pIter = pNotBranch;
102984         while( pIter->pLeft ){
102985           pIter = pIter->pLeft;
102986         }
102987         pIter->pLeft = pRet;
102988         pRet = pNotBranch;
102989       }
102990     }
102991   }
102992   *pnConsumed = n - nIn;
102993
102994 exprparse_out:
102995   if( rc!=SQLITE_OK ){
102996     sqlite3Fts3ExprFree(pRet);
102997     sqlite3Fts3ExprFree(pNotBranch);
102998     pRet = 0;
102999   }
103000   *ppExpr = pRet;
103001   return rc;
103002 }
103003
103004 /*
103005 ** Parameters z and n contain a pointer to and length of a buffer containing
103006 ** an fts3 query expression, respectively. This function attempts to parse the
103007 ** query expression and create a tree of Fts3Expr structures representing the
103008 ** parsed expression. If successful, *ppExpr is set to point to the head
103009 ** of the parsed expression tree and SQLITE_OK is returned. If an error
103010 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
103011 ** error) is returned and *ppExpr is set to 0.
103012 **
103013 ** If parameter n is a negative number, then z is assumed to point to a
103014 ** nul-terminated string and the length is determined using strlen().
103015 **
103016 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
103017 ** use to normalize query tokens while parsing the expression. The azCol[]
103018 ** array, which is assumed to contain nCol entries, should contain the names
103019 ** of each column in the target fts3 table, in order from left to right. 
103020 ** Column names must be nul-terminated strings.
103021 **
103022 ** The iDefaultCol parameter should be passed the index of the table column
103023 ** that appears on the left-hand-side of the MATCH operator (the default
103024 ** column to match against for tokens for which a column name is not explicitly
103025 ** specified as part of the query string), or -1 if tokens may by default
103026 ** match any table column.
103027 */
103028 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
103029   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
103030   char **azCol,                       /* Array of column names for fts3 table */
103031   int nCol,                           /* Number of entries in azCol[] */
103032   int iDefaultCol,                    /* Default column to query */
103033   const char *z, int n,               /* Text of MATCH query */
103034   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
103035 ){
103036   int nParsed;
103037   int rc;
103038   ParseContext sParse;
103039   sParse.pTokenizer = pTokenizer;
103040   sParse.azCol = (const char **)azCol;
103041   sParse.nCol = nCol;
103042   sParse.iDefaultCol = iDefaultCol;
103043   sParse.nNest = 0;
103044   if( z==0 ){
103045     *ppExpr = 0;
103046     return SQLITE_OK;
103047   }
103048   if( n<0 ){
103049     n = (int)strlen(z);
103050   }
103051   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
103052
103053   /* Check for mismatched parenthesis */
103054   if( rc==SQLITE_OK && sParse.nNest ){
103055     rc = SQLITE_ERROR;
103056     sqlite3Fts3ExprFree(*ppExpr);
103057     *ppExpr = 0;
103058   }
103059
103060   return rc;
103061 }
103062
103063 /*
103064 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
103065 */
103066 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *p){
103067   if( p ){
103068     sqlite3Fts3ExprFree(p->pLeft);
103069     sqlite3Fts3ExprFree(p->pRight);
103070     sqlite3_free(p->aDoclist);
103071     sqlite3_free(p);
103072   }
103073 }
103074
103075 /****************************************************************************
103076 *****************************************************************************
103077 ** Everything after this point is just test code.
103078 */
103079
103080 #ifdef SQLITE_TEST
103081
103082
103083 /*
103084 ** Function to query the hash-table of tokenizers (see README.tokenizers).
103085 */
103086 static int queryTestTokenizer(
103087   sqlite3 *db, 
103088   const char *zName,  
103089   const sqlite3_tokenizer_module **pp
103090 ){
103091   int rc;
103092   sqlite3_stmt *pStmt;
103093   const char zSql[] = "SELECT fts3_tokenizer(?)";
103094
103095   *pp = 0;
103096   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
103097   if( rc!=SQLITE_OK ){
103098     return rc;
103099   }
103100
103101   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
103102   if( SQLITE_ROW==sqlite3_step(pStmt) ){
103103     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
103104       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
103105     }
103106   }
103107
103108   return sqlite3_finalize(pStmt);
103109 }
103110
103111 /*
103112 ** This function is part of the test interface for the query parser. It
103113 ** writes a text representation of the query expression pExpr into the
103114 ** buffer pointed to by argument zBuf. It is assumed that zBuf is large 
103115 ** enough to store the required text representation.
103116 */
103117 static void exprToString(Fts3Expr *pExpr, char *zBuf){
103118   switch( pExpr->eType ){
103119     case FTSQUERY_PHRASE: {
103120       Fts3Phrase *pPhrase = pExpr->pPhrase;
103121       int i;
103122       zBuf += sprintf(zBuf, "PHRASE %d %d", pPhrase->iColumn, pPhrase->isNot);
103123       for(i=0; i<pPhrase->nToken; i++){
103124         zBuf += sprintf(zBuf," %.*s",pPhrase->aToken[i].n,pPhrase->aToken[i].z);
103125         zBuf += sprintf(zBuf,"%s", (pPhrase->aToken[i].isPrefix?"+":""));
103126       }
103127       return;
103128     }
103129
103130     case FTSQUERY_NEAR:
103131       zBuf += sprintf(zBuf, "NEAR/%d ", pExpr->nNear);
103132       break;
103133     case FTSQUERY_NOT:
103134       zBuf += sprintf(zBuf, "NOT ");
103135       break;
103136     case FTSQUERY_AND:
103137       zBuf += sprintf(zBuf, "AND ");
103138       break;
103139     case FTSQUERY_OR:
103140       zBuf += sprintf(zBuf, "OR ");
103141       break;
103142   }
103143
103144   zBuf += sprintf(zBuf, "{");
103145   exprToString(pExpr->pLeft, zBuf);
103146   zBuf += strlen(zBuf);
103147   zBuf += sprintf(zBuf, "} ");
103148
103149   zBuf += sprintf(zBuf, "{");
103150   exprToString(pExpr->pRight, zBuf);
103151   zBuf += strlen(zBuf);
103152   zBuf += sprintf(zBuf, "}");
103153 }
103154
103155 /*
103156 ** This is the implementation of a scalar SQL function used to test the 
103157 ** expression parser. It should be called as follows:
103158 **
103159 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
103160 **
103161 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
103162 ** to parse the query expression (see README.tokenizers). The second argument
103163 ** is the query expression to parse. Each subsequent argument is the name
103164 ** of a column of the fts3 table that the query expression may refer to.
103165 ** For example:
103166 **
103167 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
103168 */
103169 static void fts3ExprTest(
103170   sqlite3_context *context,
103171   int argc,
103172   sqlite3_value **argv
103173 ){
103174   sqlite3_tokenizer_module const *pModule = 0;
103175   sqlite3_tokenizer *pTokenizer = 0;
103176   int rc;
103177   char **azCol = 0;
103178   const char *zExpr;
103179   int nExpr;
103180   int nCol;
103181   int ii;
103182   Fts3Expr *pExpr;
103183   sqlite3 *db = sqlite3_context_db_handle(context);
103184
103185   if( argc<3 ){
103186     sqlite3_result_error(context, 
103187         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
103188     );
103189     return;
103190   }
103191
103192   rc = queryTestTokenizer(db,
103193                           (const char *)sqlite3_value_text(argv[0]), &pModule);
103194   if( rc==SQLITE_NOMEM ){
103195     sqlite3_result_error_nomem(context);
103196     goto exprtest_out;
103197   }else if( !pModule ){
103198     sqlite3_result_error(context, "No such tokenizer module", -1);
103199     goto exprtest_out;
103200   }
103201
103202   rc = pModule->xCreate(0, 0, &pTokenizer);
103203   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
103204   if( rc==SQLITE_NOMEM ){
103205     sqlite3_result_error_nomem(context);
103206     goto exprtest_out;
103207   }
103208   pTokenizer->pModule = pModule;
103209
103210   zExpr = (const char *)sqlite3_value_text(argv[1]);
103211   nExpr = sqlite3_value_bytes(argv[1]);
103212   nCol = argc-2;
103213   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
103214   if( !azCol ){
103215     sqlite3_result_error_nomem(context);
103216     goto exprtest_out;
103217   }
103218   for(ii=0; ii<nCol; ii++){
103219     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
103220   }
103221
103222   rc = sqlite3Fts3ExprParse(
103223       pTokenizer, azCol, nCol, nCol, zExpr, nExpr, &pExpr
103224   );
103225   if( rc==SQLITE_NOMEM ){
103226     sqlite3_result_error_nomem(context);
103227     goto exprtest_out;
103228   }else if( rc==SQLITE_OK ){
103229     char zBuf[4096];
103230     exprToString(pExpr, zBuf);
103231     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
103232     sqlite3Fts3ExprFree(pExpr);
103233   }else{
103234     sqlite3_result_error(context, "Error parsing expression", -1);
103235   }
103236
103237 exprtest_out:
103238   if( pModule && pTokenizer ){
103239     rc = pModule->xDestroy(pTokenizer);
103240   }
103241   sqlite3_free(azCol);
103242 }
103243
103244 /*
103245 ** Register the query expression parser test function fts3_exprtest() 
103246 ** with database connection db. 
103247 */
103248 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
103249   return sqlite3_create_function(
103250       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
103251   );
103252 }
103253
103254 #endif
103255 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
103256
103257 /************** End of fts3_expr.c *******************************************/
103258 /************** Begin file fts3_hash.c ***************************************/
103259 /*
103260 ** 2001 September 22
103261 **
103262 ** The author disclaims copyright to this source code.  In place of
103263 ** a legal notice, here is a blessing:
103264 **
103265 **    May you do good and not evil.
103266 **    May you find forgiveness for yourself and forgive others.
103267 **    May you share freely, never taking more than you give.
103268 **
103269 *************************************************************************
103270 ** This is the implementation of generic hash-tables used in SQLite.
103271 ** We've modified it slightly to serve as a standalone hash table
103272 ** implementation for the full-text indexing module.
103273 */
103274
103275 /*
103276 ** The code in this file is only compiled if:
103277 **
103278 **     * The FTS3 module is being built as an extension
103279 **       (in which case SQLITE_CORE is not defined), or
103280 **
103281 **     * The FTS3 module is being built into the core of
103282 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
103283 */
103284 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
103285
103286
103287
103288 /*
103289 ** Malloc and Free functions
103290 */
103291 static void *fts3HashMalloc(int n){
103292   void *p = sqlite3_malloc(n);
103293   if( p ){
103294     memset(p, 0, n);
103295   }
103296   return p;
103297 }
103298 static void fts3HashFree(void *p){
103299   sqlite3_free(p);
103300 }
103301
103302 /* Turn bulk memory into a hash table object by initializing the
103303 ** fields of the Hash structure.
103304 **
103305 ** "pNew" is a pointer to the hash table that is to be initialized.
103306 ** keyClass is one of the constants 
103307 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
103308 ** determines what kind of key the hash table will use.  "copyKey" is
103309 ** true if the hash table should make its own private copy of keys and
103310 ** false if it should just use the supplied pointer.
103311 */
103312 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
103313   assert( pNew!=0 );
103314   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
103315   pNew->keyClass = keyClass;
103316   pNew->copyKey = copyKey;
103317   pNew->first = 0;
103318   pNew->count = 0;
103319   pNew->htsize = 0;
103320   pNew->ht = 0;
103321 }
103322
103323 /* Remove all entries from a hash table.  Reclaim all memory.
103324 ** Call this routine to delete a hash table or to reset a hash table
103325 ** to the empty state.
103326 */
103327 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
103328   Fts3HashElem *elem;         /* For looping over all elements of the table */
103329
103330   assert( pH!=0 );
103331   elem = pH->first;
103332   pH->first = 0;
103333   fts3HashFree(pH->ht);
103334   pH->ht = 0;
103335   pH->htsize = 0;
103336   while( elem ){
103337     Fts3HashElem *next_elem = elem->next;
103338     if( pH->copyKey && elem->pKey ){
103339       fts3HashFree(elem->pKey);
103340     }
103341     fts3HashFree(elem);
103342     elem = next_elem;
103343   }
103344   pH->count = 0;
103345 }
103346
103347 /*
103348 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
103349 */
103350 static int fts3StrHash(const void *pKey, int nKey){
103351   const char *z = (const char *)pKey;
103352   int h = 0;
103353   if( nKey<=0 ) nKey = (int) strlen(z);
103354   while( nKey > 0  ){
103355     h = (h<<3) ^ h ^ *z++;
103356     nKey--;
103357   }
103358   return h & 0x7fffffff;
103359 }
103360 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
103361   if( n1!=n2 ) return 1;
103362   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
103363 }
103364
103365 /*
103366 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
103367 */
103368 static int fts3BinHash(const void *pKey, int nKey){
103369   int h = 0;
103370   const char *z = (const char *)pKey;
103371   while( nKey-- > 0 ){
103372     h = (h<<3) ^ h ^ *(z++);
103373   }
103374   return h & 0x7fffffff;
103375 }
103376 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
103377   if( n1!=n2 ) return 1;
103378   return memcmp(pKey1,pKey2,n1);
103379 }
103380
103381 /*
103382 ** Return a pointer to the appropriate hash function given the key class.
103383 **
103384 ** The C syntax in this function definition may be unfamilar to some 
103385 ** programmers, so we provide the following additional explanation:
103386 **
103387 ** The name of the function is "ftsHashFunction".  The function takes a
103388 ** single parameter "keyClass".  The return value of ftsHashFunction()
103389 ** is a pointer to another function.  Specifically, the return value
103390 ** of ftsHashFunction() is a pointer to a function that takes two parameters
103391 ** with types "const void*" and "int" and returns an "int".
103392 */
103393 static int (*ftsHashFunction(int keyClass))(const void*,int){
103394   if( keyClass==FTS3_HASH_STRING ){
103395     return &fts3StrHash;
103396   }else{
103397     assert( keyClass==FTS3_HASH_BINARY );
103398     return &fts3BinHash;
103399   }
103400 }
103401
103402 /*
103403 ** Return a pointer to the appropriate hash function given the key class.
103404 **
103405 ** For help in interpreted the obscure C code in the function definition,
103406 ** see the header comment on the previous function.
103407 */
103408 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
103409   if( keyClass==FTS3_HASH_STRING ){
103410     return &fts3StrCompare;
103411   }else{
103412     assert( keyClass==FTS3_HASH_BINARY );
103413     return &fts3BinCompare;
103414   }
103415 }
103416
103417 /* Link an element into the hash table
103418 */
103419 static void fts3HashInsertElement(
103420   Fts3Hash *pH,            /* The complete hash table */
103421   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
103422   Fts3HashElem *pNew       /* The element to be inserted */
103423 ){
103424   Fts3HashElem *pHead;     /* First element already in pEntry */
103425   pHead = pEntry->chain;
103426   if( pHead ){
103427     pNew->next = pHead;
103428     pNew->prev = pHead->prev;
103429     if( pHead->prev ){ pHead->prev->next = pNew; }
103430     else             { pH->first = pNew; }
103431     pHead->prev = pNew;
103432   }else{
103433     pNew->next = pH->first;
103434     if( pH->first ){ pH->first->prev = pNew; }
103435     pNew->prev = 0;
103436     pH->first = pNew;
103437   }
103438   pEntry->count++;
103439   pEntry->chain = pNew;
103440 }
103441
103442
103443 /* Resize the hash table so that it cantains "new_size" buckets.
103444 ** "new_size" must be a power of 2.  The hash table might fail 
103445 ** to resize if sqliteMalloc() fails.
103446 **
103447 ** Return non-zero if a memory allocation error occurs.
103448 */
103449 static int fts3Rehash(Fts3Hash *pH, int new_size){
103450   struct _fts3ht *new_ht;          /* The new hash table */
103451   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
103452   int (*xHash)(const void*,int);   /* The hash function */
103453
103454   assert( (new_size & (new_size-1))==0 );
103455   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
103456   if( new_ht==0 ) return 1;
103457   fts3HashFree(pH->ht);
103458   pH->ht = new_ht;
103459   pH->htsize = new_size;
103460   xHash = ftsHashFunction(pH->keyClass);
103461   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
103462     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
103463     next_elem = elem->next;
103464     fts3HashInsertElement(pH, &new_ht[h], elem);
103465   }
103466   return 0;
103467 }
103468
103469 /* This function (for internal use only) locates an element in an
103470 ** hash table that matches the given key.  The hash for this key has
103471 ** already been computed and is passed as the 4th parameter.
103472 */
103473 static Fts3HashElem *fts3FindElementByHash(
103474   const Fts3Hash *pH, /* The pH to be searched */
103475   const void *pKey,   /* The key we are searching for */
103476   int nKey,
103477   int h               /* The hash for this key. */
103478 ){
103479   Fts3HashElem *elem;            /* Used to loop thru the element list */
103480   int count;                     /* Number of elements left to test */
103481   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
103482
103483   if( pH->ht ){
103484     struct _fts3ht *pEntry = &pH->ht[h];
103485     elem = pEntry->chain;
103486     count = pEntry->count;
103487     xCompare = ftsCompareFunction(pH->keyClass);
103488     while( count-- && elem ){
103489       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
103490         return elem;
103491       }
103492       elem = elem->next;
103493     }
103494   }
103495   return 0;
103496 }
103497
103498 /* Remove a single entry from the hash table given a pointer to that
103499 ** element and a hash on the element's key.
103500 */
103501 static void fts3RemoveElementByHash(
103502   Fts3Hash *pH,         /* The pH containing "elem" */
103503   Fts3HashElem* elem,   /* The element to be removed from the pH */
103504   int h                 /* Hash value for the element */
103505 ){
103506   struct _fts3ht *pEntry;
103507   if( elem->prev ){
103508     elem->prev->next = elem->next; 
103509   }else{
103510     pH->first = elem->next;
103511   }
103512   if( elem->next ){
103513     elem->next->prev = elem->prev;
103514   }
103515   pEntry = &pH->ht[h];
103516   if( pEntry->chain==elem ){
103517     pEntry->chain = elem->next;
103518   }
103519   pEntry->count--;
103520   if( pEntry->count<=0 ){
103521     pEntry->chain = 0;
103522   }
103523   if( pH->copyKey && elem->pKey ){
103524     fts3HashFree(elem->pKey);
103525   }
103526   fts3HashFree( elem );
103527   pH->count--;
103528   if( pH->count<=0 ){
103529     assert( pH->first==0 );
103530     assert( pH->count==0 );
103531     fts3HashClear(pH);
103532   }
103533 }
103534
103535 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
103536   const Fts3Hash *pH, 
103537   const void *pKey, 
103538   int nKey
103539 ){
103540   int h;                          /* A hash on key */
103541   int (*xHash)(const void*,int);  /* The hash function */
103542
103543   if( pH==0 || pH->ht==0 ) return 0;
103544   xHash = ftsHashFunction(pH->keyClass);
103545   assert( xHash!=0 );
103546   h = (*xHash)(pKey,nKey);
103547   assert( (pH->htsize & (pH->htsize-1))==0 );
103548   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
103549 }
103550
103551 /* 
103552 ** Attempt to locate an element of the hash table pH with a key
103553 ** that matches pKey,nKey.  Return the data for this element if it is
103554 ** found, or NULL if there is no match.
103555 */
103556 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
103557   Fts3HashElem *pElem;            /* The element that matches key (if any) */
103558
103559   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
103560   return pElem ? pElem->data : 0;
103561 }
103562
103563 /* Insert an element into the hash table pH.  The key is pKey,nKey
103564 ** and the data is "data".
103565 **
103566 ** If no element exists with a matching key, then a new
103567 ** element is created.  A copy of the key is made if the copyKey
103568 ** flag is set.  NULL is returned.
103569 **
103570 ** If another element already exists with the same key, then the
103571 ** new data replaces the old data and the old data is returned.
103572 ** The key is not copied in this instance.  If a malloc fails, then
103573 ** the new data is returned and the hash table is unchanged.
103574 **
103575 ** If the "data" parameter to this function is NULL, then the
103576 ** element corresponding to "key" is removed from the hash table.
103577 */
103578 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
103579   Fts3Hash *pH,        /* The hash table to insert into */
103580   const void *pKey,    /* The key */
103581   int nKey,            /* Number of bytes in the key */
103582   void *data           /* The data */
103583 ){
103584   int hraw;                 /* Raw hash value of the key */
103585   int h;                    /* the hash of the key modulo hash table size */
103586   Fts3HashElem *elem;       /* Used to loop thru the element list */
103587   Fts3HashElem *new_elem;   /* New element added to the pH */
103588   int (*xHash)(const void*,int);  /* The hash function */
103589
103590   assert( pH!=0 );
103591   xHash = ftsHashFunction(pH->keyClass);
103592   assert( xHash!=0 );
103593   hraw = (*xHash)(pKey, nKey);
103594   assert( (pH->htsize & (pH->htsize-1))==0 );
103595   h = hraw & (pH->htsize-1);
103596   elem = fts3FindElementByHash(pH,pKey,nKey,h);
103597   if( elem ){
103598     void *old_data = elem->data;
103599     if( data==0 ){
103600       fts3RemoveElementByHash(pH,elem,h);
103601     }else{
103602       elem->data = data;
103603     }
103604     return old_data;
103605   }
103606   if( data==0 ) return 0;
103607   if( (pH->htsize==0 && fts3Rehash(pH,8))
103608    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
103609   ){
103610     pH->count = 0;
103611     return data;
103612   }
103613   assert( pH->htsize>0 );
103614   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
103615   if( new_elem==0 ) return data;
103616   if( pH->copyKey && pKey!=0 ){
103617     new_elem->pKey = fts3HashMalloc( nKey );
103618     if( new_elem->pKey==0 ){
103619       fts3HashFree(new_elem);
103620       return data;
103621     }
103622     memcpy((void*)new_elem->pKey, pKey, nKey);
103623   }else{
103624     new_elem->pKey = (void*)pKey;
103625   }
103626   new_elem->nKey = nKey;
103627   pH->count++;
103628   assert( pH->htsize>0 );
103629   assert( (pH->htsize & (pH->htsize-1))==0 );
103630   h = hraw & (pH->htsize-1);
103631   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
103632   new_elem->data = data;
103633   return 0;
103634 }
103635
103636 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
103637
103638 /************** End of fts3_hash.c *******************************************/
103639 /************** Begin file fts3_porter.c *************************************/
103640 /*
103641 ** 2006 September 30
103642 **
103643 ** The author disclaims copyright to this source code.  In place of
103644 ** a legal notice, here is a blessing:
103645 **
103646 **    May you do good and not evil.
103647 **    May you find forgiveness for yourself and forgive others.
103648 **    May you share freely, never taking more than you give.
103649 **
103650 *************************************************************************
103651 ** Implementation of the full-text-search tokenizer that implements
103652 ** a Porter stemmer.
103653 */
103654
103655 /*
103656 ** The code in this file is only compiled if:
103657 **
103658 **     * The FTS3 module is being built as an extension
103659 **       (in which case SQLITE_CORE is not defined), or
103660 **
103661 **     * The FTS3 module is being built into the core of
103662 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
103663 */
103664 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
103665
103666
103667
103668
103669 /*
103670 ** Class derived from sqlite3_tokenizer
103671 */
103672 typedef struct porter_tokenizer {
103673   sqlite3_tokenizer base;      /* Base class */
103674 } porter_tokenizer;
103675
103676 /*
103677 ** Class derived from sqlit3_tokenizer_cursor
103678 */
103679 typedef struct porter_tokenizer_cursor {
103680   sqlite3_tokenizer_cursor base;
103681   const char *zInput;          /* input we are tokenizing */
103682   int nInput;                  /* size of the input */
103683   int iOffset;                 /* current position in zInput */
103684   int iToken;                  /* index of next token to be returned */
103685   char *zToken;                /* storage for current token */
103686   int nAllocated;              /* space allocated to zToken buffer */
103687 } porter_tokenizer_cursor;
103688
103689
103690 /*
103691 ** Create a new tokenizer instance.
103692 */
103693 static int porterCreate(
103694   int argc, const char * const *argv,
103695   sqlite3_tokenizer **ppTokenizer
103696 ){
103697   porter_tokenizer *t;
103698
103699   UNUSED_PARAMETER(argc);
103700   UNUSED_PARAMETER(argv);
103701
103702   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
103703   if( t==NULL ) return SQLITE_NOMEM;
103704   memset(t, 0, sizeof(*t));
103705   *ppTokenizer = &t->base;
103706   return SQLITE_OK;
103707 }
103708
103709 /*
103710 ** Destroy a tokenizer
103711 */
103712 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
103713   sqlite3_free(pTokenizer);
103714   return SQLITE_OK;
103715 }
103716
103717 /*
103718 ** Prepare to begin tokenizing a particular string.  The input
103719 ** string to be tokenized is zInput[0..nInput-1].  A cursor
103720 ** used to incrementally tokenize this string is returned in 
103721 ** *ppCursor.
103722 */
103723 static int porterOpen(
103724   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
103725   const char *zInput, int nInput,        /* String to be tokenized */
103726   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
103727 ){
103728   porter_tokenizer_cursor *c;
103729
103730   UNUSED_PARAMETER(pTokenizer);
103731
103732   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
103733   if( c==NULL ) return SQLITE_NOMEM;
103734
103735   c->zInput = zInput;
103736   if( zInput==0 ){
103737     c->nInput = 0;
103738   }else if( nInput<0 ){
103739     c->nInput = (int)strlen(zInput);
103740   }else{
103741     c->nInput = nInput;
103742   }
103743   c->iOffset = 0;                 /* start tokenizing at the beginning */
103744   c->iToken = 0;
103745   c->zToken = NULL;               /* no space allocated, yet. */
103746   c->nAllocated = 0;
103747
103748   *ppCursor = &c->base;
103749   return SQLITE_OK;
103750 }
103751
103752 /*
103753 ** Close a tokenization cursor previously opened by a call to
103754 ** porterOpen() above.
103755 */
103756 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
103757   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
103758   sqlite3_free(c->zToken);
103759   sqlite3_free(c);
103760   return SQLITE_OK;
103761 }
103762 /*
103763 ** Vowel or consonant
103764 */
103765 static const char cType[] = {
103766    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
103767    1, 1, 1, 2, 1
103768 };
103769
103770 /*
103771 ** isConsonant() and isVowel() determine if their first character in
103772 ** the string they point to is a consonant or a vowel, according
103773 ** to Porter ruls.  
103774 **
103775 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
103776 ** 'Y' is a consonant unless it follows another consonant,
103777 ** in which case it is a vowel.
103778 **
103779 ** In these routine, the letters are in reverse order.  So the 'y' rule
103780 ** is that 'y' is a consonant unless it is followed by another
103781 ** consonent.
103782 */
103783 static int isVowel(const char*);
103784 static int isConsonant(const char *z){
103785   int j;
103786   char x = *z;
103787   if( x==0 ) return 0;
103788   assert( x>='a' && x<='z' );
103789   j = cType[x-'a'];
103790   if( j<2 ) return j;
103791   return z[1]==0 || isVowel(z + 1);
103792 }
103793 static int isVowel(const char *z){
103794   int j;
103795   char x = *z;
103796   if( x==0 ) return 0;
103797   assert( x>='a' && x<='z' );
103798   j = cType[x-'a'];
103799   if( j<2 ) return 1-j;
103800   return isConsonant(z + 1);
103801 }
103802
103803 /*
103804 ** Let any sequence of one or more vowels be represented by V and let
103805 ** C be sequence of one or more consonants.  Then every word can be
103806 ** represented as:
103807 **
103808 **           [C] (VC){m} [V]
103809 **
103810 ** In prose:  A word is an optional consonant followed by zero or
103811 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
103812 ** number of vowel consonant pairs.  This routine computes the value
103813 ** of m for the first i bytes of a word.
103814 **
103815 ** Return true if the m-value for z is 1 or more.  In other words,
103816 ** return true if z contains at least one vowel that is followed
103817 ** by a consonant.
103818 **
103819 ** In this routine z[] is in reverse order.  So we are really looking
103820 ** for an instance of of a consonant followed by a vowel.
103821 */
103822 static int m_gt_0(const char *z){
103823   while( isVowel(z) ){ z++; }
103824   if( *z==0 ) return 0;
103825   while( isConsonant(z) ){ z++; }
103826   return *z!=0;
103827 }
103828
103829 /* Like mgt0 above except we are looking for a value of m which is
103830 ** exactly 1
103831 */
103832 static int m_eq_1(const char *z){
103833   while( isVowel(z) ){ z++; }
103834   if( *z==0 ) return 0;
103835   while( isConsonant(z) ){ z++; }
103836   if( *z==0 ) return 0;
103837   while( isVowel(z) ){ z++; }
103838   if( *z==0 ) return 1;
103839   while( isConsonant(z) ){ z++; }
103840   return *z==0;
103841 }
103842
103843 /* Like mgt0 above except we are looking for a value of m>1 instead
103844 ** or m>0
103845 */
103846 static int m_gt_1(const char *z){
103847   while( isVowel(z) ){ z++; }
103848   if( *z==0 ) return 0;
103849   while( isConsonant(z) ){ z++; }
103850   if( *z==0 ) return 0;
103851   while( isVowel(z) ){ z++; }
103852   if( *z==0 ) return 0;
103853   while( isConsonant(z) ){ z++; }
103854   return *z!=0;
103855 }
103856
103857 /*
103858 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
103859 */
103860 static int hasVowel(const char *z){
103861   while( isConsonant(z) ){ z++; }
103862   return *z!=0;
103863 }
103864
103865 /*
103866 ** Return TRUE if the word ends in a double consonant.
103867 **
103868 ** The text is reversed here. So we are really looking at
103869 ** the first two characters of z[].
103870 */
103871 static int doubleConsonant(const char *z){
103872   return isConsonant(z) && z[0]==z[1];
103873 }
103874
103875 /*
103876 ** Return TRUE if the word ends with three letters which
103877 ** are consonant-vowel-consonent and where the final consonant
103878 ** is not 'w', 'x', or 'y'.
103879 **
103880 ** The word is reversed here.  So we are really checking the
103881 ** first three letters and the first one cannot be in [wxy].
103882 */
103883 static int star_oh(const char *z){
103884   return
103885     isConsonant(z) &&
103886     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
103887     isVowel(z+1) &&
103888     isConsonant(z+2);
103889 }
103890
103891 /*
103892 ** If the word ends with zFrom and xCond() is true for the stem
103893 ** of the word that preceeds the zFrom ending, then change the 
103894 ** ending to zTo.
103895 **
103896 ** The input word *pz and zFrom are both in reverse order.  zTo
103897 ** is in normal order. 
103898 **
103899 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
103900 ** match.  Not that TRUE is returned even if xCond() fails and
103901 ** no substitution occurs.
103902 */
103903 static int stem(
103904   char **pz,             /* The word being stemmed (Reversed) */
103905   const char *zFrom,     /* If the ending matches this... (Reversed) */
103906   const char *zTo,       /* ... change the ending to this (not reversed) */
103907   int (*xCond)(const char*)   /* Condition that must be true */
103908 ){
103909   char *z = *pz;
103910   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
103911   if( *zFrom!=0 ) return 0;
103912   if( xCond && !xCond(z) ) return 1;
103913   while( *zTo ){
103914     *(--z) = *(zTo++);
103915   }
103916   *pz = z;
103917   return 1;
103918 }
103919
103920 /*
103921 ** This is the fallback stemmer used when the porter stemmer is
103922 ** inappropriate.  The input word is copied into the output with
103923 ** US-ASCII case folding.  If the input word is too long (more
103924 ** than 20 bytes if it contains no digits or more than 6 bytes if
103925 ** it contains digits) then word is truncated to 20 or 6 bytes
103926 ** by taking 10 or 3 bytes from the beginning and end.
103927 */
103928 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
103929   int i, mx, j;
103930   int hasDigit = 0;
103931   for(i=0; i<nIn; i++){
103932     char c = zIn[i];
103933     if( c>='A' && c<='Z' ){
103934       zOut[i] = c - 'A' + 'a';
103935     }else{
103936       if( c>='0' && c<='9' ) hasDigit = 1;
103937       zOut[i] = c;
103938     }
103939   }
103940   mx = hasDigit ? 3 : 10;
103941   if( nIn>mx*2 ){
103942     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
103943       zOut[j] = zOut[i];
103944     }
103945     i = j;
103946   }
103947   zOut[i] = 0;
103948   *pnOut = i;
103949 }
103950
103951
103952 /*
103953 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
103954 ** zOut is at least big enough to hold nIn bytes.  Write the actual
103955 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
103956 **
103957 ** Any upper-case characters in the US-ASCII character set ([A-Z])
103958 ** are converted to lower case.  Upper-case UTF characters are
103959 ** unchanged.
103960 **
103961 ** Words that are longer than about 20 bytes are stemmed by retaining
103962 ** a few bytes from the beginning and the end of the word.  If the
103963 ** word contains digits, 3 bytes are taken from the beginning and
103964 ** 3 bytes from the end.  For long words without digits, 10 bytes
103965 ** are taken from each end.  US-ASCII case folding still applies.
103966 ** 
103967 ** If the input word contains not digits but does characters not 
103968 ** in [a-zA-Z] then no stemming is attempted and this routine just 
103969 ** copies the input into the input into the output with US-ASCII
103970 ** case folding.
103971 **
103972 ** Stemming never increases the length of the word.  So there is
103973 ** no chance of overflowing the zOut buffer.
103974 */
103975 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
103976   int i, j;
103977   char zReverse[28];
103978   char *z, *z2;
103979   if( nIn<3 || nIn>=sizeof(zReverse)-7 ){
103980     /* The word is too big or too small for the porter stemmer.
103981     ** Fallback to the copy stemmer */
103982     copy_stemmer(zIn, nIn, zOut, pnOut);
103983     return;
103984   }
103985   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
103986     char c = zIn[i];
103987     if( c>='A' && c<='Z' ){
103988       zReverse[j] = c + 'a' - 'A';
103989     }else if( c>='a' && c<='z' ){
103990       zReverse[j] = c;
103991     }else{
103992       /* The use of a character not in [a-zA-Z] means that we fallback
103993       ** to the copy stemmer */
103994       copy_stemmer(zIn, nIn, zOut, pnOut);
103995       return;
103996     }
103997   }
103998   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
103999   z = &zReverse[j+1];
104000
104001
104002   /* Step 1a */
104003   if( z[0]=='s' ){
104004     if(
104005      !stem(&z, "sess", "ss", 0) &&
104006      !stem(&z, "sei", "i", 0)  &&
104007      !stem(&z, "ss", "ss", 0)
104008     ){
104009       z++;
104010     }
104011   }
104012
104013   /* Step 1b */  
104014   z2 = z;
104015   if( stem(&z, "dee", "ee", m_gt_0) ){
104016     /* Do nothing.  The work was all in the test */
104017   }else if( 
104018      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
104019       && z!=z2
104020   ){
104021      if( stem(&z, "ta", "ate", 0) ||
104022          stem(&z, "lb", "ble", 0) ||
104023          stem(&z, "zi", "ize", 0) ){
104024        /* Do nothing.  The work was all in the test */
104025      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
104026        z++;
104027      }else if( m_eq_1(z) && star_oh(z) ){
104028        *(--z) = 'e';
104029      }
104030   }
104031
104032   /* Step 1c */
104033   if( z[0]=='y' && hasVowel(z+1) ){
104034     z[0] = 'i';
104035   }
104036
104037   /* Step 2 */
104038   switch( z[1] ){
104039    case 'a':
104040      stem(&z, "lanoita", "ate", m_gt_0) ||
104041      stem(&z, "lanoit", "tion", m_gt_0);
104042      break;
104043    case 'c':
104044      stem(&z, "icne", "ence", m_gt_0) ||
104045      stem(&z, "icna", "ance", m_gt_0);
104046      break;
104047    case 'e':
104048      stem(&z, "rezi", "ize", m_gt_0);
104049      break;
104050    case 'g':
104051      stem(&z, "igol", "log", m_gt_0);
104052      break;
104053    case 'l':
104054      stem(&z, "ilb", "ble", m_gt_0) ||
104055      stem(&z, "illa", "al", m_gt_0) ||
104056      stem(&z, "iltne", "ent", m_gt_0) ||
104057      stem(&z, "ile", "e", m_gt_0) ||
104058      stem(&z, "ilsuo", "ous", m_gt_0);
104059      break;
104060    case 'o':
104061      stem(&z, "noitazi", "ize", m_gt_0) ||
104062      stem(&z, "noita", "ate", m_gt_0) ||
104063      stem(&z, "rota", "ate", m_gt_0);
104064      break;
104065    case 's':
104066      stem(&z, "msila", "al", m_gt_0) ||
104067      stem(&z, "ssenevi", "ive", m_gt_0) ||
104068      stem(&z, "ssenluf", "ful", m_gt_0) ||
104069      stem(&z, "ssensuo", "ous", m_gt_0);
104070      break;
104071    case 't':
104072      stem(&z, "itila", "al", m_gt_0) ||
104073      stem(&z, "itivi", "ive", m_gt_0) ||
104074      stem(&z, "itilib", "ble", m_gt_0);
104075      break;
104076   }
104077
104078   /* Step 3 */
104079   switch( z[0] ){
104080    case 'e':
104081      stem(&z, "etaci", "ic", m_gt_0) ||
104082      stem(&z, "evita", "", m_gt_0)   ||
104083      stem(&z, "ezila", "al", m_gt_0);
104084      break;
104085    case 'i':
104086      stem(&z, "itici", "ic", m_gt_0);
104087      break;
104088    case 'l':
104089      stem(&z, "laci", "ic", m_gt_0) ||
104090      stem(&z, "luf", "", m_gt_0);
104091      break;
104092    case 's':
104093      stem(&z, "ssen", "", m_gt_0);
104094      break;
104095   }
104096
104097   /* Step 4 */
104098   switch( z[1] ){
104099    case 'a':
104100      if( z[0]=='l' && m_gt_1(z+2) ){
104101        z += 2;
104102      }
104103      break;
104104    case 'c':
104105      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
104106        z += 4;
104107      }
104108      break;
104109    case 'e':
104110      if( z[0]=='r' && m_gt_1(z+2) ){
104111        z += 2;
104112      }
104113      break;
104114    case 'i':
104115      if( z[0]=='c' && m_gt_1(z+2) ){
104116        z += 2;
104117      }
104118      break;
104119    case 'l':
104120      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
104121        z += 4;
104122      }
104123      break;
104124    case 'n':
104125      if( z[0]=='t' ){
104126        if( z[2]=='a' ){
104127          if( m_gt_1(z+3) ){
104128            z += 3;
104129          }
104130        }else if( z[2]=='e' ){
104131          stem(&z, "tneme", "", m_gt_1) ||
104132          stem(&z, "tnem", "", m_gt_1) ||
104133          stem(&z, "tne", "", m_gt_1);
104134        }
104135      }
104136      break;
104137    case 'o':
104138      if( z[0]=='u' ){
104139        if( m_gt_1(z+2) ){
104140          z += 2;
104141        }
104142      }else if( z[3]=='s' || z[3]=='t' ){
104143        stem(&z, "noi", "", m_gt_1);
104144      }
104145      break;
104146    case 's':
104147      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
104148        z += 3;
104149      }
104150      break;
104151    case 't':
104152      stem(&z, "eta", "", m_gt_1) ||
104153      stem(&z, "iti", "", m_gt_1);
104154      break;
104155    case 'u':
104156      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
104157        z += 3;
104158      }
104159      break;
104160    case 'v':
104161    case 'z':
104162      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
104163        z += 3;
104164      }
104165      break;
104166   }
104167
104168   /* Step 5a */
104169   if( z[0]=='e' ){
104170     if( m_gt_1(z+1) ){
104171       z++;
104172     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
104173       z++;
104174     }
104175   }
104176
104177   /* Step 5b */
104178   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
104179     z++;
104180   }
104181
104182   /* z[] is now the stemmed word in reverse order.  Flip it back
104183   ** around into forward order and return.
104184   */
104185   *pnOut = i = (int)strlen(z);
104186   zOut[i] = 0;
104187   while( *z ){
104188     zOut[--i] = *(z++);
104189   }
104190 }
104191
104192 /*
104193 ** Characters that can be part of a token.  We assume any character
104194 ** whose value is greater than 0x80 (any UTF character) can be
104195 ** part of a token.  In other words, delimiters all must have
104196 ** values of 0x7f or lower.
104197 */
104198 static const char porterIdChar[] = {
104199 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
104200     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
104201     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
104202     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
104203     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
104204     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
104205 };
104206 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
104207
104208 /*
104209 ** Extract the next token from a tokenization cursor.  The cursor must
104210 ** have been opened by a prior call to porterOpen().
104211 */
104212 static int porterNext(
104213   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
104214   const char **pzToken,               /* OUT: *pzToken is the token text */
104215   int *pnBytes,                       /* OUT: Number of bytes in token */
104216   int *piStartOffset,                 /* OUT: Starting offset of token */
104217   int *piEndOffset,                   /* OUT: Ending offset of token */
104218   int *piPosition                     /* OUT: Position integer of token */
104219 ){
104220   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
104221   const char *z = c->zInput;
104222
104223   while( c->iOffset<c->nInput ){
104224     int iStartOffset, ch;
104225
104226     /* Scan past delimiter characters */
104227     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
104228       c->iOffset++;
104229     }
104230
104231     /* Count non-delimiter characters. */
104232     iStartOffset = c->iOffset;
104233     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
104234       c->iOffset++;
104235     }
104236
104237     if( c->iOffset>iStartOffset ){
104238       int n = c->iOffset-iStartOffset;
104239       if( n>c->nAllocated ){
104240         char *pNew;
104241         c->nAllocated = n+20;
104242         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
104243         if( !pNew ) return SQLITE_NOMEM;
104244         c->zToken = pNew;
104245       }
104246       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
104247       *pzToken = c->zToken;
104248       *piStartOffset = iStartOffset;
104249       *piEndOffset = c->iOffset;
104250       *piPosition = c->iToken++;
104251       return SQLITE_OK;
104252     }
104253   }
104254   return SQLITE_DONE;
104255 }
104256
104257 /*
104258 ** The set of routines that implement the porter-stemmer tokenizer
104259 */
104260 static const sqlite3_tokenizer_module porterTokenizerModule = {
104261   0,
104262   porterCreate,
104263   porterDestroy,
104264   porterOpen,
104265   porterClose,
104266   porterNext,
104267 };
104268
104269 /*
104270 ** Allocate a new porter tokenizer.  Return a pointer to the new
104271 ** tokenizer in *ppModule
104272 */
104273 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
104274   sqlite3_tokenizer_module const**ppModule
104275 ){
104276   *ppModule = &porterTokenizerModule;
104277 }
104278
104279 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
104280
104281 /************** End of fts3_porter.c *****************************************/
104282 /************** Begin file fts3_tokenizer.c **********************************/
104283 /*
104284 ** 2007 June 22
104285 **
104286 ** The author disclaims copyright to this source code.  In place of
104287 ** a legal notice, here is a blessing:
104288 **
104289 **    May you do good and not evil.
104290 **    May you find forgiveness for yourself and forgive others.
104291 **    May you share freely, never taking more than you give.
104292 **
104293 ******************************************************************************
104294 **
104295 ** This is part of an SQLite module implementing full-text search.
104296 ** This particular file implements the generic tokenizer interface.
104297 */
104298
104299 /*
104300 ** The code in this file is only compiled if:
104301 **
104302 **     * The FTS3 module is being built as an extension
104303 **       (in which case SQLITE_CORE is not defined), or
104304 **
104305 **     * The FTS3 module is being built into the core of
104306 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
104307 */
104308 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
104309
104310 #ifndef SQLITE_CORE
104311   SQLITE_EXTENSION_INIT1
104312 #endif
104313
104314
104315 /*
104316 ** Implementation of the SQL scalar function for accessing the underlying 
104317 ** hash table. This function may be called as follows:
104318 **
104319 **   SELECT <function-name>(<key-name>);
104320 **   SELECT <function-name>(<key-name>, <pointer>);
104321 **
104322 ** where <function-name> is the name passed as the second argument
104323 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
104324 **
104325 ** If the <pointer> argument is specified, it must be a blob value
104326 ** containing a pointer to be stored as the hash data corresponding
104327 ** to the string <key-name>. If <pointer> is not specified, then
104328 ** the string <key-name> must already exist in the has table. Otherwise,
104329 ** an error is returned.
104330 **
104331 ** Whether or not the <pointer> argument is specified, the value returned
104332 ** is a blob containing the pointer stored as the hash data corresponding
104333 ** to string <key-name> (after the hash-table is updated, if applicable).
104334 */
104335 static void scalarFunc(
104336   sqlite3_context *context,
104337   int argc,
104338   sqlite3_value **argv
104339 ){
104340   Fts3Hash *pHash;
104341   void *pPtr = 0;
104342   const unsigned char *zName;
104343   int nName;
104344
104345   assert( argc==1 || argc==2 );
104346
104347   pHash = (Fts3Hash *)sqlite3_user_data(context);
104348
104349   zName = sqlite3_value_text(argv[0]);
104350   nName = sqlite3_value_bytes(argv[0])+1;
104351
104352   if( argc==2 ){
104353     void *pOld;
104354     int n = sqlite3_value_bytes(argv[1]);
104355     if( n!=sizeof(pPtr) ){
104356       sqlite3_result_error(context, "argument type mismatch", -1);
104357       return;
104358     }
104359     pPtr = *(void **)sqlite3_value_blob(argv[1]);
104360     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
104361     if( pOld==pPtr ){
104362       sqlite3_result_error(context, "out of memory", -1);
104363       return;
104364     }
104365   }else{
104366     pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
104367     if( !pPtr ){
104368       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
104369       sqlite3_result_error(context, zErr, -1);
104370       sqlite3_free(zErr);
104371       return;
104372     }
104373   }
104374
104375   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
104376 }
104377
104378 static int fts3IsIdChar(char c){
104379   static const char isFtsIdChar[] = {
104380       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
104381       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
104382       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
104383       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
104384       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
104385       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
104386       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
104387       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
104388   };
104389   return (c&0x80 || isFtsIdChar[(int)(c)]);
104390 }
104391
104392 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
104393   const char *z1;
104394   const char *z2 = 0;
104395
104396   /* Find the start of the next token. */
104397   z1 = zStr;
104398   while( z2==0 ){
104399     char c = *z1;
104400     switch( c ){
104401       case '\0': return 0;        /* No more tokens here */
104402       case '\'':
104403       case '"':
104404       case '`': {
104405         z2 = z1;
104406         while( *++z2 && (*z2!=c || *++z2==c) );
104407         break;
104408       }
104409       case '[':
104410         z2 = &z1[1];
104411         while( *z2 && z2[0]!=']' ) z2++;
104412         if( *z2 ) z2++;
104413         break;
104414
104415       default:
104416         if( fts3IsIdChar(*z1) ){
104417           z2 = &z1[1];
104418           while( fts3IsIdChar(*z2) ) z2++;
104419         }else{
104420           z1++;
104421         }
104422     }
104423   }
104424
104425   *pn = (int)(z2-z1);
104426   return z1;
104427 }
104428
104429 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
104430   Fts3Hash *pHash,                /* Tokenizer hash table */
104431   const char *zArg,               /* Possible tokenizer specification */
104432   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
104433   const char **pzTokenizer,       /* OUT: Set to zArg if is tokenizer */
104434   char **pzErr                    /* OUT: Set to malloced error message */
104435 ){
104436   int rc;
104437   char *z = (char *)zArg;
104438   int n;
104439   char *zCopy;
104440   char *zEnd;                     /* Pointer to nul-term of zCopy */
104441   sqlite3_tokenizer_module *m;
104442
104443   if( !z ){
104444     zCopy = sqlite3_mprintf("simple");
104445   }else{
104446     if( sqlite3_strnicmp(z, "tokenize", 8) || fts3IsIdChar(z[8])){
104447       return SQLITE_OK;
104448     }
104449     zCopy = sqlite3_mprintf("%s", &z[8]);
104450     *pzTokenizer = zArg;
104451   }
104452   if( !zCopy ){
104453     return SQLITE_NOMEM;
104454   }
104455
104456   zEnd = &zCopy[strlen(zCopy)];
104457
104458   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
104459   z[n] = '\0';
104460   sqlite3Fts3Dequote(z);
104461
104462   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, z, (int)strlen(z)+1);
104463   if( !m ){
104464     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
104465     rc = SQLITE_ERROR;
104466   }else{
104467     char const **aArg = 0;
104468     int iArg = 0;
104469     z = &z[n+1];
104470     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
104471       int nNew = sizeof(char *)*(iArg+1);
104472       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
104473       if( !aNew ){
104474         sqlite3_free(zCopy);
104475         sqlite3_free((void *)aArg);
104476         return SQLITE_NOMEM;
104477       }
104478       aArg = aNew;
104479       aArg[iArg++] = z;
104480       z[n] = '\0';
104481       sqlite3Fts3Dequote(z);
104482       z = &z[n+1];
104483     }
104484     rc = m->xCreate(iArg, aArg, ppTok);
104485     assert( rc!=SQLITE_OK || *ppTok );
104486     if( rc!=SQLITE_OK ){
104487       *pzErr = sqlite3_mprintf("unknown tokenizer");
104488     }else{
104489       (*ppTok)->pModule = m; 
104490     }
104491     sqlite3_free((void *)aArg);
104492   }
104493
104494   sqlite3_free(zCopy);
104495   return rc;
104496 }
104497
104498
104499 #ifdef SQLITE_TEST
104500
104501
104502 /*
104503 ** Implementation of a special SQL scalar function for testing tokenizers 
104504 ** designed to be used in concert with the Tcl testing framework. This
104505 ** function must be called with two arguments:
104506 **
104507 **   SELECT <function-name>(<key-name>, <input-string>);
104508 **   SELECT <function-name>(<key-name>, <pointer>);
104509 **
104510 ** where <function-name> is the name passed as the second argument
104511 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
104512 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
104513 **
104514 ** The return value is a string that may be interpreted as a Tcl
104515 ** list. For each token in the <input-string>, three elements are
104516 ** added to the returned list. The first is the token position, the 
104517 ** second is the token text (folded, stemmed, etc.) and the third is the
104518 ** substring of <input-string> associated with the token. For example, 
104519 ** using the built-in "simple" tokenizer:
104520 **
104521 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
104522 **
104523 ** will return the string:
104524 **
104525 **   "{0 i I 1 dont don't 2 see see 3 how how}"
104526 **   
104527 */
104528 static void testFunc(
104529   sqlite3_context *context,
104530   int argc,
104531   sqlite3_value **argv
104532 ){
104533   Fts3Hash *pHash;
104534   sqlite3_tokenizer_module *p;
104535   sqlite3_tokenizer *pTokenizer = 0;
104536   sqlite3_tokenizer_cursor *pCsr = 0;
104537
104538   const char *zErr = 0;
104539
104540   const char *zName;
104541   int nName;
104542   const char *zInput;
104543   int nInput;
104544
104545   const char *zArg = 0;
104546
104547   const char *zToken;
104548   int nToken;
104549   int iStart;
104550   int iEnd;
104551   int iPos;
104552
104553   Tcl_Obj *pRet;
104554
104555   assert( argc==2 || argc==3 );
104556
104557   nName = sqlite3_value_bytes(argv[0]);
104558   zName = (const char *)sqlite3_value_text(argv[0]);
104559   nInput = sqlite3_value_bytes(argv[argc-1]);
104560   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
104561
104562   if( argc==3 ){
104563     zArg = (const char *)sqlite3_value_text(argv[1]);
104564   }
104565
104566   pHash = (Fts3Hash *)sqlite3_user_data(context);
104567   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
104568
104569   if( !p ){
104570     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
104571     sqlite3_result_error(context, zErr, -1);
104572     sqlite3_free(zErr);
104573     return;
104574   }
104575
104576   pRet = Tcl_NewObj();
104577   Tcl_IncrRefCount(pRet);
104578
104579   if( SQLITE_OK!=p->xCreate(zArg ? 1 : 0, &zArg, &pTokenizer) ){
104580     zErr = "error in xCreate()";
104581     goto finish;
104582   }
104583   pTokenizer->pModule = p;
104584   if( SQLITE_OK!=p->xOpen(pTokenizer, zInput, nInput, &pCsr) ){
104585     zErr = "error in xOpen()";
104586     goto finish;
104587   }
104588   pCsr->pTokenizer = pTokenizer;
104589
104590   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
104591     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
104592     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
104593     zToken = &zInput[iStart];
104594     nToken = iEnd-iStart;
104595     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
104596   }
104597
104598   if( SQLITE_OK!=p->xClose(pCsr) ){
104599     zErr = "error in xClose()";
104600     goto finish;
104601   }
104602   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
104603     zErr = "error in xDestroy()";
104604     goto finish;
104605   }
104606
104607 finish:
104608   if( zErr ){
104609     sqlite3_result_error(context, zErr, -1);
104610   }else{
104611     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
104612   }
104613   Tcl_DecrRefCount(pRet);
104614 }
104615
104616 static
104617 int registerTokenizer(
104618   sqlite3 *db, 
104619   char *zName, 
104620   const sqlite3_tokenizer_module *p
104621 ){
104622   int rc;
104623   sqlite3_stmt *pStmt;
104624   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
104625
104626   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
104627   if( rc!=SQLITE_OK ){
104628     return rc;
104629   }
104630
104631   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
104632   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
104633   sqlite3_step(pStmt);
104634
104635   return sqlite3_finalize(pStmt);
104636 }
104637
104638 static
104639 int queryTokenizer(
104640   sqlite3 *db, 
104641   char *zName,  
104642   const sqlite3_tokenizer_module **pp
104643 ){
104644   int rc;
104645   sqlite3_stmt *pStmt;
104646   const char zSql[] = "SELECT fts3_tokenizer(?)";
104647
104648   *pp = 0;
104649   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
104650   if( rc!=SQLITE_OK ){
104651     return rc;
104652   }
104653
104654   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
104655   if( SQLITE_ROW==sqlite3_step(pStmt) ){
104656     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
104657       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
104658     }
104659   }
104660
104661   return sqlite3_finalize(pStmt);
104662 }
104663
104664 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
104665
104666 /*
104667 ** Implementation of the scalar function fts3_tokenizer_internal_test().
104668 ** This function is used for testing only, it is not included in the
104669 ** build unless SQLITE_TEST is defined.
104670 **
104671 ** The purpose of this is to test that the fts3_tokenizer() function
104672 ** can be used as designed by the C-code in the queryTokenizer and
104673 ** registerTokenizer() functions above. These two functions are repeated
104674 ** in the README.tokenizer file as an example, so it is important to
104675 ** test them.
104676 **
104677 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
104678 ** function with no arguments. An assert() will fail if a problem is
104679 ** detected. i.e.:
104680 **
104681 **     SELECT fts3_tokenizer_internal_test();
104682 **
104683 */
104684 static void intTestFunc(
104685   sqlite3_context *context,
104686   int argc,
104687   sqlite3_value **argv
104688 ){
104689   int rc;
104690   const sqlite3_tokenizer_module *p1;
104691   const sqlite3_tokenizer_module *p2;
104692   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
104693
104694   UNUSED_PARAMETER(argc);
104695   UNUSED_PARAMETER(argv);
104696
104697   /* Test the query function */
104698   sqlite3Fts3SimpleTokenizerModule(&p1);
104699   rc = queryTokenizer(db, "simple", &p2);
104700   assert( rc==SQLITE_OK );
104701   assert( p1==p2 );
104702   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
104703   assert( rc==SQLITE_ERROR );
104704   assert( p2==0 );
104705   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
104706
104707   /* Test the storage function */
104708   rc = registerTokenizer(db, "nosuchtokenizer", p1);
104709   assert( rc==SQLITE_OK );
104710   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
104711   assert( rc==SQLITE_OK );
104712   assert( p2==p1 );
104713
104714   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
104715 }
104716
104717 #endif
104718
104719 /*
104720 ** Set up SQL objects in database db used to access the contents of
104721 ** the hash table pointed to by argument pHash. The hash table must
104722 ** been initialised to use string keys, and to take a private copy 
104723 ** of the key when a value is inserted. i.e. by a call similar to:
104724 **
104725 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
104726 **
104727 ** This function adds a scalar function (see header comment above
104728 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
104729 ** defined at compilation time, a temporary virtual table (see header 
104730 ** comment above struct HashTableVtab) to the database schema. Both 
104731 ** provide read/write access to the contents of *pHash.
104732 **
104733 ** The third argument to this function, zName, is used as the name
104734 ** of both the scalar and, if created, the virtual table.
104735 */
104736 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
104737   sqlite3 *db, 
104738   Fts3Hash *pHash, 
104739   const char *zName
104740 ){
104741   int rc = SQLITE_OK;
104742   void *p = (void *)pHash;
104743   const int any = SQLITE_ANY;
104744
104745 #ifdef SQLITE_TEST
104746   char *zTest = 0;
104747   char *zTest2 = 0;
104748   void *pdb = (void *)db;
104749   zTest = sqlite3_mprintf("%s_test", zName);
104750   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
104751   if( !zTest || !zTest2 ){
104752     rc = SQLITE_NOMEM;
104753   }
104754 #endif
104755
104756   if( SQLITE_OK!=rc
104757    || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0))
104758    || SQLITE_OK!=(rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0))
104759 #ifdef SQLITE_TEST
104760    || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 2, any, p, testFunc, 0, 0))
104761    || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest, 3, any, p, testFunc, 0, 0))
104762    || SQLITE_OK!=(rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0))
104763 #endif
104764    );
104765
104766 #ifdef SQLITE_TEST
104767   sqlite3_free(zTest);
104768   sqlite3_free(zTest2);
104769 #endif
104770
104771   return rc;
104772 }
104773
104774 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
104775
104776 /************** End of fts3_tokenizer.c **************************************/
104777 /************** Begin file fts3_tokenizer1.c *********************************/
104778 /*
104779 ** 2006 Oct 10
104780 **
104781 ** The author disclaims copyright to this source code.  In place of
104782 ** a legal notice, here is a blessing:
104783 **
104784 **    May you do good and not evil.
104785 **    May you find forgiveness for yourself and forgive others.
104786 **    May you share freely, never taking more than you give.
104787 **
104788 ******************************************************************************
104789 **
104790 ** Implementation of the "simple" full-text-search tokenizer.
104791 */
104792
104793 /*
104794 ** The code in this file is only compiled if:
104795 **
104796 **     * The FTS3 module is being built as an extension
104797 **       (in which case SQLITE_CORE is not defined), or
104798 **
104799 **     * The FTS3 module is being built into the core of
104800 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
104801 */
104802 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
104803
104804
104805
104806
104807 typedef struct simple_tokenizer {
104808   sqlite3_tokenizer base;
104809   char delim[128];             /* flag ASCII delimiters */
104810 } simple_tokenizer;
104811
104812 typedef struct simple_tokenizer_cursor {
104813   sqlite3_tokenizer_cursor base;
104814   const char *pInput;          /* input we are tokenizing */
104815   int nBytes;                  /* size of the input */
104816   int iOffset;                 /* current position in pInput */
104817   int iToken;                  /* index of next token to be returned */
104818   char *pToken;                /* storage for current token */
104819   int nTokenAllocated;         /* space allocated to zToken buffer */
104820 } simple_tokenizer_cursor;
104821
104822
104823 static int simpleDelim(simple_tokenizer *t, unsigned char c){
104824   return c<0x80 && t->delim[c];
104825 }
104826
104827 /*
104828 ** Create a new tokenizer instance.
104829 */
104830 static int simpleCreate(
104831   int argc, const char * const *argv,
104832   sqlite3_tokenizer **ppTokenizer
104833 ){
104834   simple_tokenizer *t;
104835
104836   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
104837   if( t==NULL ) return SQLITE_NOMEM;
104838   memset(t, 0, sizeof(*t));
104839
104840   /* TODO(shess) Delimiters need to remain the same from run to run,
104841   ** else we need to reindex.  One solution would be a meta-table to
104842   ** track such information in the database, then we'd only want this
104843   ** information on the initial create.
104844   */
104845   if( argc>1 ){
104846     int i, n = (int)strlen(argv[1]);
104847     for(i=0; i<n; i++){
104848       unsigned char ch = argv[1][i];
104849       /* We explicitly don't support UTF-8 delimiters for now. */
104850       if( ch>=0x80 ){
104851         sqlite3_free(t);
104852         return SQLITE_ERROR;
104853       }
104854       t->delim[ch] = 1;
104855     }
104856   } else {
104857     /* Mark non-alphanumeric ASCII characters as delimiters */
104858     int i;
104859     for(i=1; i<0x80; i++){
104860       t->delim[i] = !isalnum(i) ? -1 : 0;
104861     }
104862   }
104863
104864   *ppTokenizer = &t->base;
104865   return SQLITE_OK;
104866 }
104867
104868 /*
104869 ** Destroy a tokenizer
104870 */
104871 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
104872   sqlite3_free(pTokenizer);
104873   return SQLITE_OK;
104874 }
104875
104876 /*
104877 ** Prepare to begin tokenizing a particular string.  The input
104878 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
104879 ** used to incrementally tokenize this string is returned in 
104880 ** *ppCursor.
104881 */
104882 static int simpleOpen(
104883   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
104884   const char *pInput, int nBytes,        /* String to be tokenized */
104885   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
104886 ){
104887   simple_tokenizer_cursor *c;
104888
104889   UNUSED_PARAMETER(pTokenizer);
104890
104891   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
104892   if( c==NULL ) return SQLITE_NOMEM;
104893
104894   c->pInput = pInput;
104895   if( pInput==0 ){
104896     c->nBytes = 0;
104897   }else if( nBytes<0 ){
104898     c->nBytes = (int)strlen(pInput);
104899   }else{
104900     c->nBytes = nBytes;
104901   }
104902   c->iOffset = 0;                 /* start tokenizing at the beginning */
104903   c->iToken = 0;
104904   c->pToken = NULL;               /* no space allocated, yet. */
104905   c->nTokenAllocated = 0;
104906
104907   *ppCursor = &c->base;
104908   return SQLITE_OK;
104909 }
104910
104911 /*
104912 ** Close a tokenization cursor previously opened by a call to
104913 ** simpleOpen() above.
104914 */
104915 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
104916   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
104917   sqlite3_free(c->pToken);
104918   sqlite3_free(c);
104919   return SQLITE_OK;
104920 }
104921
104922 /*
104923 ** Extract the next token from a tokenization cursor.  The cursor must
104924 ** have been opened by a prior call to simpleOpen().
104925 */
104926 static int simpleNext(
104927   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
104928   const char **ppToken,               /* OUT: *ppToken is the token text */
104929   int *pnBytes,                       /* OUT: Number of bytes in token */
104930   int *piStartOffset,                 /* OUT: Starting offset of token */
104931   int *piEndOffset,                   /* OUT: Ending offset of token */
104932   int *piPosition                     /* OUT: Position integer of token */
104933 ){
104934   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
104935   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
104936   unsigned char *p = (unsigned char *)c->pInput;
104937
104938   while( c->iOffset<c->nBytes ){
104939     int iStartOffset;
104940
104941     /* Scan past delimiter characters */
104942     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
104943       c->iOffset++;
104944     }
104945
104946     /* Count non-delimiter characters. */
104947     iStartOffset = c->iOffset;
104948     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
104949       c->iOffset++;
104950     }
104951
104952     if( c->iOffset>iStartOffset ){
104953       int i, n = c->iOffset-iStartOffset;
104954       if( n>c->nTokenAllocated ){
104955         char *pNew;
104956         c->nTokenAllocated = n+20;
104957         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
104958         if( !pNew ) return SQLITE_NOMEM;
104959         c->pToken = pNew;
104960       }
104961       for(i=0; i<n; i++){
104962         /* TODO(shess) This needs expansion to handle UTF-8
104963         ** case-insensitivity.
104964         */
104965         unsigned char ch = p[iStartOffset+i];
104966         c->pToken[i] = (char)(ch<0x80 ? tolower(ch) : ch);
104967       }
104968       *ppToken = c->pToken;
104969       *pnBytes = n;
104970       *piStartOffset = iStartOffset;
104971       *piEndOffset = c->iOffset;
104972       *piPosition = c->iToken++;
104973
104974       return SQLITE_OK;
104975     }
104976   }
104977   return SQLITE_DONE;
104978 }
104979
104980 /*
104981 ** The set of routines that implement the simple tokenizer
104982 */
104983 static const sqlite3_tokenizer_module simpleTokenizerModule = {
104984   0,
104985   simpleCreate,
104986   simpleDestroy,
104987   simpleOpen,
104988   simpleClose,
104989   simpleNext,
104990 };
104991
104992 /*
104993 ** Allocate a new simple tokenizer.  Return a pointer to the new
104994 ** tokenizer in *ppModule
104995 */
104996 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
104997   sqlite3_tokenizer_module const**ppModule
104998 ){
104999   *ppModule = &simpleTokenizerModule;
105000 }
105001
105002 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
105003
105004 /************** End of fts3_tokenizer1.c *************************************/
105005 /************** Begin file fts3_write.c **************************************/
105006 /*
105007 ** 2009 Oct 23
105008 **
105009 ** The author disclaims copyright to this source code.  In place of
105010 ** a legal notice, here is a blessing:
105011 **
105012 **    May you do good and not evil.
105013 **    May you find forgiveness for yourself and forgive others.
105014 **    May you share freely, never taking more than you give.
105015 **
105016 ******************************************************************************
105017 **
105018 ** This file is part of the SQLite FTS3 extension module. Specifically,
105019 ** this file contains code to insert, update and delete rows from FTS3
105020 ** tables. It also contains code to merge FTS3 b-tree segments. Some
105021 ** of the sub-routines used to merge segments are also used by the query 
105022 ** code in fts3.c.
105023 */
105024
105025 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
105026
105027
105028 typedef struct PendingList PendingList;
105029 typedef struct SegmentNode SegmentNode;
105030 typedef struct SegmentWriter SegmentWriter;
105031
105032 /*
105033 ** Data structure used while accumulating terms in the pending-terms hash
105034 ** table. The hash table entry maps from term (a string) to a malloc'd
105035 ** instance of this structure.
105036 */
105037 struct PendingList {
105038   int nData;
105039   char *aData;
105040   int nSpace;
105041   sqlite3_int64 iLastDocid;
105042   sqlite3_int64 iLastCol;
105043   sqlite3_int64 iLastPos;
105044 };
105045
105046 /*
105047 ** An instance of this structure is used to iterate through the terms on
105048 ** a contiguous set of segment b-tree leaf nodes. Although the details of
105049 ** this structure are only manipulated by code in this file, opaque handles
105050 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
105051 ** terms when querying the full-text index. See functions:
105052 **
105053 **   sqlite3Fts3SegReaderNew()
105054 **   sqlite3Fts3SegReaderFree()
105055 **   sqlite3Fts3SegReaderIterate()
105056 **
105057 ** Methods used to manipulate Fts3SegReader structures:
105058 **
105059 **   fts3SegReaderNext()
105060 **   fts3SegReaderFirstDocid()
105061 **   fts3SegReaderNextDocid()
105062 */
105063 struct Fts3SegReader {
105064   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
105065   sqlite3_int64 iStartBlock;
105066   sqlite3_int64 iEndBlock;
105067   sqlite3_stmt *pStmt;            /* SQL Statement to access leaf nodes */
105068   char *aNode;                    /* Pointer to node data (or NULL) */
105069   int nNode;                      /* Size of buffer at aNode (or 0) */
105070   int nTermAlloc;                 /* Allocated size of zTerm buffer */
105071   Fts3HashElem **ppNextElem;
105072
105073   /* Variables set by fts3SegReaderNext(). These may be read directly
105074   ** by the caller. They are valid from the time SegmentReaderNew() returns
105075   ** until SegmentReaderNext() returns something other than SQLITE_OK
105076   ** (i.e. SQLITE_DONE).
105077   */
105078   int nTerm;                      /* Number of bytes in current term */
105079   char *zTerm;                    /* Pointer to current term */
105080   char *aDoclist;                 /* Pointer to doclist of current entry */
105081   int nDoclist;                   /* Size of doclist in current entry */
105082
105083   /* The following variables are used to iterate through the current doclist */
105084   char *pOffsetList;
105085   sqlite3_int64 iDocid;
105086 };
105087
105088 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
105089
105090 /*
105091 ** An instance of this structure is used to create a segment b-tree in the
105092 ** database. The internal details of this type are only accessed by the
105093 ** following functions:
105094 **
105095 **   fts3SegWriterAdd()
105096 **   fts3SegWriterFlush()
105097 **   fts3SegWriterFree()
105098 */
105099 struct SegmentWriter {
105100   SegmentNode *pTree;             /* Pointer to interior tree structure */
105101   sqlite3_int64 iFirst;           /* First slot in %_segments written */
105102   sqlite3_int64 iFree;            /* Next free slot in %_segments */
105103   char *zTerm;                    /* Pointer to previous term buffer */
105104   int nTerm;                      /* Number of bytes in zTerm */
105105   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
105106   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
105107   int nSize;                      /* Size of allocation at aData */
105108   int nData;                      /* Bytes of data in aData */
105109   char *aData;                    /* Pointer to block from malloc() */
105110 };
105111
105112 /*
105113 ** Type SegmentNode is used by the following three functions to create
105114 ** the interior part of the segment b+-tree structures (everything except
105115 ** the leaf nodes). These functions and type are only ever used by code
105116 ** within the fts3SegWriterXXX() family of functions described above.
105117 **
105118 **   fts3NodeAddTerm()
105119 **   fts3NodeWrite()
105120 **   fts3NodeFree()
105121 */
105122 struct SegmentNode {
105123   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
105124   SegmentNode *pRight;            /* Pointer to right-sibling */
105125   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
105126   int nEntry;                     /* Number of terms written to node so far */
105127   char *zTerm;                    /* Pointer to previous term buffer */
105128   int nTerm;                      /* Number of bytes in zTerm */
105129   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
105130   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
105131   int nData;                      /* Bytes of valid data so far */
105132   char *aData;                    /* Node data */
105133 };
105134
105135 /*
105136 ** Valid values for the second argument to fts3SqlStmt().
105137 */
105138 #define SQL_DELETE_CONTENT             0
105139 #define SQL_IS_EMPTY                   1
105140 #define SQL_DELETE_ALL_CONTENT         2 
105141 #define SQL_DELETE_ALL_SEGMENTS        3
105142 #define SQL_DELETE_ALL_SEGDIR          4
105143 #define SQL_DELETE_ALL_DOCSIZE         5
105144 #define SQL_DELETE_ALL_STAT            6
105145 #define SQL_SELECT_CONTENT_BY_ROWID    7
105146 #define SQL_NEXT_SEGMENT_INDEX         8
105147 #define SQL_INSERT_SEGMENTS            9
105148 #define SQL_NEXT_SEGMENTS_ID          10
105149 #define SQL_INSERT_SEGDIR             11
105150 #define SQL_SELECT_LEVEL              12
105151 #define SQL_SELECT_ALL_LEVEL          13
105152 #define SQL_SELECT_LEVEL_COUNT        14
105153 #define SQL_SELECT_SEGDIR_COUNT_MAX   15
105154 #define SQL_DELETE_SEGDIR_BY_LEVEL    16
105155 #define SQL_DELETE_SEGMENTS_RANGE     17
105156 #define SQL_CONTENT_INSERT            18
105157 #define SQL_GET_BLOCK                 19
105158 #define SQL_DELETE_DOCSIZE            20
105159 #define SQL_REPLACE_DOCSIZE           21
105160 #define SQL_SELECT_DOCSIZE            22
105161 #define SQL_SELECT_DOCTOTAL           23
105162 #define SQL_REPLACE_DOCTOTAL          24
105163
105164 /*
105165 ** This function is used to obtain an SQLite prepared statement handle
105166 ** for the statement identified by the second argument. If successful,
105167 ** *pp is set to the requested statement handle and SQLITE_OK returned.
105168 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
105169 **
105170 ** If argument apVal is not NULL, then it must point to an array with
105171 ** at least as many entries as the requested statement has bound 
105172 ** parameters. The values are bound to the statements parameters before
105173 ** returning.
105174 */
105175 static int fts3SqlStmt(
105176   Fts3Table *p,                   /* Virtual table handle */
105177   int eStmt,                      /* One of the SQL_XXX constants above */
105178   sqlite3_stmt **pp,              /* OUT: Statement handle */
105179   sqlite3_value **apVal           /* Values to bind to statement */
105180 ){
105181   const char *azSql[] = {
105182 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
105183 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
105184 /* 2  */  "DELETE FROM %Q.'%q_content'",
105185 /* 3  */  "DELETE FROM %Q.'%q_segments'",
105186 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
105187 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
105188 /* 6  */  "DELETE FROM %Q.'%q_stat'",
105189 /* 7  */  "SELECT * FROM %Q.'%q_content' WHERE rowid=?",
105190 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
105191 /* 9  */  "INSERT INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
105192 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
105193 /* 11 */  "INSERT INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
105194
105195           /* Return segments in order from oldest to newest.*/ 
105196 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
105197             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
105198 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
105199             "FROM %Q.'%q_segdir' ORDER BY level DESC, idx ASC",
105200
105201 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
105202 /* 15 */  "SELECT count(*), max(level) FROM %Q.'%q_segdir'",
105203
105204 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
105205 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
105206 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%z)",
105207 /* 19 */  "SELECT block FROM %Q.'%q_segments' WHERE blockid = ?",
105208 /* 20 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
105209 /* 21 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
105210 /* 22 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
105211 /* 23 */  "SELECT value FROM %Q.'%q_stat' WHERE id=0",
105212 /* 24 */  "REPLACE INTO %Q.'%q_stat' VALUES(0,?)",
105213   };
105214   int rc = SQLITE_OK;
105215   sqlite3_stmt *pStmt;
105216
105217   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
105218   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
105219   
105220   pStmt = p->aStmt[eStmt];
105221   if( !pStmt ){
105222     char *zSql;
105223     if( eStmt==SQL_CONTENT_INSERT ){
105224       int i;                      /* Iterator variable */  
105225       char *zVarlist;             /* The "?, ?, ..." string */
105226       zVarlist = (char *)sqlite3_malloc(2*p->nColumn+2);
105227       if( !zVarlist ){
105228         *pp = 0;
105229         return SQLITE_NOMEM;
105230       }
105231       zVarlist[0] = '?';
105232       zVarlist[p->nColumn*2+1] = '\0';
105233       for(i=1; i<=p->nColumn; i++){
105234         zVarlist[i*2-1] = ',';
105235         zVarlist[i*2] = '?';
105236       }
105237       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, zVarlist);
105238     }else{
105239       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
105240     }
105241     if( !zSql ){
105242       rc = SQLITE_NOMEM;
105243     }else{
105244       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
105245       sqlite3_free(zSql);
105246       assert( rc==SQLITE_OK || pStmt==0 );
105247       p->aStmt[eStmt] = pStmt;
105248     }
105249   }
105250   if( apVal ){
105251     int i;
105252     int nParam = sqlite3_bind_parameter_count(pStmt);
105253     for(i=0; rc==SQLITE_OK && i<nParam; i++){
105254       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
105255     }
105256   }
105257   *pp = pStmt;
105258   return rc;
105259 }
105260
105261 /*
105262 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
105263 ** array apVal[] to the SQL statement identified by eStmt, the statement
105264 ** is executed.
105265 **
105266 ** Returns SQLITE_OK if the statement is successfully executed, or an
105267 ** SQLite error code otherwise.
105268 */
105269 static void fts3SqlExec(
105270   int *pRC,                /* Result code */
105271   Fts3Table *p,            /* The FTS3 table */
105272   int eStmt,               /* Index of statement to evaluate */
105273   sqlite3_value **apVal    /* Parameters to bind */
105274 ){
105275   sqlite3_stmt *pStmt;
105276   int rc;
105277   if( *pRC ) return;
105278   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
105279   if( rc==SQLITE_OK ){
105280     sqlite3_step(pStmt);
105281     rc = sqlite3_reset(pStmt);
105282   }
105283   *pRC = rc;
105284 }
105285
105286
105287 /*
105288 ** Read a single block from the %_segments table. If the specified block
105289 ** does not exist, return SQLITE_CORRUPT. If some other error (malloc, IO 
105290 ** etc.) occurs, return the appropriate SQLite error code.
105291 **
105292 ** Otherwise, if successful, set *pzBlock to point to a buffer containing
105293 ** the block read from the database, and *pnBlock to the size of the read
105294 ** block in bytes.
105295 **
105296 ** WARNING: The returned buffer is only valid until the next call to 
105297 ** sqlite3Fts3ReadBlock().
105298 */
105299 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
105300   Fts3Table *p,
105301   sqlite3_int64 iBlock,
105302   char const **pzBlock,
105303   int *pnBlock
105304 ){
105305   sqlite3_stmt *pStmt;
105306   int rc = fts3SqlStmt(p, SQL_GET_BLOCK, &pStmt, 0);
105307   if( rc!=SQLITE_OK ) return rc;
105308   sqlite3_reset(pStmt);
105309
105310   if( pzBlock ){
105311     sqlite3_bind_int64(pStmt, 1, iBlock);
105312     rc = sqlite3_step(pStmt); 
105313     if( rc!=SQLITE_ROW ){
105314       return (rc==SQLITE_DONE ? SQLITE_CORRUPT : rc);
105315     }
105316   
105317     *pnBlock = sqlite3_column_bytes(pStmt, 0);
105318     *pzBlock = (char *)sqlite3_column_blob(pStmt, 0);
105319     if( sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
105320       return SQLITE_CORRUPT;
105321     }
105322   }
105323   return SQLITE_OK;
105324 }
105325
105326 /*
105327 ** Set *ppStmt to a statement handle that may be used to iterate through
105328 ** all rows in the %_segdir table, from oldest to newest. If successful,
105329 ** return SQLITE_OK. If an error occurs while preparing the statement, 
105330 ** return an SQLite error code.
105331 **
105332 ** There is only ever one instance of this SQL statement compiled for
105333 ** each FTS3 table.
105334 **
105335 ** The statement returns the following columns from the %_segdir table:
105336 **
105337 **   0: idx
105338 **   1: start_block
105339 **   2: leaves_end_block
105340 **   3: end_block
105341 **   4: root
105342 */
105343 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table *p, sqlite3_stmt **ppStmt){
105344   return fts3SqlStmt(p, SQL_SELECT_ALL_LEVEL, ppStmt, 0);
105345 }
105346
105347
105348 /*
105349 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
105350 ** if successful, or an SQLite error code otherwise.
105351 **
105352 ** This function also serves to allocate the PendingList structure itself.
105353 ** For example, to create a new PendingList structure containing two
105354 ** varints:
105355 **
105356 **   PendingList *p = 0;
105357 **   fts3PendingListAppendVarint(&p, 1);
105358 **   fts3PendingListAppendVarint(&p, 2);
105359 */
105360 static int fts3PendingListAppendVarint(
105361   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
105362   sqlite3_int64 i                 /* Value to append to data */
105363 ){
105364   PendingList *p = *pp;
105365
105366   /* Allocate or grow the PendingList as required. */
105367   if( !p ){
105368     p = sqlite3_malloc(sizeof(*p) + 100);
105369     if( !p ){
105370       return SQLITE_NOMEM;
105371     }
105372     p->nSpace = 100;
105373     p->aData = (char *)&p[1];
105374     p->nData = 0;
105375   }
105376   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
105377     int nNew = p->nSpace * 2;
105378     p = sqlite3_realloc(p, sizeof(*p) + nNew);
105379     if( !p ){
105380       sqlite3_free(*pp);
105381       *pp = 0;
105382       return SQLITE_NOMEM;
105383     }
105384     p->nSpace = nNew;
105385     p->aData = (char *)&p[1];
105386   }
105387
105388   /* Append the new serialized varint to the end of the list. */
105389   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
105390   p->aData[p->nData] = '\0';
105391   *pp = p;
105392   return SQLITE_OK;
105393 }
105394
105395 /*
105396 ** Add a docid/column/position entry to a PendingList structure. Non-zero
105397 ** is returned if the structure is sqlite3_realloced as part of adding
105398 ** the entry. Otherwise, zero.
105399 **
105400 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
105401 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
105402 ** it is set to SQLITE_OK.
105403 */
105404 static int fts3PendingListAppend(
105405   PendingList **pp,               /* IN/OUT: PendingList structure */
105406   sqlite3_int64 iDocid,           /* Docid for entry to add */
105407   sqlite3_int64 iCol,             /* Column for entry to add */
105408   sqlite3_int64 iPos,             /* Position of term for entry to add */
105409   int *pRc                        /* OUT: Return code */
105410 ){
105411   PendingList *p = *pp;
105412   int rc = SQLITE_OK;
105413
105414   assert( !p || p->iLastDocid<=iDocid );
105415
105416   if( !p || p->iLastDocid!=iDocid ){
105417     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
105418     if( p ){
105419       assert( p->nData<p->nSpace );
105420       assert( p->aData[p->nData]==0 );
105421       p->nData++;
105422     }
105423     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
105424       goto pendinglistappend_out;
105425     }
105426     p->iLastCol = -1;
105427     p->iLastPos = 0;
105428     p->iLastDocid = iDocid;
105429   }
105430   if( iCol>0 && p->iLastCol!=iCol ){
105431     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
105432      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
105433     ){
105434       goto pendinglistappend_out;
105435     }
105436     p->iLastCol = iCol;
105437     p->iLastPos = 0;
105438   }
105439   if( iCol>=0 ){
105440     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
105441     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
105442     if( rc==SQLITE_OK ){
105443       p->iLastPos = iPos;
105444     }
105445   }
105446
105447  pendinglistappend_out:
105448   *pRc = rc;
105449   if( p!=*pp ){
105450     *pp = p;
105451     return 1;
105452   }
105453   return 0;
105454 }
105455
105456 /*
105457 ** Tokenize the nul-terminated string zText and add all tokens to the
105458 ** pending-terms hash-table. The docid used is that currently stored in
105459 ** p->iPrevDocid, and the column is specified by argument iCol.
105460 **
105461 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
105462 */
105463 static int fts3PendingTermsAdd(
105464   Fts3Table *p,          /* FTS table into which text will be inserted */
105465   const char *zText,     /* Text of document to be inseted */
105466   int iCol,              /* Column number into which text is inserted */
105467   u32 *pnWord            /* OUT: Number of tokens inserted */
105468 ){
105469   int rc;
105470   int iStart;
105471   int iEnd;
105472   int iPos;
105473   int nWord = 0;
105474
105475   char const *zToken;
105476   int nToken;
105477
105478   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
105479   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
105480   sqlite3_tokenizer_cursor *pCsr;
105481   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
105482       const char**,int*,int*,int*,int*);
105483
105484   assert( pTokenizer && pModule );
105485
105486   rc = pModule->xOpen(pTokenizer, zText, -1, &pCsr);
105487   if( rc!=SQLITE_OK ){
105488     return rc;
105489   }
105490   pCsr->pTokenizer = pTokenizer;
105491
105492   xNext = pModule->xNext;
105493   while( SQLITE_OK==rc
105494       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
105495   ){
105496     PendingList *pList;
105497  
105498     if( iPos>=nWord ) nWord = iPos+1;
105499
105500     /* Positions cannot be negative; we use -1 as a terminator internally.
105501     ** Tokens must have a non-zero length.
105502     */
105503     if( iPos<0 || !zToken || nToken<=0 ){
105504       rc = SQLITE_ERROR;
105505       break;
105506     }
105507
105508     pList = (PendingList *)fts3HashFind(&p->pendingTerms, zToken, nToken);
105509     if( pList ){
105510       p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
105511     }
105512     if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
105513       if( pList==fts3HashInsert(&p->pendingTerms, zToken, nToken, pList) ){
105514         /* Malloc failed while inserting the new entry. This can only 
105515         ** happen if there was no previous entry for this token.
105516         */
105517         assert( 0==fts3HashFind(&p->pendingTerms, zToken, nToken) );
105518         sqlite3_free(pList);
105519         rc = SQLITE_NOMEM;
105520       }
105521     }
105522     if( rc==SQLITE_OK ){
105523       p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
105524     }
105525   }
105526
105527   pModule->xClose(pCsr);
105528   *pnWord = nWord;
105529   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
105530 }
105531
105532 /* 
105533 ** Calling this function indicates that subsequent calls to 
105534 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
105535 ** contents of the document with docid iDocid.
105536 */
105537 static int fts3PendingTermsDocid(Fts3Table *p, sqlite_int64 iDocid){
105538   /* TODO(shess) Explore whether partially flushing the buffer on
105539   ** forced-flush would provide better performance.  I suspect that if
105540   ** we ordered the doclists by size and flushed the largest until the
105541   ** buffer was half empty, that would let the less frequent terms
105542   ** generate longer doclists.
105543   */
105544   if( iDocid<=p->iPrevDocid || p->nPendingData>p->nMaxPendingData ){
105545     int rc = sqlite3Fts3PendingTermsFlush(p);
105546     if( rc!=SQLITE_OK ) return rc;
105547   }
105548   p->iPrevDocid = iDocid;
105549   return SQLITE_OK;
105550 }
105551
105552 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
105553   Fts3HashElem *pElem;
105554   for(pElem=fts3HashFirst(&p->pendingTerms); pElem; pElem=fts3HashNext(pElem)){
105555     sqlite3_free(fts3HashData(pElem));
105556   }
105557   fts3HashClear(&p->pendingTerms);
105558   p->nPendingData = 0;
105559 }
105560
105561 /*
105562 ** This function is called by the xUpdate() method as part of an INSERT
105563 ** operation. It adds entries for each term in the new record to the
105564 ** pendingTerms hash table.
105565 **
105566 ** Argument apVal is the same as the similarly named argument passed to
105567 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
105568 */
105569 static int fts3InsertTerms(Fts3Table *p, sqlite3_value **apVal, u32 *aSz){
105570   int i;                          /* Iterator variable */
105571   for(i=2; i<p->nColumn+2; i++){
105572     const char *zText = (const char *)sqlite3_value_text(apVal[i]);
105573     if( zText ){
105574       int rc = fts3PendingTermsAdd(p, zText, i-2, &aSz[i-2]);
105575       if( rc!=SQLITE_OK ){
105576         return rc;
105577       }
105578     }
105579   }
105580   return SQLITE_OK;
105581 }
105582
105583 /*
105584 ** This function is called by the xUpdate() method for an INSERT operation.
105585 ** The apVal parameter is passed a copy of the apVal argument passed by
105586 ** SQLite to the xUpdate() method. i.e:
105587 **
105588 **   apVal[0]                Not used for INSERT.
105589 **   apVal[1]                rowid
105590 **   apVal[2]                Left-most user-defined column
105591 **   ...
105592 **   apVal[p->nColumn+1]     Right-most user-defined column
105593 **   apVal[p->nColumn+2]     Hidden column with same name as table
105594 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
105595 */
105596 static int fts3InsertData(
105597   Fts3Table *p,                   /* Full-text table */
105598   sqlite3_value **apVal,          /* Array of values to insert */
105599   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
105600 ){
105601   int rc;                         /* Return code */
105602   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
105603
105604   /* Locate the statement handle used to insert data into the %_content
105605   ** table. The SQL for this statement is:
105606   **
105607   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
105608   **
105609   ** The statement features N '?' variables, where N is the number of user
105610   ** defined columns in the FTS3 table, plus one for the docid field.
105611   */
105612   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
105613   if( rc!=SQLITE_OK ){
105614     return rc;
105615   }
105616
105617   /* There is a quirk here. The users INSERT statement may have specified
105618   ** a value for the "rowid" field, for the "docid" field, or for both.
105619   ** Which is a problem, since "rowid" and "docid" are aliases for the
105620   ** same value. For example:
105621   **
105622   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
105623   **
105624   ** In FTS3, this is an error. It is an error to specify non-NULL values
105625   ** for both docid and some other rowid alias.
105626   */
105627   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
105628     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
105629      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
105630     ){
105631       /* A rowid/docid conflict. */
105632       return SQLITE_ERROR;
105633     }
105634     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
105635     if( rc!=SQLITE_OK ) return rc;
105636   }
105637
105638   /* Execute the statement to insert the record. Set *piDocid to the 
105639   ** new docid value. 
105640   */
105641   sqlite3_step(pContentInsert);
105642   rc = sqlite3_reset(pContentInsert);
105643
105644   *piDocid = sqlite3_last_insert_rowid(p->db);
105645   return rc;
105646 }
105647
105648
105649
105650 /*
105651 ** Remove all data from the FTS3 table. Clear the hash table containing
105652 ** pending terms.
105653 */
105654 static int fts3DeleteAll(Fts3Table *p){
105655   int rc = SQLITE_OK;             /* Return code */
105656
105657   /* Discard the contents of the pending-terms hash table. */
105658   sqlite3Fts3PendingTermsClear(p);
105659
105660   /* Delete everything from the %_content, %_segments and %_segdir tables. */
105661   fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
105662   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
105663   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
105664   if( p->bHasDocsize ){
105665     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
105666     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
105667   }
105668   return rc;
105669 }
105670
105671 /*
105672 ** The first element in the apVal[] array is assumed to contain the docid
105673 ** (an integer) of a row about to be deleted. Remove all terms from the
105674 ** full-text index.
105675 */
105676 static void fts3DeleteTerms(
105677   int *pRC,               /* Result code */
105678   Fts3Table *p,           /* The FTS table to delete from */
105679   sqlite3_value **apVal,  /* apVal[] contains the docid to be deleted */
105680   u32 *aSz                /* Sizes of deleted document written here */
105681 ){
105682   int rc;
105683   sqlite3_stmt *pSelect;
105684
105685   if( *pRC ) return;
105686   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, apVal);
105687   if( rc==SQLITE_OK ){
105688     if( SQLITE_ROW==sqlite3_step(pSelect) ){
105689       int i;
105690       for(i=1; i<=p->nColumn; i++){
105691         const char *zText = (const char *)sqlite3_column_text(pSelect, i);
105692         rc = fts3PendingTermsAdd(p, zText, -1, &aSz[i-1]);
105693         if( rc!=SQLITE_OK ){
105694           sqlite3_reset(pSelect);
105695           *pRC = rc;
105696           return;
105697         }
105698       }
105699     }
105700     rc = sqlite3_reset(pSelect);
105701   }else{
105702     sqlite3_reset(pSelect);
105703   }
105704   *pRC = rc;
105705 }
105706
105707 /*
105708 ** Forward declaration to account for the circular dependency between
105709 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
105710 */
105711 static int fts3SegmentMerge(Fts3Table *, int);
105712
105713 /* 
105714 ** This function allocates a new level iLevel index in the segdir table.
105715 ** Usually, indexes are allocated within a level sequentially starting
105716 ** with 0, so the allocated index is one greater than the value returned
105717 ** by:
105718 **
105719 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
105720 **
105721 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
105722 ** level, they are merged into a single level (iLevel+1) segment and the 
105723 ** allocated index is 0.
105724 **
105725 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
105726 ** returned. Otherwise, an SQLite error code is returned.
105727 */
105728 static int fts3AllocateSegdirIdx(Fts3Table *p, int iLevel, int *piIdx){
105729   int rc;                         /* Return Code */
105730   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
105731   int iNext = 0;                  /* Result of query pNextIdx */
105732
105733   /* Set variable iNext to the next available segdir index at level iLevel. */
105734   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
105735   if( rc==SQLITE_OK ){
105736     sqlite3_bind_int(pNextIdx, 1, iLevel);
105737     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
105738       iNext = sqlite3_column_int(pNextIdx, 0);
105739     }
105740     rc = sqlite3_reset(pNextIdx);
105741   }
105742
105743   if( rc==SQLITE_OK ){
105744     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
105745     ** full, merge all segments in level iLevel into a single iLevel+1
105746     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
105747     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
105748     */
105749     if( iNext>=FTS3_MERGE_COUNT ){
105750       rc = fts3SegmentMerge(p, iLevel);
105751       *piIdx = 0;
105752     }else{
105753       *piIdx = iNext;
105754     }
105755   }
105756
105757   return rc;
105758 }
105759
105760 /*
105761 ** Move the iterator passed as the first argument to the next term in the
105762 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
105763 ** SQLITE_DONE. Otherwise, an SQLite error code.
105764 */
105765 static int fts3SegReaderNext(Fts3SegReader *pReader){
105766   char *pNext;                    /* Cursor variable */
105767   int nPrefix;                    /* Number of bytes in term prefix */
105768   int nSuffix;                    /* Number of bytes in term suffix */
105769
105770   if( !pReader->aDoclist ){
105771     pNext = pReader->aNode;
105772   }else{
105773     pNext = &pReader->aDoclist[pReader->nDoclist];
105774   }
105775
105776   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
105777     int rc;
105778     if( fts3SegReaderIsPending(pReader) ){
105779       Fts3HashElem *pElem = *(pReader->ppNextElem);
105780       if( pElem==0 ){
105781         pReader->aNode = 0;
105782       }else{
105783         PendingList *pList = (PendingList *)fts3HashData(pElem);
105784         pReader->zTerm = (char *)fts3HashKey(pElem);
105785         pReader->nTerm = fts3HashKeysize(pElem);
105786         pReader->nNode = pReader->nDoclist = pList->nData + 1;
105787         pReader->aNode = pReader->aDoclist = pList->aData;
105788         pReader->ppNextElem++;
105789         assert( pReader->aNode );
105790       }
105791       return SQLITE_OK;
105792     }
105793     if( !pReader->pStmt ){
105794       pReader->aNode = 0;
105795       return SQLITE_OK;
105796     }
105797     rc = sqlite3_step(pReader->pStmt);
105798     if( rc!=SQLITE_ROW ){
105799       pReader->aNode = 0;
105800       return (rc==SQLITE_DONE ? SQLITE_OK : rc);
105801     }
105802     pReader->nNode = sqlite3_column_bytes(pReader->pStmt, 0);
105803     pReader->aNode = (char *)sqlite3_column_blob(pReader->pStmt, 0);
105804     pNext = pReader->aNode;
105805   }
105806   
105807   pNext += sqlite3Fts3GetVarint32(pNext, &nPrefix);
105808   pNext += sqlite3Fts3GetVarint32(pNext, &nSuffix);
105809
105810   if( nPrefix+nSuffix>pReader->nTermAlloc ){
105811     int nNew = (nPrefix+nSuffix)*2;
105812     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
105813     if( !zNew ){
105814       return SQLITE_NOMEM;
105815     }
105816     pReader->zTerm = zNew;
105817     pReader->nTermAlloc = nNew;
105818   }
105819   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
105820   pReader->nTerm = nPrefix+nSuffix;
105821   pNext += nSuffix;
105822   pNext += sqlite3Fts3GetVarint32(pNext, &pReader->nDoclist);
105823   assert( pNext<&pReader->aNode[pReader->nNode] );
105824   pReader->aDoclist = pNext;
105825   pReader->pOffsetList = 0;
105826   return SQLITE_OK;
105827 }
105828
105829 /*
105830 ** Set the SegReader to point to the first docid in the doclist associated
105831 ** with the current term.
105832 */
105833 static void fts3SegReaderFirstDocid(Fts3SegReader *pReader){
105834   int n;
105835   assert( pReader->aDoclist );
105836   assert( !pReader->pOffsetList );
105837   n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
105838   pReader->pOffsetList = &pReader->aDoclist[n];
105839 }
105840
105841 /*
105842 ** Advance the SegReader to point to the next docid in the doclist
105843 ** associated with the current term.
105844 ** 
105845 ** If arguments ppOffsetList and pnOffsetList are not NULL, then 
105846 ** *ppOffsetList is set to point to the first column-offset list
105847 ** in the doclist entry (i.e. immediately past the docid varint).
105848 ** *pnOffsetList is set to the length of the set of column-offset
105849 ** lists, not including the nul-terminator byte. For example:
105850 */
105851 static void fts3SegReaderNextDocid(
105852   Fts3SegReader *pReader,
105853   char **ppOffsetList,
105854   int *pnOffsetList
105855 ){
105856   char *p = pReader->pOffsetList;
105857   char c = 0;
105858
105859   /* Pointer p currently points at the first byte of an offset list. The
105860   ** following two lines advance it to point one byte past the end of
105861   ** the same offset list.
105862   */
105863   while( *p | c ) c = *p++ & 0x80;
105864   p++;
105865
105866   /* If required, populate the output variables with a pointer to and the
105867   ** size of the previous offset-list.
105868   */
105869   if( ppOffsetList ){
105870     *ppOffsetList = pReader->pOffsetList;
105871     *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
105872   }
105873
105874   /* If there are no more entries in the doclist, set pOffsetList to
105875   ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
105876   ** Fts3SegReader.pOffsetList to point to the next offset list before
105877   ** returning.
105878   */
105879   if( p>=&pReader->aDoclist[pReader->nDoclist] ){
105880     pReader->pOffsetList = 0;
105881   }else{
105882     sqlite3_int64 iDelta;
105883     pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
105884     pReader->iDocid += iDelta;
105885   }
105886 }
105887
105888 /*
105889 ** Free all allocations associated with the iterator passed as the 
105890 ** second argument.
105891 */
105892 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3Table *p, Fts3SegReader *pReader){
105893   if( pReader ){
105894     if( pReader->pStmt ){
105895       /* Move the leaf-range SELECT statement to the aLeavesStmt[] array,
105896       ** so that it can be reused when required by another query.
105897       */
105898       assert( p->nLeavesStmt<p->nLeavesTotal );
105899       sqlite3_reset(pReader->pStmt);
105900       p->aLeavesStmt[p->nLeavesStmt++] = pReader->pStmt;
105901     }
105902     if( !fts3SegReaderIsPending(pReader) ){
105903       sqlite3_free(pReader->zTerm);
105904     }
105905     sqlite3_free(pReader);
105906   }
105907 }
105908
105909 /*
105910 ** Allocate a new SegReader object.
105911 */
105912 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
105913   Fts3Table *p,                   /* Virtual table handle */
105914   int iAge,                       /* Segment "age". */
105915   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
105916   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
105917   sqlite3_int64 iEndBlock,        /* Final block of segment */
105918   const char *zRoot,              /* Buffer containing root node */
105919   int nRoot,                      /* Size of buffer containing root node */
105920   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
105921 ){
105922   int rc = SQLITE_OK;             /* Return code */
105923   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
105924   int nExtra = 0;                 /* Bytes to allocate segment root node */
105925
105926   if( iStartLeaf==0 ){
105927     nExtra = nRoot;
105928   }
105929
105930   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
105931   if( !pReader ){
105932     return SQLITE_NOMEM;
105933   }
105934   memset(pReader, 0, sizeof(Fts3SegReader));
105935   pReader->iStartBlock = iStartLeaf;
105936   pReader->iIdx = iAge;
105937   pReader->iEndBlock = iEndBlock;
105938
105939   if( nExtra ){
105940     /* The entire segment is stored in the root node. */
105941     pReader->aNode = (char *)&pReader[1];
105942     pReader->nNode = nRoot;
105943     memcpy(pReader->aNode, zRoot, nRoot);
105944   }else{
105945     /* If the text of the SQL statement to iterate through a contiguous
105946     ** set of entries in the %_segments table has not yet been composed,
105947     ** compose it now.
105948     */
105949     if( !p->zSelectLeaves ){
105950       p->zSelectLeaves = sqlite3_mprintf(
105951           "SELECT block FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ? "
105952           "ORDER BY blockid", p->zDb, p->zName
105953       );
105954       if( !p->zSelectLeaves ){
105955         rc = SQLITE_NOMEM;
105956         goto finished;
105957       }
105958     }
105959
105960     /* If there are no free statements in the aLeavesStmt[] array, prepare
105961     ** a new statement now. Otherwise, reuse a prepared statement from
105962     ** aLeavesStmt[].
105963     */
105964     if( p->nLeavesStmt==0 ){
105965       if( p->nLeavesTotal==p->nLeavesAlloc ){
105966         int nNew = p->nLeavesAlloc + 16;
105967         sqlite3_stmt **aNew = (sqlite3_stmt **)sqlite3_realloc(
105968             p->aLeavesStmt, nNew*sizeof(sqlite3_stmt *)
105969         );
105970         if( !aNew ){
105971           rc = SQLITE_NOMEM;
105972           goto finished;
105973         }
105974         p->nLeavesAlloc = nNew;
105975         p->aLeavesStmt = aNew;
105976       }
105977       rc = sqlite3_prepare_v2(p->db, p->zSelectLeaves, -1, &pReader->pStmt, 0);
105978       if( rc!=SQLITE_OK ){
105979         goto finished;
105980       }
105981       p->nLeavesTotal++;
105982     }else{
105983       pReader->pStmt = p->aLeavesStmt[--p->nLeavesStmt];
105984     }
105985
105986     /* Bind the start and end leaf blockids to the prepared SQL statement. */
105987     sqlite3_bind_int64(pReader->pStmt, 1, iStartLeaf);
105988     sqlite3_bind_int64(pReader->pStmt, 2, iEndLeaf);
105989   }
105990   rc = fts3SegReaderNext(pReader);
105991
105992  finished:
105993   if( rc==SQLITE_OK ){
105994     *ppReader = pReader;
105995   }else{
105996     sqlite3Fts3SegReaderFree(p, pReader);
105997   }
105998   return rc;
105999 }
106000
106001 /*
106002 ** This is a comparison function used as a qsort() callback when sorting
106003 ** an array of pending terms by term. This occurs as part of flushing
106004 ** the contents of the pending-terms hash table to the database.
106005 */
106006 static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
106007   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
106008   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
106009   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
106010   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
106011
106012   int n = (n1<n2 ? n1 : n2);
106013   int c = memcmp(z1, z2, n);
106014   if( c==0 ){
106015     c = n1 - n2;
106016   }
106017   return c;
106018 }
106019
106020 /*
106021 ** This function is used to allocate an Fts3SegReader that iterates through
106022 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
106023 */
106024 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
106025   Fts3Table *p,                   /* Virtual table handle */
106026   const char *zTerm,              /* Term to search for */
106027   int nTerm,                      /* Size of buffer zTerm */
106028   int isPrefix,                   /* True for a term-prefix query */
106029   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
106030 ){
106031   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
106032   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
106033   int nElem = 0;                  /* Size of array at aElem */
106034   int rc = SQLITE_OK;             /* Return Code */
106035
106036   if( isPrefix ){
106037     int nAlloc = 0;               /* Size of allocated array at aElem */
106038     Fts3HashElem *pE = 0;         /* Iterator variable */
106039
106040     for(pE=fts3HashFirst(&p->pendingTerms); pE; pE=fts3HashNext(pE)){
106041       char *zKey = (char *)fts3HashKey(pE);
106042       int nKey = fts3HashKeysize(pE);
106043       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
106044         if( nElem==nAlloc ){
106045           Fts3HashElem **aElem2;
106046           nAlloc += 16;
106047           aElem2 = (Fts3HashElem **)sqlite3_realloc(
106048               aElem, nAlloc*sizeof(Fts3HashElem *)
106049           );
106050           if( !aElem2 ){
106051             rc = SQLITE_NOMEM;
106052             nElem = 0;
106053             break;
106054           }
106055           aElem = aElem2;
106056         }
106057         aElem[nElem++] = pE;
106058       }
106059     }
106060
106061     /* If more than one term matches the prefix, sort the Fts3HashElem
106062     ** objects in term order using qsort(). This uses the same comparison
106063     ** callback as is used when flushing terms to disk.
106064     */
106065     if( nElem>1 ){
106066       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
106067     }
106068
106069   }else{
106070     Fts3HashElem *pE = fts3HashFindElem(&p->pendingTerms, zTerm, nTerm);
106071     if( pE ){
106072       aElem = &pE;
106073       nElem = 1;
106074     }
106075   }
106076
106077   if( nElem>0 ){
106078     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
106079     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
106080     if( !pReader ){
106081       rc = SQLITE_NOMEM;
106082     }else{
106083       memset(pReader, 0, nByte);
106084       pReader->iIdx = 0x7FFFFFFF;
106085       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
106086       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
106087       fts3SegReaderNext(pReader);
106088     }
106089   }
106090
106091   if( isPrefix ){
106092     sqlite3_free(aElem);
106093   }
106094   *ppReader = pReader;
106095   return rc;
106096 }
106097
106098
106099 /*
106100 ** The second argument to this function is expected to be a statement of
106101 ** the form:
106102 **
106103 **   SELECT 
106104 **     idx,                  -- col 0
106105 **     start_block,          -- col 1
106106 **     leaves_end_block,     -- col 2
106107 **     end_block,            -- col 3
106108 **     root                  -- col 4
106109 **   FROM %_segdir ...
106110 **
106111 ** This function allocates and initializes a Fts3SegReader structure to
106112 ** iterate through the terms stored in the segment identified by the
106113 ** current row that pStmt is pointing to. 
106114 **
106115 ** If successful, the Fts3SegReader is left pointing to the first term
106116 ** in the segment and SQLITE_OK is returned. Otherwise, an SQLite error
106117 ** code is returned.
106118 */
106119 static int fts3SegReaderNew(
106120   Fts3Table *p,                   /* Virtual table handle */
106121   sqlite3_stmt *pStmt,            /* See above */
106122   int iAge,                       /* Segment "age". */
106123   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
106124 ){
106125   return sqlite3Fts3SegReaderNew(p, iAge, 
106126       sqlite3_column_int64(pStmt, 1),
106127       sqlite3_column_int64(pStmt, 2),
106128       sqlite3_column_int64(pStmt, 3),
106129       sqlite3_column_blob(pStmt, 4),
106130       sqlite3_column_bytes(pStmt, 4),
106131       ppReader
106132   );
106133 }
106134
106135 /*
106136 ** Compare the entries pointed to by two Fts3SegReader structures. 
106137 ** Comparison is as follows:
106138 **
106139 **   1) EOF is greater than not EOF.
106140 **
106141 **   2) The current terms (if any) are compared using memcmp(). If one
106142 **      term is a prefix of another, the longer term is considered the
106143 **      larger.
106144 **
106145 **   3) By segment age. An older segment is considered larger.
106146 */
106147 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
106148   int rc;
106149   if( pLhs->aNode && pRhs->aNode ){
106150     int rc2 = pLhs->nTerm - pRhs->nTerm;
106151     if( rc2<0 ){
106152       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
106153     }else{
106154       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
106155     }
106156     if( rc==0 ){
106157       rc = rc2;
106158     }
106159   }else{
106160     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
106161   }
106162   if( rc==0 ){
106163     rc = pRhs->iIdx - pLhs->iIdx;
106164   }
106165   assert( rc!=0 );
106166   return rc;
106167 }
106168
106169 /*
106170 ** A different comparison function for SegReader structures. In this
106171 ** version, it is assumed that each SegReader points to an entry in
106172 ** a doclist for identical terms. Comparison is made as follows:
106173 **
106174 **   1) EOF (end of doclist in this case) is greater than not EOF.
106175 **
106176 **   2) By current docid.
106177 **
106178 **   3) By segment age. An older segment is considered larger.
106179 */
106180 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
106181   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
106182   if( rc==0 ){
106183     if( pLhs->iDocid==pRhs->iDocid ){
106184       rc = pRhs->iIdx - pLhs->iIdx;
106185     }else{
106186       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
106187     }
106188   }
106189   assert( pLhs->aNode && pRhs->aNode );
106190   return rc;
106191 }
106192
106193 /*
106194 ** Compare the term that the Fts3SegReader object passed as the first argument
106195 ** points to with the term specified by arguments zTerm and nTerm. 
106196 **
106197 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
106198 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
106199 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
106200 */
106201 static int fts3SegReaderTermCmp(
106202   Fts3SegReader *pSeg,            /* Segment reader object */
106203   const char *zTerm,              /* Term to compare to */
106204   int nTerm                       /* Size of term zTerm in bytes */
106205 ){
106206   int res = 0;
106207   if( pSeg->aNode ){
106208     if( pSeg->nTerm>nTerm ){
106209       res = memcmp(pSeg->zTerm, zTerm, nTerm);
106210     }else{
106211       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
106212     }
106213     if( res==0 ){
106214       res = pSeg->nTerm-nTerm;
106215     }
106216   }
106217   return res;
106218 }
106219
106220 /*
106221 ** Argument apSegment is an array of nSegment elements. It is known that
106222 ** the final (nSegment-nSuspect) members are already in sorted order
106223 ** (according to the comparison function provided). This function shuffles
106224 ** the array around until all entries are in sorted order.
106225 */
106226 static void fts3SegReaderSort(
106227   Fts3SegReader **apSegment,                     /* Array to sort entries of */
106228   int nSegment,                                  /* Size of apSegment array */
106229   int nSuspect,                                  /* Unsorted entry count */
106230   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
106231 ){
106232   int i;                          /* Iterator variable */
106233
106234   assert( nSuspect<=nSegment );
106235
106236   if( nSuspect==nSegment ) nSuspect--;
106237   for(i=nSuspect-1; i>=0; i--){
106238     int j;
106239     for(j=i; j<(nSegment-1); j++){
106240       Fts3SegReader *pTmp;
106241       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
106242       pTmp = apSegment[j+1];
106243       apSegment[j+1] = apSegment[j];
106244       apSegment[j] = pTmp;
106245     }
106246   }
106247
106248 #ifndef NDEBUG
106249   /* Check that the list really is sorted now. */
106250   for(i=0; i<(nSuspect-1); i++){
106251     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
106252   }
106253 #endif
106254 }
106255
106256 /* 
106257 ** Insert a record into the %_segments table.
106258 */
106259 static int fts3WriteSegment(
106260   Fts3Table *p,                   /* Virtual table handle */
106261   sqlite3_int64 iBlock,           /* Block id for new block */
106262   char *z,                        /* Pointer to buffer containing block data */
106263   int n                           /* Size of buffer z in bytes */
106264 ){
106265   sqlite3_stmt *pStmt;
106266   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
106267   if( rc==SQLITE_OK ){
106268     sqlite3_bind_int64(pStmt, 1, iBlock);
106269     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
106270     sqlite3_step(pStmt);
106271     rc = sqlite3_reset(pStmt);
106272   }
106273   return rc;
106274 }
106275
106276 /* 
106277 ** Insert a record into the %_segdir table.
106278 */
106279 static int fts3WriteSegdir(
106280   Fts3Table *p,                   /* Virtual table handle */
106281   int iLevel,                     /* Value for "level" field */
106282   int iIdx,                       /* Value for "idx" field */
106283   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
106284   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
106285   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
106286   char *zRoot,                    /* Blob value for "root" field */
106287   int nRoot                       /* Number of bytes in buffer zRoot */
106288 ){
106289   sqlite3_stmt *pStmt;
106290   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
106291   if( rc==SQLITE_OK ){
106292     sqlite3_bind_int(pStmt, 1, iLevel);
106293     sqlite3_bind_int(pStmt, 2, iIdx);
106294     sqlite3_bind_int64(pStmt, 3, iStartBlock);
106295     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
106296     sqlite3_bind_int64(pStmt, 5, iEndBlock);
106297     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
106298     sqlite3_step(pStmt);
106299     rc = sqlite3_reset(pStmt);
106300   }
106301   return rc;
106302 }
106303
106304 /*
106305 ** Return the size of the common prefix (if any) shared by zPrev and
106306 ** zNext, in bytes. For example, 
106307 **
106308 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
106309 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
106310 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
106311 */
106312 static int fts3PrefixCompress(
106313   const char *zPrev,              /* Buffer containing previous term */
106314   int nPrev,                      /* Size of buffer zPrev in bytes */
106315   const char *zNext,              /* Buffer containing next term */
106316   int nNext                       /* Size of buffer zNext in bytes */
106317 ){
106318   int n;
106319   UNUSED_PARAMETER(nNext);
106320   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
106321   return n;
106322 }
106323
106324 /*
106325 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
106326 ** (according to memcmp) than the previous term.
106327 */
106328 static int fts3NodeAddTerm(
106329   Fts3Table *p,               /* Virtual table handle */
106330   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
106331   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
106332   const char *zTerm,              /* Pointer to buffer containing term */
106333   int nTerm                       /* Size of term in bytes */
106334 ){
106335   SegmentNode *pTree = *ppTree;
106336   int rc;
106337   SegmentNode *pNew;
106338
106339   /* First try to append the term to the current node. Return early if 
106340   ** this is possible.
106341   */
106342   if( pTree ){
106343     int nData = pTree->nData;     /* Current size of node in bytes */
106344     int nReq = nData;             /* Required space after adding zTerm */
106345     int nPrefix;                  /* Number of bytes of prefix compression */
106346     int nSuffix;                  /* Suffix length */
106347
106348     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
106349     nSuffix = nTerm-nPrefix;
106350
106351     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
106352     if( nReq<=p->nNodeSize || !pTree->zTerm ){
106353
106354       if( nReq>p->nNodeSize ){
106355         /* An unusual case: this is the first term to be added to the node
106356         ** and the static node buffer (p->nNodeSize bytes) is not large
106357         ** enough. Use a separately malloced buffer instead This wastes
106358         ** p->nNodeSize bytes, but since this scenario only comes about when
106359         ** the database contain two terms that share a prefix of almost 2KB, 
106360         ** this is not expected to be a serious problem. 
106361         */
106362         assert( pTree->aData==(char *)&pTree[1] );
106363         pTree->aData = (char *)sqlite3_malloc(nReq);
106364         if( !pTree->aData ){
106365           return SQLITE_NOMEM;
106366         }
106367       }
106368
106369       if( pTree->zTerm ){
106370         /* There is no prefix-length field for first term in a node */
106371         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
106372       }
106373
106374       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
106375       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
106376       pTree->nData = nData + nSuffix;
106377       pTree->nEntry++;
106378
106379       if( isCopyTerm ){
106380         if( pTree->nMalloc<nTerm ){
106381           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
106382           if( !zNew ){
106383             return SQLITE_NOMEM;
106384           }
106385           pTree->nMalloc = nTerm*2;
106386           pTree->zMalloc = zNew;
106387         }
106388         pTree->zTerm = pTree->zMalloc;
106389         memcpy(pTree->zTerm, zTerm, nTerm);
106390         pTree->nTerm = nTerm;
106391       }else{
106392         pTree->zTerm = (char *)zTerm;
106393         pTree->nTerm = nTerm;
106394       }
106395       return SQLITE_OK;
106396     }
106397   }
106398
106399   /* If control flows to here, it was not possible to append zTerm to the
106400   ** current node. Create a new node (a right-sibling of the current node).
106401   ** If this is the first node in the tree, the term is added to it.
106402   **
106403   ** Otherwise, the term is not added to the new node, it is left empty for
106404   ** now. Instead, the term is inserted into the parent of pTree. If pTree 
106405   ** has no parent, one is created here.
106406   */
106407   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
106408   if( !pNew ){
106409     return SQLITE_NOMEM;
106410   }
106411   memset(pNew, 0, sizeof(SegmentNode));
106412   pNew->nData = 1 + FTS3_VARINT_MAX;
106413   pNew->aData = (char *)&pNew[1];
106414
106415   if( pTree ){
106416     SegmentNode *pParent = pTree->pParent;
106417     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
106418     if( pTree->pParent==0 ){
106419       pTree->pParent = pParent;
106420     }
106421     pTree->pRight = pNew;
106422     pNew->pLeftmost = pTree->pLeftmost;
106423     pNew->pParent = pParent;
106424     pNew->zMalloc = pTree->zMalloc;
106425     pNew->nMalloc = pTree->nMalloc;
106426     pTree->zMalloc = 0;
106427   }else{
106428     pNew->pLeftmost = pNew;
106429     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
106430   }
106431
106432   *ppTree = pNew;
106433   return rc;
106434 }
106435
106436 /*
106437 ** Helper function for fts3NodeWrite().
106438 */
106439 static int fts3TreeFinishNode(
106440   SegmentNode *pTree, 
106441   int iHeight, 
106442   sqlite3_int64 iLeftChild
106443 ){
106444   int nStart;
106445   assert( iHeight>=1 && iHeight<128 );
106446   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
106447   pTree->aData[nStart] = (char)iHeight;
106448   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
106449   return nStart;
106450 }
106451
106452 /*
106453 ** Write the buffer for the segment node pTree and all of its peers to the
106454 ** database. Then call this function recursively to write the parent of 
106455 ** pTree and its peers to the database. 
106456 **
106457 ** Except, if pTree is a root node, do not write it to the database. Instead,
106458 ** set output variables *paRoot and *pnRoot to contain the root node.
106459 **
106460 ** If successful, SQLITE_OK is returned and output variable *piLast is
106461 ** set to the largest blockid written to the database (or zero if no
106462 ** blocks were written to the db). Otherwise, an SQLite error code is 
106463 ** returned.
106464 */
106465 static int fts3NodeWrite(
106466   Fts3Table *p,                   /* Virtual table handle */
106467   SegmentNode *pTree,             /* SegmentNode handle */
106468   int iHeight,                    /* Height of this node in tree */
106469   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
106470   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
106471   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
106472   char **paRoot,                  /* OUT: Data for root node */
106473   int *pnRoot                     /* OUT: Size of root node in bytes */
106474 ){
106475   int rc = SQLITE_OK;
106476
106477   if( !pTree->pParent ){
106478     /* Root node of the tree. */
106479     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
106480     *piLast = iFree-1;
106481     *pnRoot = pTree->nData - nStart;
106482     *paRoot = &pTree->aData[nStart];
106483   }else{
106484     SegmentNode *pIter;
106485     sqlite3_int64 iNextFree = iFree;
106486     sqlite3_int64 iNextLeaf = iLeaf;
106487     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
106488       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
106489       int nWrite = pIter->nData - nStart;
106490   
106491       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
106492       iNextFree++;
106493       iNextLeaf += (pIter->nEntry+1);
106494     }
106495     if( rc==SQLITE_OK ){
106496       assert( iNextLeaf==iFree );
106497       rc = fts3NodeWrite(
106498           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
106499       );
106500     }
106501   }
106502
106503   return rc;
106504 }
106505
106506 /*
106507 ** Free all memory allocations associated with the tree pTree.
106508 */
106509 static void fts3NodeFree(SegmentNode *pTree){
106510   if( pTree ){
106511     SegmentNode *p = pTree->pLeftmost;
106512     fts3NodeFree(p->pParent);
106513     while( p ){
106514       SegmentNode *pRight = p->pRight;
106515       if( p->aData!=(char *)&p[1] ){
106516         sqlite3_free(p->aData);
106517       }
106518       assert( pRight==0 || p->zMalloc==0 );
106519       sqlite3_free(p->zMalloc);
106520       sqlite3_free(p);
106521       p = pRight;
106522     }
106523   }
106524 }
106525
106526 /*
106527 ** Add a term to the segment being constructed by the SegmentWriter object
106528 ** *ppWriter. When adding the first term to a segment, *ppWriter should
106529 ** be passed NULL. This function will allocate a new SegmentWriter object
106530 ** and return it via the input/output variable *ppWriter in this case.
106531 **
106532 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
106533 */
106534 static int fts3SegWriterAdd(
106535   Fts3Table *p,                   /* Virtual table handle */
106536   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
106537   int isCopyTerm,                 /* True if buffer zTerm must be copied */
106538   const char *zTerm,              /* Pointer to buffer containing term */
106539   int nTerm,                      /* Size of term in bytes */
106540   const char *aDoclist,           /* Pointer to buffer containing doclist */
106541   int nDoclist                    /* Size of doclist in bytes */
106542 ){
106543   int nPrefix;                    /* Size of term prefix in bytes */
106544   int nSuffix;                    /* Size of term suffix in bytes */
106545   int nReq;                       /* Number of bytes required on leaf page */
106546   int nData;
106547   SegmentWriter *pWriter = *ppWriter;
106548
106549   if( !pWriter ){
106550     int rc;
106551     sqlite3_stmt *pStmt;
106552
106553     /* Allocate the SegmentWriter structure */
106554     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
106555     if( !pWriter ) return SQLITE_NOMEM;
106556     memset(pWriter, 0, sizeof(SegmentWriter));
106557     *ppWriter = pWriter;
106558
106559     /* Allocate a buffer in which to accumulate data */
106560     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
106561     if( !pWriter->aData ) return SQLITE_NOMEM;
106562     pWriter->nSize = p->nNodeSize;
106563
106564     /* Find the next free blockid in the %_segments table */
106565     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
106566     if( rc!=SQLITE_OK ) return rc;
106567     if( SQLITE_ROW==sqlite3_step(pStmt) ){
106568       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
106569       pWriter->iFirst = pWriter->iFree;
106570     }
106571     rc = sqlite3_reset(pStmt);
106572     if( rc!=SQLITE_OK ) return rc;
106573   }
106574   nData = pWriter->nData;
106575
106576   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
106577   nSuffix = nTerm-nPrefix;
106578
106579   /* Figure out how many bytes are required by this new entry */
106580   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
106581     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
106582     nSuffix +                               /* Term suffix */
106583     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
106584     nDoclist;                               /* Doclist data */
106585
106586   if( nData>0 && nData+nReq>p->nNodeSize ){
106587     int rc;
106588
106589     /* The current leaf node is full. Write it out to the database. */
106590     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
106591     if( rc!=SQLITE_OK ) return rc;
106592
106593     /* Add the current term to the interior node tree. The term added to
106594     ** the interior tree must:
106595     **
106596     **   a) be greater than the largest term on the leaf node just written
106597     **      to the database (still available in pWriter->zTerm), and
106598     **
106599     **   b) be less than or equal to the term about to be added to the new
106600     **      leaf node (zTerm/nTerm).
106601     **
106602     ** In other words, it must be the prefix of zTerm 1 byte longer than
106603     ** the common prefix (if any) of zTerm and pWriter->zTerm.
106604     */
106605     assert( nPrefix<nTerm );
106606     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
106607     if( rc!=SQLITE_OK ) return rc;
106608
106609     nData = 0;
106610     pWriter->nTerm = 0;
106611
106612     nPrefix = 0;
106613     nSuffix = nTerm;
106614     nReq = 1 +                              /* varint containing prefix size */
106615       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
106616       nTerm +                               /* Term suffix */
106617       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
106618       nDoclist;                             /* Doclist data */
106619   }
106620
106621   /* If the buffer currently allocated is too small for this entry, realloc
106622   ** the buffer to make it large enough.
106623   */
106624   if( nReq>pWriter->nSize ){
106625     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
106626     if( !aNew ) return SQLITE_NOMEM;
106627     pWriter->aData = aNew;
106628     pWriter->nSize = nReq;
106629   }
106630   assert( nData+nReq<=pWriter->nSize );
106631
106632   /* Append the prefix-compressed term and doclist to the buffer. */
106633   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
106634   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
106635   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
106636   nData += nSuffix;
106637   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
106638   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
106639   pWriter->nData = nData + nDoclist;
106640
106641   /* Save the current term so that it can be used to prefix-compress the next.
106642   ** If the isCopyTerm parameter is true, then the buffer pointed to by
106643   ** zTerm is transient, so take a copy of the term data. Otherwise, just
106644   ** store a copy of the pointer.
106645   */
106646   if( isCopyTerm ){
106647     if( nTerm>pWriter->nMalloc ){
106648       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
106649       if( !zNew ){
106650         return SQLITE_NOMEM;
106651       }
106652       pWriter->nMalloc = nTerm*2;
106653       pWriter->zMalloc = zNew;
106654       pWriter->zTerm = zNew;
106655     }
106656     assert( pWriter->zTerm==pWriter->zMalloc );
106657     memcpy(pWriter->zTerm, zTerm, nTerm);
106658   }else{
106659     pWriter->zTerm = (char *)zTerm;
106660   }
106661   pWriter->nTerm = nTerm;
106662
106663   return SQLITE_OK;
106664 }
106665
106666 /*
106667 ** Flush all data associated with the SegmentWriter object pWriter to the
106668 ** database. This function must be called after all terms have been added
106669 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
106670 ** returned. Otherwise, an SQLite error code.
106671 */
106672 static int fts3SegWriterFlush(
106673   Fts3Table *p,                   /* Virtual table handle */
106674   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
106675   int iLevel,                     /* Value for 'level' column of %_segdir */
106676   int iIdx                        /* Value for 'idx' column of %_segdir */
106677 ){
106678   int rc;                         /* Return code */
106679   if( pWriter->pTree ){
106680     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
106681     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
106682     char *zRoot = NULL;           /* Pointer to buffer containing root node */
106683     int nRoot = 0;                /* Size of buffer zRoot */
106684
106685     iLastLeaf = pWriter->iFree;
106686     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
106687     if( rc==SQLITE_OK ){
106688       rc = fts3NodeWrite(p, pWriter->pTree, 1,
106689           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
106690     }
106691     if( rc==SQLITE_OK ){
106692       rc = fts3WriteSegdir(
106693           p, iLevel, iIdx, pWriter->iFirst, iLastLeaf, iLast, zRoot, nRoot);
106694     }
106695   }else{
106696     /* The entire tree fits on the root node. Write it to the segdir table. */
106697     rc = fts3WriteSegdir(
106698         p, iLevel, iIdx, 0, 0, 0, pWriter->aData, pWriter->nData);
106699   }
106700   return rc;
106701 }
106702
106703 /*
106704 ** Release all memory held by the SegmentWriter object passed as the 
106705 ** first argument.
106706 */
106707 static void fts3SegWriterFree(SegmentWriter *pWriter){
106708   if( pWriter ){
106709     sqlite3_free(pWriter->aData);
106710     sqlite3_free(pWriter->zMalloc);
106711     fts3NodeFree(pWriter->pTree);
106712     sqlite3_free(pWriter);
106713   }
106714 }
106715
106716 /*
106717 ** The first value in the apVal[] array is assumed to contain an integer.
106718 ** This function tests if there exist any documents with docid values that
106719 ** are different from that integer. i.e. if deleting the document with docid
106720 ** apVal[0] would mean the FTS3 table were empty.
106721 **
106722 ** If successful, *pisEmpty is set to true if the table is empty except for
106723 ** document apVal[0], or false otherwise, and SQLITE_OK is returned. If an
106724 ** error occurs, an SQLite error code is returned.
106725 */
106726 static int fts3IsEmpty(Fts3Table *p, sqlite3_value **apVal, int *pisEmpty){
106727   sqlite3_stmt *pStmt;
106728   int rc;
106729   rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, apVal);
106730   if( rc==SQLITE_OK ){
106731     if( SQLITE_ROW==sqlite3_step(pStmt) ){
106732       *pisEmpty = sqlite3_column_int(pStmt, 0);
106733     }
106734     rc = sqlite3_reset(pStmt);
106735   }
106736   return rc;
106737 }
106738
106739 /*
106740 ** Set *pnSegment to the number of segments of level iLevel in the database.
106741 **
106742 ** Return SQLITE_OK if successful, or an SQLite error code if not.
106743 */
106744 static int fts3SegmentCount(Fts3Table *p, int iLevel, int *pnSegment){
106745   sqlite3_stmt *pStmt;
106746   int rc;
106747
106748   assert( iLevel>=0 );
106749   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_COUNT, &pStmt, 0);
106750   if( rc!=SQLITE_OK ) return rc;
106751   sqlite3_bind_int(pStmt, 1, iLevel);
106752   if( SQLITE_ROW==sqlite3_step(pStmt) ){
106753     *pnSegment = sqlite3_column_int(pStmt, 0);
106754   }
106755   return sqlite3_reset(pStmt);
106756 }
106757
106758 /*
106759 ** Set *pnSegment to the total number of segments in the database. Set
106760 ** *pnMax to the largest segment level in the database (segment levels
106761 ** are stored in the 'level' column of the %_segdir table).
106762 **
106763 ** Return SQLITE_OK if successful, or an SQLite error code if not.
106764 */
106765 static int fts3SegmentCountMax(Fts3Table *p, int *pnSegment, int *pnMax){
106766   sqlite3_stmt *pStmt;
106767   int rc;
106768
106769   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_COUNT_MAX, &pStmt, 0);
106770   if( rc!=SQLITE_OK ) return rc;
106771   if( SQLITE_ROW==sqlite3_step(pStmt) ){
106772     *pnSegment = sqlite3_column_int(pStmt, 0);
106773     *pnMax = sqlite3_column_int(pStmt, 1);
106774   }
106775   return sqlite3_reset(pStmt);
106776 }
106777
106778 /*
106779 ** This function is used after merging multiple segments into a single large
106780 ** segment to delete the old, now redundant, segment b-trees. Specifically,
106781 ** it:
106782 ** 
106783 **   1) Deletes all %_segments entries for the segments associated with 
106784 **      each of the SegReader objects in the array passed as the third 
106785 **      argument, and
106786 **
106787 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
106788 **      entries regardless of level if (iLevel<0).
106789 **
106790 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
106791 */
106792 static int fts3DeleteSegdir(
106793   Fts3Table *p,                   /* Virtual table handle */
106794   int iLevel,                     /* Level of %_segdir entries to delete */
106795   Fts3SegReader **apSegment,      /* Array of SegReader objects */
106796   int nReader                     /* Size of array apSegment */
106797 ){
106798   int rc;                         /* Return Code */
106799   int i;                          /* Iterator variable */
106800   sqlite3_stmt *pDelete;          /* SQL statement to delete rows */
106801
106802   rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
106803   for(i=0; rc==SQLITE_OK && i<nReader; i++){
106804     Fts3SegReader *pSegment = apSegment[i];
106805     if( pSegment->iStartBlock ){
106806       sqlite3_bind_int64(pDelete, 1, pSegment->iStartBlock);
106807       sqlite3_bind_int64(pDelete, 2, pSegment->iEndBlock);
106808       sqlite3_step(pDelete);
106809       rc = sqlite3_reset(pDelete);
106810     }
106811   }
106812   if( rc!=SQLITE_OK ){
106813     return rc;
106814   }
106815
106816   if( iLevel>=0 ){
106817     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_BY_LEVEL, &pDelete, 0);
106818     if( rc==SQLITE_OK ){
106819       sqlite3_bind_int(pDelete, 1, iLevel);
106820       sqlite3_step(pDelete);
106821       rc = sqlite3_reset(pDelete);
106822     }
106823   }else{
106824     fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
106825   }
106826
106827   return rc;
106828 }
106829
106830 /*
106831 ** When this function is called, buffer *ppList (size *pnList bytes) contains 
106832 ** a position list that may (or may not) feature multiple columns. This
106833 ** function adjusts the pointer *ppList and the length *pnList so that they
106834 ** identify the subset of the position list that corresponds to column iCol.
106835 **
106836 ** If there are no entries in the input position list for column iCol, then
106837 ** *pnList is set to zero before returning.
106838 */
106839 static void fts3ColumnFilter(
106840   int iCol,                       /* Column to filter on */
106841   char **ppList,                  /* IN/OUT: Pointer to position list */
106842   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
106843 ){
106844   char *pList = *ppList;
106845   int nList = *pnList;
106846   char *pEnd = &pList[nList];
106847   int iCurrent = 0;
106848   char *p = pList;
106849
106850   assert( iCol>=0 );
106851   while( 1 ){
106852     char c = 0;
106853     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
106854   
106855     if( iCol==iCurrent ){
106856       nList = (int)(p - pList);
106857       break;
106858     }
106859
106860     nList -= (int)(p - pList);
106861     pList = p;
106862     if( nList==0 ){
106863       break;
106864     }
106865     p = &pList[1];
106866     p += sqlite3Fts3GetVarint32(p, &iCurrent);
106867   }
106868
106869   *ppList = pList;
106870   *pnList = nList;
106871 }
106872
106873 /*
106874 ** sqlite3Fts3SegReaderIterate() callback used when merging multiple 
106875 ** segments to create a single, larger segment.
106876 */
106877 static int fts3MergeCallback(
106878   Fts3Table *p,                   /* FTS3 Virtual table handle */
106879   void *pContext,                 /* Pointer to SegmentWriter* to write with */
106880   char *zTerm,                    /* Term to write to the db */
106881   int nTerm,                      /* Number of bytes in zTerm */
106882   char *aDoclist,                 /* Doclist associated with zTerm */
106883   int nDoclist                    /* Number of bytes in doclist */
106884 ){
106885   SegmentWriter **ppW = (SegmentWriter **)pContext;
106886   return fts3SegWriterAdd(p, ppW, 1, zTerm, nTerm, aDoclist, nDoclist);
106887 }
106888
106889 /*
106890 ** sqlite3Fts3SegReaderIterate() callback used when flushing the contents
106891 ** of the pending-terms hash table to the database.
106892 */
106893 static int fts3FlushCallback(
106894   Fts3Table *p,                   /* FTS3 Virtual table handle */
106895   void *pContext,                 /* Pointer to SegmentWriter* to write with */
106896   char *zTerm,                    /* Term to write to the db */
106897   int nTerm,                      /* Number of bytes in zTerm */
106898   char *aDoclist,                 /* Doclist associated with zTerm */
106899   int nDoclist                    /* Number of bytes in doclist */
106900 ){
106901   SegmentWriter **ppW = (SegmentWriter **)pContext;
106902   return fts3SegWriterAdd(p, ppW, 0, zTerm, nTerm, aDoclist, nDoclist);
106903 }
106904
106905 /*
106906 ** This function is used to iterate through a contiguous set of terms 
106907 ** stored in the full-text index. It merges data contained in one or 
106908 ** more segments to support this.
106909 **
106910 ** The second argument is passed an array of pointers to SegReader objects
106911 ** allocated with sqlite3Fts3SegReaderNew(). This function merges the range 
106912 ** of terms selected by each SegReader. If a single term is present in
106913 ** more than one segment, the associated doclists are merged. For each
106914 ** term and (possibly merged) doclist in the merged range, the callback
106915 ** function xFunc is invoked with its arguments set as follows.
106916 **
106917 **   arg 0: Copy of 'p' parameter passed to this function
106918 **   arg 1: Copy of 'pContext' parameter passed to this function
106919 **   arg 2: Pointer to buffer containing term
106920 **   arg 3: Size of arg 2 buffer in bytes
106921 **   arg 4: Pointer to buffer containing doclist
106922 **   arg 5: Size of arg 2 buffer in bytes
106923 **
106924 ** The 4th argument to this function is a pointer to a structure of type
106925 ** Fts3SegFilter, defined in fts3Int.h. The contents of this structure
106926 ** further restrict the range of terms that callbacks are made for and
106927 ** modify the behaviour of this function. See comments above structure
106928 ** definition for details.
106929 */
106930 SQLITE_PRIVATE int sqlite3Fts3SegReaderIterate(
106931   Fts3Table *p,                   /* Virtual table handle */
106932   Fts3SegReader **apSegment,      /* Array of Fts3SegReader objects */
106933   int nSegment,                   /* Size of apSegment array */
106934   Fts3SegFilter *pFilter,         /* Restrictions on range of iteration */
106935   int (*xFunc)(Fts3Table *, void *, char *, int, char *, int),  /* Callback */
106936   void *pContext                  /* Callback context (2nd argument) */
106937 ){
106938   int i;                          /* Iterator variable */
106939   char *aBuffer = 0;              /* Buffer to merge doclists in */
106940   int nAlloc = 0;                 /* Allocated size of aBuffer buffer */
106941   int rc = SQLITE_OK;             /* Return code */
106942
106943   int isIgnoreEmpty =  (pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
106944   int isRequirePos =   (pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
106945   int isColFilter =    (pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
106946   int isPrefix =       (pFilter->flags & FTS3_SEGMENT_PREFIX);
106947
106948   /* If there are zero segments, this function is a no-op. This scenario
106949   ** comes about only when reading from an empty database.
106950   */
106951   if( nSegment==0 ) goto finished;
106952
106953   /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
106954   ** for, then advance each segment iterator until it points to a term of
106955   ** equal or greater value than the specified term. This prevents many
106956   ** unnecessary merge/sort operations for the case where single segment
106957   ** b-tree leaf nodes contain more than one term.
106958   */
106959   if( pFilter->zTerm ){
106960     int nTerm = pFilter->nTerm;
106961     const char *zTerm = pFilter->zTerm;
106962     for(i=0; i<nSegment; i++){
106963       Fts3SegReader *pSeg = apSegment[i];
106964       while( fts3SegReaderTermCmp(pSeg, zTerm, nTerm)<0 ){
106965         rc = fts3SegReaderNext(pSeg);
106966         if( rc!=SQLITE_OK ) goto finished; }
106967     }
106968   }
106969
106970   fts3SegReaderSort(apSegment, nSegment, nSegment, fts3SegReaderCmp);
106971   while( apSegment[0]->aNode ){
106972     int nTerm = apSegment[0]->nTerm;
106973     char *zTerm = apSegment[0]->zTerm;
106974     int nMerge = 1;
106975
106976     /* If this is a prefix-search, and if the term that apSegment[0] points
106977     ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
106978     ** required callbacks have been made. In this case exit early.
106979     **
106980     ** Similarly, if this is a search for an exact match, and the first term
106981     ** of segment apSegment[0] is not a match, exit early.
106982     */
106983     if( pFilter->zTerm ){
106984       if( nTerm<pFilter->nTerm 
106985        || (!isPrefix && nTerm>pFilter->nTerm)
106986        || memcmp(zTerm, pFilter->zTerm, pFilter->nTerm) 
106987     ){
106988         goto finished;
106989       }
106990     }
106991
106992     while( nMerge<nSegment 
106993         && apSegment[nMerge]->aNode
106994         && apSegment[nMerge]->nTerm==nTerm 
106995         && 0==memcmp(zTerm, apSegment[nMerge]->zTerm, nTerm)
106996     ){
106997       nMerge++;
106998     }
106999
107000     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
107001     if( nMerge==1 && !isIgnoreEmpty ){
107002       Fts3SegReader *p0 = apSegment[0];
107003       rc = xFunc(p, pContext, zTerm, nTerm, p0->aDoclist, p0->nDoclist);
107004       if( rc!=SQLITE_OK ) goto finished;
107005     }else{
107006       int nDoclist = 0;           /* Size of doclist */
107007       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
107008
107009       /* The current term of the first nMerge entries in the array
107010       ** of Fts3SegReader objects is the same. The doclists must be merged
107011       ** and a single term added to the new segment.
107012       */
107013       for(i=0; i<nMerge; i++){
107014         fts3SegReaderFirstDocid(apSegment[i]);
107015       }
107016       fts3SegReaderSort(apSegment, nMerge, nMerge, fts3SegReaderDoclistCmp);
107017       while( apSegment[0]->pOffsetList ){
107018         int j;                    /* Number of segments that share a docid */
107019         char *pList;
107020         int nList;
107021         int nByte;
107022         sqlite3_int64 iDocid = apSegment[0]->iDocid;
107023         fts3SegReaderNextDocid(apSegment[0], &pList, &nList);
107024         j = 1;
107025         while( j<nMerge
107026             && apSegment[j]->pOffsetList
107027             && apSegment[j]->iDocid==iDocid
107028         ){
107029           fts3SegReaderNextDocid(apSegment[j], 0, 0);
107030           j++;
107031         }
107032
107033         if( isColFilter ){
107034           fts3ColumnFilter(pFilter->iCol, &pList, &nList);
107035         }
107036
107037         if( !isIgnoreEmpty || nList>0 ){
107038           nByte = sqlite3Fts3VarintLen(iDocid-iPrev) + (isRequirePos?nList+1:0);
107039           if( nDoclist+nByte>nAlloc ){
107040             char *aNew;
107041             nAlloc = nDoclist+nByte*2;
107042             aNew = sqlite3_realloc(aBuffer, nAlloc);
107043             if( !aNew ){
107044               rc = SQLITE_NOMEM;
107045               goto finished;
107046             }
107047             aBuffer = aNew;
107048           }
107049           nDoclist += sqlite3Fts3PutVarint(&aBuffer[nDoclist], iDocid-iPrev);
107050           iPrev = iDocid;
107051           if( isRequirePos ){
107052             memcpy(&aBuffer[nDoclist], pList, nList);
107053             nDoclist += nList;
107054             aBuffer[nDoclist++] = '\0';
107055           }
107056         }
107057
107058         fts3SegReaderSort(apSegment, nMerge, j, fts3SegReaderDoclistCmp);
107059       }
107060
107061       if( nDoclist>0 ){
107062         rc = xFunc(p, pContext, zTerm, nTerm, aBuffer, nDoclist);
107063         if( rc!=SQLITE_OK ) goto finished;
107064       }
107065     }
107066
107067     /* If there is a term specified to filter on, and this is not a prefix
107068     ** search, return now. The callback that corresponds to the required
107069     ** term (if such a term exists in the index) has already been made.
107070     */
107071     if( pFilter->zTerm && !isPrefix ){
107072       goto finished;
107073     }
107074
107075     for(i=0; i<nMerge; i++){
107076       rc = fts3SegReaderNext(apSegment[i]);
107077       if( rc!=SQLITE_OK ) goto finished;
107078     }
107079     fts3SegReaderSort(apSegment, nSegment, nMerge, fts3SegReaderCmp);
107080   }
107081
107082  finished:
107083   sqlite3_free(aBuffer);
107084   return rc;
107085 }
107086
107087 /*
107088 ** Merge all level iLevel segments in the database into a single 
107089 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
107090 ** single segment with a level equal to the numerically largest level 
107091 ** currently present in the database.
107092 **
107093 ** If this function is called with iLevel<0, but there is only one
107094 ** segment in the database, SQLITE_DONE is returned immediately. 
107095 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, 
107096 ** an SQLite error code is returned.
107097 */
107098 static int fts3SegmentMerge(Fts3Table *p, int iLevel){
107099   int i;                          /* Iterator variable */
107100   int rc;                         /* Return code */
107101   int iIdx;                       /* Index of new segment */
107102   int iNewLevel;                  /* Level to create new segment at */
107103   sqlite3_stmt *pStmt = 0;
107104   SegmentWriter *pWriter = 0;
107105   int nSegment = 0;               /* Number of segments being merged */
107106   Fts3SegReader **apSegment = 0;  /* Array of Segment iterators */
107107   Fts3SegReader *pPending = 0;    /* Iterator for pending-terms */
107108   Fts3SegFilter filter;           /* Segment term filter condition */
107109
107110   if( iLevel<0 ){
107111     /* This call is to merge all segments in the database to a single
107112     ** segment. The level of the new segment is equal to the the numerically 
107113     ** greatest segment level currently present in the database. The index
107114     ** of the new segment is always 0.
107115     */
107116     iIdx = 0;
107117     rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pPending);
107118     if( rc!=SQLITE_OK ) goto finished;
107119     rc = fts3SegmentCountMax(p, &nSegment, &iNewLevel);
107120     if( rc!=SQLITE_OK ) goto finished;
107121     nSegment += (pPending!=0);
107122     if( nSegment<=1 ){
107123       return SQLITE_DONE;
107124     }
107125   }else{
107126     /* This call is to merge all segments at level iLevel. Find the next
107127     ** available segment index at level iLevel+1. The call to
107128     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
107129     ** a single iLevel+2 segment if necessary.
107130     */
107131     iNewLevel = iLevel+1;
107132     rc = fts3AllocateSegdirIdx(p, iNewLevel, &iIdx);
107133     if( rc!=SQLITE_OK ) goto finished;
107134     rc = fts3SegmentCount(p, iLevel, &nSegment);
107135     if( rc!=SQLITE_OK ) goto finished;
107136   }
107137   assert( nSegment>0 );
107138   assert( iNewLevel>=0 );
107139
107140   /* Allocate space for an array of pointers to segment iterators. */
107141   apSegment = (Fts3SegReader**)sqlite3_malloc(sizeof(Fts3SegReader *)*nSegment);
107142   if( !apSegment ){
107143     rc = SQLITE_NOMEM;
107144     goto finished;
107145   }
107146   memset(apSegment, 0, sizeof(Fts3SegReader *)*nSegment);
107147
107148   /* Allocate a Fts3SegReader structure for each segment being merged. A 
107149   ** Fts3SegReader stores the state data required to iterate through all 
107150   ** entries on all leaves of a single segment. 
107151   */
107152   assert( SQL_SELECT_LEVEL+1==SQL_SELECT_ALL_LEVEL);
107153   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL+(iLevel<0), &pStmt, 0);
107154   if( rc!=SQLITE_OK ) goto finished;
107155   sqlite3_bind_int(pStmt, 1, iLevel);
107156   for(i=0; SQLITE_ROW==(sqlite3_step(pStmt)); i++){
107157     rc = fts3SegReaderNew(p, pStmt, i, &apSegment[i]);
107158     if( rc!=SQLITE_OK ){
107159       goto finished;
107160     }
107161   }
107162   rc = sqlite3_reset(pStmt);
107163   if( pPending ){
107164     apSegment[i] = pPending;
107165     pPending = 0;
107166   }
107167   pStmt = 0;
107168   if( rc!=SQLITE_OK ) goto finished;
107169
107170   memset(&filter, 0, sizeof(Fts3SegFilter));
107171   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
107172   filter.flags |= (iLevel<0 ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
107173   rc = sqlite3Fts3SegReaderIterate(p, apSegment, nSegment,
107174       &filter, fts3MergeCallback, (void *)&pWriter
107175   );
107176   if( rc!=SQLITE_OK ) goto finished;
107177
107178   rc = fts3DeleteSegdir(p, iLevel, apSegment, nSegment);
107179   if( rc==SQLITE_OK ){
107180     rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
107181   }
107182
107183  finished:
107184   fts3SegWriterFree(pWriter);
107185   if( apSegment ){
107186     for(i=0; i<nSegment; i++){
107187       sqlite3Fts3SegReaderFree(p, apSegment[i]);
107188     }
107189     sqlite3_free(apSegment);
107190   }
107191   sqlite3Fts3SegReaderFree(p, pPending);
107192   sqlite3_reset(pStmt);
107193   return rc;
107194 }
107195
107196
107197 /* 
107198 ** Flush the contents of pendingTerms to a level 0 segment.
107199 */
107200 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
107201   int rc;                         /* Return Code */
107202   int idx;                        /* Index of new segment created */
107203   SegmentWriter *pWriter = 0;     /* Used to write the segment */
107204   Fts3SegReader *pReader = 0;     /* Used to iterate through the hash table */
107205
107206   /* Allocate a SegReader object to iterate through the contents of the
107207   ** pending-terms table. If an error occurs, or if there are no terms
107208   ** in the pending-terms table, return immediately.
107209   */
107210   rc = sqlite3Fts3SegReaderPending(p, 0, 0, 1, &pReader);
107211   if( rc!=SQLITE_OK || pReader==0 ){
107212     return rc;
107213   }
107214
107215   /* Determine the next index at level 0. If level 0 is already full, this
107216   ** call may merge all existing level 0 segments into a single level 1
107217   ** segment.
107218   */
107219   rc = fts3AllocateSegdirIdx(p, 0, &idx);
107220
107221   /* If no errors have occured, iterate through the contents of the 
107222   ** pending-terms hash table using the Fts3SegReader iterator. The callback
107223   ** writes each term (along with its doclist) to the database via the
107224   ** SegmentWriter handle pWriter.
107225   */
107226   if( rc==SQLITE_OK ){
107227     void *c = (void *)&pWriter;   /* SegReaderIterate() callback context */
107228     Fts3SegFilter f;              /* SegReaderIterate() parameters */
107229
107230     memset(&f, 0, sizeof(Fts3SegFilter));
107231     f.flags = FTS3_SEGMENT_REQUIRE_POS;
107232     rc = sqlite3Fts3SegReaderIterate(p, &pReader, 1, &f, fts3FlushCallback, c);
107233   }
107234   assert( pWriter || rc!=SQLITE_OK );
107235
107236   /* If no errors have occured, flush the SegmentWriter object to the
107237   ** database. Then delete the SegmentWriter and Fts3SegReader objects
107238   ** allocated by this function.
107239   */
107240   if( rc==SQLITE_OK ){
107241     rc = fts3SegWriterFlush(p, pWriter, 0, idx);
107242   }
107243   fts3SegWriterFree(pWriter);
107244   sqlite3Fts3SegReaderFree(p, pReader);
107245
107246   if( rc==SQLITE_OK ){
107247     sqlite3Fts3PendingTermsClear(p);
107248   }
107249   return rc;
107250 }
107251
107252 /*
107253 ** Encode N integers as varints into a blob.
107254 */
107255 static void fts3EncodeIntArray(
107256   int N,             /* The number of integers to encode */
107257   u32 *a,            /* The integer values */
107258   char *zBuf,        /* Write the BLOB here */
107259   int *pNBuf         /* Write number of bytes if zBuf[] used here */
107260 ){
107261   int i, j;
107262   for(i=j=0; i<N; i++){
107263     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
107264   }
107265   *pNBuf = j;
107266 }
107267
107268 /*
107269 ** Decode a blob of varints into N integers
107270 */
107271 static void fts3DecodeIntArray(
107272   int N,             /* The number of integers to decode */
107273   u32 *a,            /* Write the integer values */
107274   const char *zBuf,  /* The BLOB containing the varints */
107275   int nBuf           /* size of the BLOB */
107276 ){
107277   int i, j;
107278   UNUSED_PARAMETER(nBuf);
107279   for(i=j=0; i<N; i++){
107280     sqlite3_int64 x;
107281     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
107282     assert(j<=nBuf);
107283     a[i] = (u32)(x & 0xffffffff);
107284   }
107285 }
107286
107287 /*
107288 ** Fill in the document size auxiliary information for the matchinfo
107289 ** structure.  The auxiliary information is:
107290 **
107291 **    N     Total number of documents in the full-text index
107292 **    a0    Average length of column 0 over the whole index
107293 **    n0    Length of column 0 on the matching row
107294 **    ...
107295 **    aM    Average length of column M over the whole index
107296 **    nM    Length of column M on the matching row
107297 **
107298 ** The fts3MatchinfoDocsizeLocal() routine fills in the nX values.
107299 ** The fts3MatchinfoDocsizeGlobal() routine fills in N and the aX values.
107300 */
107301 SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeLocal(Fts3Cursor *pCur, u32 *a){
107302   const char *pBlob;       /* The BLOB holding %_docsize info */
107303   int nBlob;               /* Size of the BLOB */
107304   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
107305   int i, j;                /* Loop counters */
107306   sqlite3_int64 x;         /* Varint value */
107307   int rc;                  /* Result code from subfunctions */
107308   Fts3Table *p;            /* The FTS table */
107309
107310   p = (Fts3Table*)pCur->base.pVtab;
107311   rc = fts3SqlStmt(p, SQL_SELECT_DOCSIZE, &pStmt, 0);
107312   if( rc ){
107313     return rc;
107314   }
107315   sqlite3_bind_int64(pStmt, 1, pCur->iPrevId);
107316   if( sqlite3_step(pStmt)==SQLITE_ROW ){
107317     nBlob = sqlite3_column_bytes(pStmt, 0);
107318     pBlob = (const char*)sqlite3_column_blob(pStmt, 0);
107319     for(i=j=0; i<p->nColumn && j<nBlob; i++){
107320       j = sqlite3Fts3GetVarint(&pBlob[j], &x);
107321       a[2+i*2] = (u32)(x & 0xffffffff);
107322     }
107323   }
107324   sqlite3_reset(pStmt);
107325   return SQLITE_OK; 
107326 }
107327 SQLITE_PRIVATE int sqlite3Fts3MatchinfoDocsizeGlobal(Fts3Cursor *pCur, u32 *a){
107328   const char *pBlob;       /* The BLOB holding %_stat info */
107329   int nBlob;               /* Size of the BLOB */
107330   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
107331   int i, j;                /* Loop counters */
107332   sqlite3_int64 x;         /* Varint value */
107333   int nDoc;                /* Number of documents */
107334   int rc;                  /* Result code from subfunctions */
107335   Fts3Table *p;            /* The FTS table */
107336
107337   p = (Fts3Table*)pCur->base.pVtab;
107338   rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
107339   if( rc ){
107340     return rc;
107341   }
107342   if( sqlite3_step(pStmt)==SQLITE_ROW ){
107343     nBlob = sqlite3_column_bytes(pStmt, 0);
107344     pBlob = (const char*)sqlite3_column_blob(pStmt, 0);
107345     j = sqlite3Fts3GetVarint(pBlob, &x);
107346     a[0] = nDoc = (u32)(x & 0xffffffff);
107347     for(i=0; i<p->nColumn && j<nBlob; i++){
107348       j = sqlite3Fts3GetVarint(&pBlob[j], &x);
107349       a[1+i*2] = ((u32)(x & 0xffffffff) + nDoc/2)/nDoc;
107350     }
107351   }
107352   sqlite3_reset(pStmt);
107353   return SQLITE_OK; 
107354 }
107355
107356 /*
107357 ** Insert the sizes (in tokens) for each column of the document
107358 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
107359 ** a blob of varints.
107360 */
107361 static void fts3InsertDocsize(
107362   int *pRC,         /* Result code */
107363   Fts3Table *p,     /* Table into which to insert */
107364   u32 *aSz          /* Sizes of each column */
107365 ){
107366   char *pBlob;             /* The BLOB encoding of the document size */
107367   int nBlob;               /* Number of bytes in the BLOB */
107368   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
107369   int rc;                  /* Result code from subfunctions */
107370
107371   if( *pRC ) return;
107372   pBlob = sqlite3_malloc( 10*p->nColumn );
107373   if( pBlob==0 ){
107374     *pRC = SQLITE_NOMEM;
107375     return;
107376   }
107377   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
107378   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
107379   if( rc ){
107380     sqlite3_free(pBlob);
107381     *pRC = rc;
107382     return;
107383   }
107384   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
107385   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
107386   sqlite3_step(pStmt);
107387   *pRC = sqlite3_reset(pStmt);
107388 }
107389
107390 /*
107391 ** Update the 0 record of the %_stat table so that it holds a blob
107392 ** which contains the document count followed by the cumulative
107393 ** document sizes for all columns.
107394 */
107395 static void fts3UpdateDocTotals(
107396   int *pRC,       /* The result code */
107397   Fts3Table *p,   /* Table being updated */
107398   u32 *aSzIns,    /* Size increases */
107399   u32 *aSzDel,    /* Size decreases */
107400   int nChng       /* Change in the number of documents */
107401 ){
107402   char *pBlob;             /* Storage for BLOB written into %_stat */
107403   int nBlob;               /* Size of BLOB written into %_stat */
107404   u32 *a;                  /* Array of integers that becomes the BLOB */
107405   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
107406   int i;                   /* Loop counter */
107407   int rc;                  /* Result code from subfunctions */
107408
107409   if( *pRC ) return;
107410   a = sqlite3_malloc( (sizeof(u32)+10)*(p->nColumn+1) );
107411   if( a==0 ){
107412     *pRC = SQLITE_NOMEM;
107413     return;
107414   }
107415   pBlob = (char*)&a[p->nColumn+1];
107416   rc = fts3SqlStmt(p, SQL_SELECT_DOCTOTAL, &pStmt, 0);
107417   if( rc ){
107418     sqlite3_free(a);
107419     *pRC = rc;
107420     return;
107421   }
107422   if( sqlite3_step(pStmt)==SQLITE_ROW ){
107423     fts3DecodeIntArray(p->nColumn+1, a,
107424          sqlite3_column_blob(pStmt, 0),
107425          sqlite3_column_bytes(pStmt, 0));
107426   }else{
107427     memset(a, 0, sizeof(u32)*(p->nColumn+1) );
107428   }
107429   sqlite3_reset(pStmt);
107430   if( nChng<0 && a[0]<(u32)(-nChng) ){
107431     a[0] = 0;
107432   }else{
107433     a[0] += nChng;
107434   }
107435   for(i=0; i<p->nColumn; i++){
107436     u32 x = a[i+1];
107437     if( x+aSzIns[i] < aSzDel[i] ){
107438       x = 0;
107439     }else{
107440       x = x + aSzIns[i] - aSzDel[i];
107441     }
107442     a[i+1] = x;
107443   }
107444   fts3EncodeIntArray(p->nColumn+1, a, pBlob, &nBlob);
107445   rc = fts3SqlStmt(p, SQL_REPLACE_DOCTOTAL, &pStmt, 0);
107446   if( rc ){
107447     sqlite3_free(a);
107448     *pRC = rc;
107449     return;
107450   }
107451   sqlite3_bind_blob(pStmt, 1, pBlob, nBlob, SQLITE_STATIC);
107452   sqlite3_step(pStmt);
107453   *pRC = sqlite3_reset(pStmt);
107454   sqlite3_free(a);
107455 }
107456
107457 /*
107458 ** Handle a 'special' INSERT of the form:
107459 **
107460 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
107461 **
107462 ** Argument pVal contains the result of <expr>. Currently the only 
107463 ** meaningful value to insert is the text 'optimize'.
107464 */
107465 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
107466   int rc;                         /* Return Code */
107467   const char *zVal = (const char *)sqlite3_value_text(pVal);
107468   int nVal = sqlite3_value_bytes(pVal);
107469
107470   if( !zVal ){
107471     return SQLITE_NOMEM;
107472   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
107473     rc = fts3SegmentMerge(p, -1);
107474     if( rc==SQLITE_DONE ){
107475       rc = SQLITE_OK;
107476     }else{
107477       sqlite3Fts3PendingTermsClear(p);
107478     }
107479 #ifdef SQLITE_TEST
107480   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
107481     p->nNodeSize = atoi(&zVal[9]);
107482     rc = SQLITE_OK;
107483   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
107484     p->nMaxPendingData = atoi(&zVal[11]);
107485     rc = SQLITE_OK;
107486 #endif
107487   }else{
107488     rc = SQLITE_ERROR;
107489   }
107490
107491   return rc;
107492 }
107493
107494 /*
107495 ** This function does the work for the xUpdate method of FTS3 virtual
107496 ** tables.
107497 */
107498 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
107499   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
107500   int nArg,                       /* Size of argument array */
107501   sqlite3_value **apVal,          /* Array of arguments */
107502   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
107503 ){
107504   Fts3Table *p = (Fts3Table *)pVtab;
107505   int rc = SQLITE_OK;             /* Return Code */
107506   int isRemove = 0;               /* True for an UPDATE or DELETE */
107507   sqlite3_int64 iRemove = 0;      /* Rowid removed by UPDATE or DELETE */
107508   u32 *aSzIns;                    /* Sizes of inserted documents */
107509   u32 *aSzDel;                    /* Sizes of deleted documents */
107510   int nChng = 0;                  /* Net change in number of documents */
107511
107512
107513   /* Allocate space to hold the change in document sizes */
107514   aSzIns = sqlite3_malloc( sizeof(aSzIns[0])*p->nColumn*2 );
107515   if( aSzIns==0 ) return SQLITE_NOMEM;
107516   aSzDel = &aSzIns[p->nColumn];
107517   memset(aSzIns, 0, sizeof(aSzIns[0])*p->nColumn*2);
107518
107519   /* If this is a DELETE or UPDATE operation, remove the old record. */
107520   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
107521     int isEmpty;
107522     rc = fts3IsEmpty(p, apVal, &isEmpty);
107523     if( rc==SQLITE_OK ){
107524       if( isEmpty ){
107525         /* Deleting this row means the whole table is empty. In this case
107526         ** delete the contents of all three tables and throw away any
107527         ** data in the pendingTerms hash table.
107528         */
107529         rc = fts3DeleteAll(p);
107530       }else{
107531         isRemove = 1;
107532         iRemove = sqlite3_value_int64(apVal[0]);
107533         rc = fts3PendingTermsDocid(p, iRemove);
107534         fts3DeleteTerms(&rc, p, apVal, aSzDel);
107535         fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, apVal);
107536         if( p->bHasDocsize ){
107537           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, apVal);
107538           nChng--;
107539         }
107540       }
107541     }
107542   }else if( sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL ){
107543     sqlite3_free(aSzIns);
107544     return fts3SpecialInsert(p, apVal[p->nColumn+2]);
107545   }
107546   
107547   /* If this is an INSERT or UPDATE operation, insert the new record. */
107548   if( nArg>1 && rc==SQLITE_OK ){
107549     rc = fts3InsertData(p, apVal, pRowid);
107550     if( rc==SQLITE_OK && (!isRemove || *pRowid!=iRemove) ){
107551       rc = fts3PendingTermsDocid(p, *pRowid);
107552     }
107553     if( rc==SQLITE_OK ){
107554       rc = fts3InsertTerms(p, apVal, aSzIns);
107555     }
107556     if( p->bHasDocsize ){
107557       nChng++;
107558       fts3InsertDocsize(&rc, p, aSzIns);
107559     }
107560   }
107561
107562   if( p->bHasDocsize ){
107563     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
107564   }
107565
107566   sqlite3_free(aSzIns);
107567   return rc;
107568 }
107569
107570 /* 
107571 ** Flush any data in the pending-terms hash table to disk. If successful,
107572 ** merge all segments in the database (including the new segment, if 
107573 ** there was any data to flush) into a single segment. 
107574 */
107575 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
107576   int rc;
107577   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
107578   if( rc==SQLITE_OK ){
107579     rc = fts3SegmentMerge(p, -1);
107580     if( rc==SQLITE_OK ){
107581       rc = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
107582       if( rc==SQLITE_OK ){
107583         sqlite3Fts3PendingTermsClear(p);
107584       }
107585     }else{
107586       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
107587       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
107588     }
107589   }
107590   return rc;
107591 }
107592
107593 #endif
107594
107595 /************** End of fts3_write.c ******************************************/
107596 /************** Begin file fts3_snippet.c ************************************/
107597 /*
107598 ** 2009 Oct 23
107599 **
107600 ** The author disclaims copyright to this source code.  In place of
107601 ** a legal notice, here is a blessing:
107602 **
107603 **    May you do good and not evil.
107604 **    May you find forgiveness for yourself and forgive others.
107605 **    May you share freely, never taking more than you give.
107606 **
107607 ******************************************************************************
107608 */
107609
107610 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
107611
107612
107613
107614 /*
107615 ** Used as an fts3ExprIterate() context when loading phrase doclists to
107616 ** Fts3Expr.aDoclist[]/nDoclist.
107617 */
107618 typedef struct LoadDoclistCtx LoadDoclistCtx;
107619 struct LoadDoclistCtx {
107620   Fts3Table *pTab;                /* FTS3 Table */
107621   int nPhrase;                    /* Number of phrases seen so far */
107622   int nToken;                     /* Number of tokens seen so far */
107623 };
107624
107625 /*
107626 ** The following types are used as part of the implementation of the 
107627 ** fts3BestSnippet() routine.
107628 */
107629 typedef struct SnippetIter SnippetIter;
107630 typedef struct SnippetPhrase SnippetPhrase;
107631 typedef struct SnippetFragment SnippetFragment;
107632
107633 struct SnippetIter {
107634   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
107635   int iCol;                       /* Extract snippet from this column */
107636   int nSnippet;                   /* Requested snippet length (in tokens) */
107637   int nPhrase;                    /* Number of phrases in query */
107638   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
107639   int iCurrent;                   /* First token of current snippet */
107640 };
107641
107642 struct SnippetPhrase {
107643   int nToken;                     /* Number of tokens in phrase */
107644   char *pList;                    /* Pointer to start of phrase position list */
107645   int iHead;                      /* Next value in position list */
107646   char *pHead;                    /* Position list data following iHead */
107647   int iTail;                      /* Next value in trailing position list */
107648   char *pTail;                    /* Position list data following iTail */
107649 };
107650
107651 struct SnippetFragment {
107652   int iCol;                       /* Column snippet is extracted from */
107653   int iPos;                       /* Index of first token in snippet */
107654   u64 covered;                    /* Mask of query phrases covered */
107655   u64 hlmask;                     /* Mask of snippet terms to highlight */
107656 };
107657
107658 /*
107659 ** This type is used as an fts3ExprIterate() context object while 
107660 ** accumulating the data returned by the matchinfo() function.
107661 */
107662 typedef struct MatchInfo MatchInfo;
107663 struct MatchInfo {
107664   Fts3Cursor *pCursor;            /* FTS3 Cursor */
107665   int nCol;                       /* Number of columns in table */
107666   u32 *aMatchinfo;                /* Pre-allocated buffer */
107667 };
107668
107669
107670
107671 /*
107672 ** The snippet() and offsets() functions both return text values. An instance
107673 ** of the following structure is used to accumulate those values while the
107674 ** functions are running. See fts3StringAppend() for details.
107675 */
107676 typedef struct StrBuffer StrBuffer;
107677 struct StrBuffer {
107678   char *z;                        /* Pointer to buffer containing string */
107679   int n;                          /* Length of z in bytes (excl. nul-term) */
107680   int nAlloc;                     /* Allocated size of buffer z in bytes */
107681 };
107682
107683
107684 /*
107685 ** This function is used to help iterate through a position-list. A position
107686 ** list is a list of unique integers, sorted from smallest to largest. Each
107687 ** element of the list is represented by an FTS3 varint that takes the value
107688 ** of the difference between the current element and the previous one plus
107689 ** two. For example, to store the position-list:
107690 **
107691 **     4 9 113
107692 **
107693 ** the three varints:
107694 **
107695 **     6 7 106
107696 **
107697 ** are encoded.
107698 **
107699 ** When this function is called, *pp points to the start of an element of
107700 ** the list. *piPos contains the value of the previous entry in the list.
107701 ** After it returns, *piPos contains the value of the next element of the
107702 ** list and *pp is advanced to the following varint.
107703 */
107704 static void fts3GetDeltaPosition(char **pp, int *piPos){
107705   int iVal;
107706   *pp += sqlite3Fts3GetVarint32(*pp, &iVal);
107707   *piPos += (iVal-2);
107708 }
107709
107710 /*
107711 ** Helper function for fts3ExprIterate() (see below).
107712 */
107713 static int fts3ExprIterate2(
107714   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
107715   int *piPhrase,                  /* Pointer to phrase counter */
107716   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
107717   void *pCtx                      /* Second argument to pass to callback */
107718 ){
107719   int rc;                         /* Return code */
107720   int eType = pExpr->eType;       /* Type of expression node pExpr */
107721
107722   if( eType!=FTSQUERY_PHRASE ){
107723     assert( pExpr->pLeft && pExpr->pRight );
107724     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
107725     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
107726       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
107727     }
107728   }else{
107729     rc = x(pExpr, *piPhrase, pCtx);
107730     (*piPhrase)++;
107731   }
107732   return rc;
107733 }
107734
107735 /*
107736 ** Iterate through all phrase nodes in an FTS3 query, except those that
107737 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
107738 ** For each phrase node found, the supplied callback function is invoked.
107739 **
107740 ** If the callback function returns anything other than SQLITE_OK, 
107741 ** the iteration is abandoned and the error code returned immediately.
107742 ** Otherwise, SQLITE_OK is returned after a callback has been made for
107743 ** all eligible phrase nodes.
107744 */
107745 static int fts3ExprIterate(
107746   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
107747   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
107748   void *pCtx                      /* Second argument to pass to callback */
107749 ){
107750   int iPhrase = 0;                /* Variable used as the phrase counter */
107751   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
107752 }
107753
107754 /*
107755 ** The argument to this function is always a phrase node. Its doclist 
107756 ** (Fts3Expr.aDoclist[]) and the doclists associated with all phrase nodes
107757 ** to the left of this one in the query tree have already been loaded.
107758 **
107759 ** If this phrase node is part of a series of phrase nodes joined by 
107760 ** NEAR operators (and is not the left-most of said series), then elements are
107761 ** removed from the phrases doclist consistent with the NEAR restriction. If
107762 ** required, elements may be removed from the doclists of phrases to the
107763 ** left of this one that are part of the same series of NEAR operator 
107764 ** connected phrases.
107765 **
107766 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
107767 */
107768 static int fts3ExprNearTrim(Fts3Expr *pExpr){
107769   int rc = SQLITE_OK;
107770   Fts3Expr *pParent = pExpr->pParent;
107771
107772   assert( pExpr->eType==FTSQUERY_PHRASE );
107773   while( rc==SQLITE_OK
107774    && pParent 
107775    && pParent->eType==FTSQUERY_NEAR 
107776    && pParent->pRight==pExpr 
107777   ){
107778     /* This expression (pExpr) is the right-hand-side of a NEAR operator. 
107779     ** Find the expression to the left of the same operator.
107780     */
107781     int nNear = pParent->nNear;
107782     Fts3Expr *pLeft = pParent->pLeft;
107783
107784     if( pLeft->eType!=FTSQUERY_PHRASE ){
107785       assert( pLeft->eType==FTSQUERY_NEAR );
107786       assert( pLeft->pRight->eType==FTSQUERY_PHRASE );
107787       pLeft = pLeft->pRight;
107788     }
107789
107790     rc = sqlite3Fts3ExprNearTrim(pLeft, pExpr, nNear);
107791
107792     pExpr = pLeft;
107793     pParent = pExpr->pParent;
107794   }
107795
107796   return rc;
107797 }
107798
107799 /*
107800 ** This is an fts3ExprIterate() callback used while loading the doclists
107801 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
107802 ** fts3ExprLoadDoclists().
107803 */
107804 static int fts3ExprLoadDoclistsCb1(Fts3Expr *pExpr, int iPhrase, void *ctx){
107805   int rc = SQLITE_OK;
107806   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
107807
107808   UNUSED_PARAMETER(iPhrase);
107809
107810   p->nPhrase++;
107811   p->nToken += pExpr->pPhrase->nToken;
107812
107813   if( pExpr->isLoaded==0 ){
107814     rc = sqlite3Fts3ExprLoadDoclist(p->pTab, pExpr);
107815     pExpr->isLoaded = 1;
107816     if( rc==SQLITE_OK ){
107817       rc = fts3ExprNearTrim(pExpr);
107818     }
107819   }
107820
107821   return rc;
107822 }
107823
107824 /*
107825 ** This is an fts3ExprIterate() callback used while loading the doclists
107826 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
107827 ** fts3ExprLoadDoclists().
107828 */
107829 static int fts3ExprLoadDoclistsCb2(Fts3Expr *pExpr, int iPhrase, void *ctx){
107830   UNUSED_PARAMETER(iPhrase);
107831   UNUSED_PARAMETER(ctx);
107832   if( pExpr->aDoclist ){
107833     pExpr->pCurrent = pExpr->aDoclist;
107834     pExpr->iCurrent = 0;
107835     pExpr->pCurrent += sqlite3Fts3GetVarint(pExpr->pCurrent, &pExpr->iCurrent);
107836   }
107837   return SQLITE_OK;
107838 }
107839
107840 /*
107841 ** Load the doclists for each phrase in the query associated with FTS3 cursor
107842 ** pCsr. 
107843 **
107844 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 
107845 ** phrases in the expression (all phrases except those directly or 
107846 ** indirectly descended from the right-hand-side of a NOT operator). If 
107847 ** pnToken is not NULL, then it is set to the number of tokens in all
107848 ** matchable phrases of the expression.
107849 */
107850 static int fts3ExprLoadDoclists(
107851   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
107852   int *pnPhrase,                  /* OUT: Number of phrases in query */
107853   int *pnToken                    /* OUT: Number of tokens in query */
107854 ){
107855   int rc;                         /* Return Code */
107856   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
107857   sCtx.pTab = (Fts3Table *)pCsr->base.pVtab;
107858   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb1, (void *)&sCtx);
107859   if( rc==SQLITE_OK ){
107860     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb2, 0);
107861   }
107862   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
107863   if( pnToken ) *pnToken = sCtx.nToken;
107864   return rc;
107865 }
107866
107867 /*
107868 ** Advance the position list iterator specified by the first two 
107869 ** arguments so that it points to the first element with a value greater
107870 ** than or equal to parameter iNext.
107871 */
107872 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
107873   char *pIter = *ppIter;
107874   if( pIter ){
107875     int iIter = *piIter;
107876
107877     while( iIter<iNext ){
107878       if( 0==(*pIter & 0xFE) ){
107879         iIter = -1;
107880         pIter = 0;
107881         break;
107882       }
107883       fts3GetDeltaPosition(&pIter, &iIter);
107884     }
107885
107886     *piIter = iIter;
107887     *ppIter = pIter;
107888   }
107889 }
107890
107891 /*
107892 ** Advance the snippet iterator to the next candidate snippet.
107893 */
107894 static int fts3SnippetNextCandidate(SnippetIter *pIter){
107895   int i;                          /* Loop counter */
107896
107897   if( pIter->iCurrent<0 ){
107898     /* The SnippetIter object has just been initialized. The first snippet
107899     ** candidate always starts at offset 0 (even if this candidate has a
107900     ** score of 0.0).
107901     */
107902     pIter->iCurrent = 0;
107903
107904     /* Advance the 'head' iterator of each phrase to the first offset that
107905     ** is greater than or equal to (iNext+nSnippet).
107906     */
107907     for(i=0; i<pIter->nPhrase; i++){
107908       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
107909       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
107910     }
107911   }else{
107912     int iStart;
107913     int iEnd = 0x7FFFFFFF;
107914
107915     for(i=0; i<pIter->nPhrase; i++){
107916       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
107917       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
107918         iEnd = pPhrase->iHead;
107919       }
107920     }
107921     if( iEnd==0x7FFFFFFF ){
107922       return 1;
107923     }
107924
107925     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
107926     for(i=0; i<pIter->nPhrase; i++){
107927       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
107928       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
107929       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
107930     }
107931   }
107932
107933   return 0;
107934 }
107935
107936 /*
107937 ** Retrieve information about the current candidate snippet of snippet 
107938 ** iterator pIter.
107939 */
107940 static void fts3SnippetDetails(
107941   SnippetIter *pIter,             /* Snippet iterator */
107942   u64 mCovered,                   /* Bitmask of phrases already covered */
107943   int *piToken,                   /* OUT: First token of proposed snippet */
107944   int *piScore,                   /* OUT: "Score" for this snippet */
107945   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
107946   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
107947 ){
107948   int iStart = pIter->iCurrent;   /* First token of snippet */
107949   int iScore = 0;                 /* Score of this snippet */
107950   int i;                          /* Loop counter */
107951   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
107952   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
107953
107954   for(i=0; i<pIter->nPhrase; i++){
107955     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
107956     if( pPhrase->pTail ){
107957       char *pCsr = pPhrase->pTail;
107958       int iCsr = pPhrase->iTail;
107959
107960       while( iCsr<(iStart+pIter->nSnippet) ){
107961         int j;
107962         u64 mPhrase = (u64)1 << i;
107963         u64 mPos = (u64)1 << (iCsr - iStart);
107964         assert( iCsr>=iStart );
107965         if( (mCover|mCovered)&mPhrase ){
107966           iScore++;
107967         }else{
107968           iScore += 1000;
107969         }
107970         mCover |= mPhrase;
107971
107972         for(j=0; j<pPhrase->nToken; j++){
107973           mHighlight |= (mPos>>j);
107974         }
107975
107976         if( 0==(*pCsr & 0x0FE) ) break;
107977         fts3GetDeltaPosition(&pCsr, &iCsr);
107978       }
107979     }
107980   }
107981
107982   /* Set the output variables before returning. */
107983   *piToken = iStart;
107984   *piScore = iScore;
107985   *pmCover = mCover;
107986   *pmHighlight = mHighlight;
107987 }
107988
107989 /*
107990 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
107991 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
107992 */
107993 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
107994   SnippetIter *p = (SnippetIter *)ctx;
107995   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
107996   char *pCsr;
107997
107998   pPhrase->nToken = pExpr->pPhrase->nToken;
107999
108000   pCsr = sqlite3Fts3FindPositions(pExpr, p->pCsr->iPrevId, p->iCol);
108001   if( pCsr ){
108002     int iFirst = 0;
108003     pPhrase->pList = pCsr;
108004     fts3GetDeltaPosition(&pCsr, &iFirst);
108005     pPhrase->pHead = pCsr;
108006     pPhrase->pTail = pCsr;
108007     pPhrase->iHead = iFirst;
108008     pPhrase->iTail = iFirst;
108009   }else{
108010     assert( pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 );
108011   }
108012
108013   return SQLITE_OK;
108014 }
108015
108016 /*
108017 ** Select the fragment of text consisting of nFragment contiguous tokens 
108018 ** from column iCol that represent the "best" snippet. The best snippet
108019 ** is the snippet with the highest score, where scores are calculated
108020 ** by adding:
108021 **
108022 **   (a) +1 point for each occurence of a matchable phrase in the snippet.
108023 **
108024 **   (b) +1000 points for the first occurence of each matchable phrase in 
108025 **       the snippet for which the corresponding mCovered bit is not set.
108026 **
108027 ** The selected snippet parameters are stored in structure *pFragment before
108028 ** returning. The score of the selected snippet is stored in *piScore
108029 ** before returning.
108030 */
108031 static int fts3BestSnippet(
108032   int nSnippet,                   /* Desired snippet length */
108033   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
108034   int iCol,                       /* Index of column to create snippet from */
108035   u64 mCovered,                   /* Mask of phrases already covered */
108036   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
108037   SnippetFragment *pFragment,     /* OUT: Best snippet found */
108038   int *piScore                    /* OUT: Score of snippet pFragment */
108039 ){
108040   int rc;                         /* Return Code */
108041   int nList;                      /* Number of phrases in expression */
108042   SnippetIter sIter;              /* Iterates through snippet candidates */
108043   int nByte;                      /* Number of bytes of space to allocate */
108044   int iBestScore = -1;            /* Best snippet score found so far */
108045   int i;                          /* Loop counter */
108046
108047   memset(&sIter, 0, sizeof(sIter));
108048
108049   /* Iterate through the phrases in the expression to count them. The same
108050   ** callback makes sure the doclists are loaded for each phrase.
108051   */
108052   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
108053   if( rc!=SQLITE_OK ){
108054     return rc;
108055   }
108056
108057   /* Now that it is known how many phrases there are, allocate and zero
108058   ** the required space using malloc().
108059   */
108060   nByte = sizeof(SnippetPhrase) * nList;
108061   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
108062   if( !sIter.aPhrase ){
108063     return SQLITE_NOMEM;
108064   }
108065   memset(sIter.aPhrase, 0, nByte);
108066
108067   /* Initialize the contents of the SnippetIter object. Then iterate through
108068   ** the set of phrases in the expression to populate the aPhrase[] array.
108069   */
108070   sIter.pCsr = pCsr;
108071   sIter.iCol = iCol;
108072   sIter.nSnippet = nSnippet;
108073   sIter.nPhrase = nList;
108074   sIter.iCurrent = -1;
108075   (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
108076
108077   /* Set the *pmSeen output variable. */
108078   for(i=0; i<nList; i++){
108079     if( sIter.aPhrase[i].pHead ){
108080       *pmSeen |= (u64)1 << i;
108081     }
108082   }
108083
108084   /* Loop through all candidate snippets. Store the best snippet in 
108085   ** *pFragment. Store its associated 'score' in iBestScore.
108086   */
108087   pFragment->iCol = iCol;
108088   while( !fts3SnippetNextCandidate(&sIter) ){
108089     int iPos;
108090     int iScore;
108091     u64 mCover;
108092     u64 mHighlight;
108093     fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
108094     assert( iScore>=0 );
108095     if( iScore>iBestScore ){
108096       pFragment->iPos = iPos;
108097       pFragment->hlmask = mHighlight;
108098       pFragment->covered = mCover;
108099       iBestScore = iScore;
108100     }
108101   }
108102
108103   sqlite3_free(sIter.aPhrase);
108104   *piScore = iBestScore;
108105   return SQLITE_OK;
108106 }
108107
108108
108109 /*
108110 ** Append a string to the string-buffer passed as the first argument.
108111 **
108112 ** If nAppend is negative, then the length of the string zAppend is
108113 ** determined using strlen().
108114 */
108115 static int fts3StringAppend(
108116   StrBuffer *pStr,                /* Buffer to append to */
108117   const char *zAppend,            /* Pointer to data to append to buffer */
108118   int nAppend                     /* Size of zAppend in bytes (or -1) */
108119 ){
108120   if( nAppend<0 ){
108121     nAppend = (int)strlen(zAppend);
108122   }
108123
108124   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
108125   ** to grow the buffer until so that it is big enough to accomadate the
108126   ** appended data.
108127   */
108128   if( pStr->n+nAppend+1>=pStr->nAlloc ){
108129     int nAlloc = pStr->nAlloc+nAppend+100;
108130     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
108131     if( !zNew ){
108132       return SQLITE_NOMEM;
108133     }
108134     pStr->z = zNew;
108135     pStr->nAlloc = nAlloc;
108136   }
108137
108138   /* Append the data to the string buffer. */
108139   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
108140   pStr->n += nAppend;
108141   pStr->z[pStr->n] = '\0';
108142
108143   return SQLITE_OK;
108144 }
108145
108146 /*
108147 ** The fts3BestSnippet() function often selects snippets that end with a
108148 ** query term. That is, the final term of the snippet is always a term
108149 ** that requires highlighting. For example, if 'X' is a highlighted term
108150 ** and '.' is a non-highlighted term, BestSnippet() may select:
108151 **
108152 **     ........X.....X
108153 **
108154 ** This function "shifts" the beginning of the snippet forward in the 
108155 ** document so that there are approximately the same number of 
108156 ** non-highlighted terms to the right of the final highlighted term as there
108157 ** are to the left of the first highlighted term. For example, to this:
108158 **
108159 **     ....X.....X....
108160 **
108161 ** This is done as part of extracting the snippet text, not when selecting
108162 ** the snippet. Snippet selection is done based on doclists only, so there
108163 ** is no way for fts3BestSnippet() to know whether or not the document 
108164 ** actually contains terms that follow the final highlighted term. 
108165 */
108166 int fts3SnippetShift(
108167   Fts3Table *pTab,                /* FTS3 table snippet comes from */
108168   int nSnippet,                   /* Number of tokens desired for snippet */
108169   const char *zDoc,               /* Document text to extract snippet from */
108170   int nDoc,                       /* Size of buffer zDoc in bytes */
108171   int *piPos,                     /* IN/OUT: First token of snippet */
108172   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
108173 ){
108174   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
108175
108176   if( hlmask ){
108177     int nLeft;                    /* Tokens to the left of first highlight */
108178     int nRight;                   /* Tokens to the right of last highlight */
108179     int nDesired;                 /* Ideal number of tokens to shift forward */
108180
108181     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
108182     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
108183     nDesired = (nLeft-nRight)/2;
108184
108185     /* Ideally, the start of the snippet should be pushed forward in the
108186     ** document nDesired tokens. This block checks if there are actually
108187     ** nDesired tokens to the right of the snippet. If so, *piPos and
108188     ** *pHlMask are updated to shift the snippet nDesired tokens to the
108189     ** right. Otherwise, the snippet is shifted by the number of tokens
108190     ** available.
108191     */
108192     if( nDesired>0 ){
108193       int nShift;                 /* Number of tokens to shift snippet by */
108194       int iCurrent = 0;           /* Token counter */
108195       int rc;                     /* Return Code */
108196       sqlite3_tokenizer_module *pMod;
108197       sqlite3_tokenizer_cursor *pC;
108198       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
108199
108200       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
108201       ** or more tokens in zDoc/nDoc.
108202       */
108203       rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
108204       if( rc!=SQLITE_OK ){
108205         return rc;
108206       }
108207       pC->pTokenizer = pTab->pTokenizer;
108208       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
108209         const char *ZDUMMY; int DUMMY1, DUMMY2, DUMMY3;
108210         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
108211       }
108212       pMod->xClose(pC);
108213       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
108214
108215       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
108216       assert( nShift<=nDesired );
108217       if( nShift>0 ){
108218         *piPos += nShift;
108219         *pHlmask = hlmask >> nShift;
108220       }
108221     }
108222   }
108223   return SQLITE_OK;
108224 }
108225
108226 /*
108227 ** Extract the snippet text for fragment pFragment from cursor pCsr and
108228 ** append it to string buffer pOut.
108229 */
108230 static int fts3SnippetText(
108231   Fts3Cursor *pCsr,               /* FTS3 Cursor */
108232   SnippetFragment *pFragment,     /* Snippet to extract */
108233   int iFragment,                  /* Fragment number */
108234   int isLast,                     /* True for final fragment in snippet */
108235   int nSnippet,                   /* Number of tokens in extracted snippet */
108236   const char *zOpen,              /* String inserted before highlighted term */
108237   const char *zClose,             /* String inserted after highlighted term */
108238   const char *zEllipsis,          /* String inserted between snippets */
108239   StrBuffer *pOut                 /* Write output here */
108240 ){
108241   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
108242   int rc;                         /* Return code */
108243   const char *zDoc;               /* Document text to extract snippet from */
108244   int nDoc;                       /* Size of zDoc in bytes */
108245   int iCurrent = 0;               /* Current token number of document */
108246   int iEnd = 0;                   /* Byte offset of end of current token */
108247   int isShiftDone = 0;            /* True after snippet is shifted */
108248   int iPos = pFragment->iPos;     /* First token of snippet */
108249   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
108250   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
108251   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
108252   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
108253   const char *ZDUMMY;             /* Dummy argument used with tokenizer */
108254   int DUMMY1;                     /* Dummy argument used with tokenizer */
108255   
108256   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
108257   if( zDoc==0 ){
108258     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
108259       return SQLITE_NOMEM;
108260     }
108261     return SQLITE_OK;
108262   }
108263   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
108264
108265   /* Open a token cursor on the document. */
108266   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
108267   rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
108268   if( rc!=SQLITE_OK ){
108269     return rc;
108270   }
108271   pC->pTokenizer = pTab->pTokenizer;
108272
108273   while( rc==SQLITE_OK ){
108274     int iBegin;                   /* Offset in zDoc of start of token */
108275     int iFin;                     /* Offset in zDoc of end of token */
108276     int isHighlight;              /* True for highlighted terms */
108277
108278     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
108279     if( rc!=SQLITE_OK ){
108280       if( rc==SQLITE_DONE ){
108281         /* Special case - the last token of the snippet is also the last token
108282         ** of the column. Append any punctuation that occurred between the end
108283         ** of the previous token and the end of the document to the output. 
108284         ** Then break out of the loop. */
108285         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
108286       }
108287       break;
108288     }
108289     if( iCurrent<iPos ){ continue; }
108290
108291     if( !isShiftDone ){
108292       int n = nDoc - iBegin;
108293       rc = fts3SnippetShift(pTab, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask);
108294       isShiftDone = 1;
108295
108296       /* Now that the shift has been done, check if the initial "..." are
108297       ** required. They are required if (a) this is not the first fragment,
108298       ** or (b) this fragment does not begin at position 0 of its column. 
108299       */
108300       if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
108301         rc = fts3StringAppend(pOut, zEllipsis, -1);
108302       }
108303       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
108304     }
108305
108306     if( iCurrent>=(iPos+nSnippet) ){
108307       if( isLast ){
108308         rc = fts3StringAppend(pOut, zEllipsis, -1);
108309       }
108310       break;
108311     }
108312
108313     /* Set isHighlight to true if this term should be highlighted. */
108314     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
108315
108316     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
108317     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
108318     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
108319     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
108320
108321     iEnd = iFin;
108322   }
108323
108324   pMod->xClose(pC);
108325   return rc;
108326 }
108327
108328
108329 /*
108330 ** This function is used to count the entries in a column-list (a 
108331 ** delta-encoded list of term offsets within a single column of a single 
108332 ** row). When this function is called, *ppCollist should point to the
108333 ** beginning of the first varint in the column-list (the varint that
108334 ** contains the position of the first matching term in the column data).
108335 ** Before returning, *ppCollist is set to point to the first byte after
108336 ** the last varint in the column-list (either the 0x00 signifying the end
108337 ** of the position-list, or the 0x01 that precedes the column number of
108338 ** the next column in the position-list).
108339 **
108340 ** The number of elements in the column-list is returned.
108341 */
108342 static int fts3ColumnlistCount(char **ppCollist){
108343   char *pEnd = *ppCollist;
108344   char c = 0;
108345   int nEntry = 0;
108346
108347   /* A column-list is terminated by either a 0x01 or 0x00. */
108348   while( 0xFE & (*pEnd | c) ){
108349     c = *pEnd++ & 0x80;
108350     if( !c ) nEntry++;
108351   }
108352
108353   *ppCollist = pEnd;
108354   return nEntry;
108355 }
108356
108357 static void fts3LoadColumnlistCounts(char **pp, u32 *aOut, int isGlobal){
108358   char *pCsr = *pp;
108359   while( *pCsr ){
108360     int nHit;
108361     sqlite3_int64 iCol = 0;
108362     if( *pCsr==0x01 ){
108363       pCsr++;
108364       pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
108365     }
108366     nHit = fts3ColumnlistCount(&pCsr);
108367     assert( nHit>0 );
108368     if( isGlobal ){
108369       aOut[iCol*3+1]++;
108370     }
108371     aOut[iCol*3] += nHit;
108372   }
108373   pCsr++;
108374   *pp = pCsr;
108375 }
108376
108377 /*
108378 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
108379 ** for a single query. The "global" stats are those elements of the matchinfo
108380 ** array that are constant for all rows returned by the current query.
108381 */
108382 static int fts3ExprGlobalMatchinfoCb(
108383   Fts3Expr *pExpr,                /* Phrase expression node */
108384   int iPhrase,                    /* Phrase number (numbered from zero) */
108385   void *pCtx                      /* Pointer to MatchInfo structure */
108386 ){
108387   MatchInfo *p = (MatchInfo *)pCtx;
108388   char *pCsr;
108389   char *pEnd;
108390   const int iStart = 2 + (iPhrase * p->nCol * 3) + 1;
108391
108392   assert( pExpr->isLoaded );
108393
108394   /* Fill in the global hit count matrix row for this phrase. */
108395   pCsr = pExpr->aDoclist;
108396   pEnd = &pExpr->aDoclist[pExpr->nDoclist];
108397   while( pCsr<pEnd ){
108398     while( *pCsr++ & 0x80 );      /* Skip past docid. */
108399     fts3LoadColumnlistCounts(&pCsr, &p->aMatchinfo[iStart], 1);
108400   }
108401
108402   return SQLITE_OK;
108403 }
108404
108405 /*
108406 ** fts3ExprIterate() callback used to collect the "local" matchinfo stats
108407 ** for a single query. The "local" stats are those elements of the matchinfo
108408 ** array that are different for each row returned by the query.
108409 */
108410 static int fts3ExprLocalMatchinfoCb(
108411   Fts3Expr *pExpr,                /* Phrase expression node */
108412   int iPhrase,                    /* Phrase number */
108413   void *pCtx                      /* Pointer to MatchInfo structure */
108414 ){
108415   MatchInfo *p = (MatchInfo *)pCtx;
108416
108417   if( pExpr->aDoclist ){
108418     char *pCsr;
108419     int iStart = 2 + (iPhrase * p->nCol * 3);
108420     int i;
108421
108422     for(i=0; i<p->nCol; i++) p->aMatchinfo[iStart+i*3] = 0;
108423
108424     pCsr = sqlite3Fts3FindPositions(pExpr, p->pCursor->iPrevId, -1);
108425     if( pCsr ){
108426       fts3LoadColumnlistCounts(&pCsr, &p->aMatchinfo[iStart], 0);
108427     }
108428   }
108429
108430   return SQLITE_OK;
108431 }
108432
108433 /*
108434 ** Populate pCsr->aMatchinfo[] with data for the current row. The 
108435 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
108436 */
108437 static int fts3GetMatchinfo(Fts3Cursor *pCsr){
108438   MatchInfo sInfo;
108439   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
108440   int rc = SQLITE_OK;
108441
108442   sInfo.pCursor = pCsr;
108443   sInfo.nCol = pTab->nColumn;
108444
108445   if( pCsr->aMatchinfo==0 ){
108446     /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
108447     ** matchinfo function has been called for this query. In this case 
108448     ** allocate the array used to accumulate the matchinfo data and
108449     ** initialize those elements that are constant for every row.
108450     */
108451     int nPhrase;                  /* Number of phrases */
108452     int nMatchinfo;               /* Number of u32 elements in match-info */
108453
108454     /* Load doclists for each phrase in the query. */
108455     rc = fts3ExprLoadDoclists(pCsr, &nPhrase, 0);
108456     if( rc!=SQLITE_OK ){
108457       return rc;
108458     }
108459     nMatchinfo = 2 + 3*sInfo.nCol*nPhrase;
108460     if( pTab->bHasDocsize ){
108461       nMatchinfo += 1 + 2*pTab->nColumn;
108462     }
108463
108464     sInfo.aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo);
108465     if( !sInfo.aMatchinfo ){ 
108466       return SQLITE_NOMEM;
108467     }
108468     memset(sInfo.aMatchinfo, 0, sizeof(u32)*nMatchinfo);
108469
108470
108471     /* First element of match-info is the number of phrases in the query */
108472     sInfo.aMatchinfo[0] = nPhrase;
108473     sInfo.aMatchinfo[1] = sInfo.nCol;
108474     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprGlobalMatchinfoCb,(void*)&sInfo);
108475     if( pTab->bHasDocsize ){
108476       int ofst = 2 + 3*sInfo.aMatchinfo[0]*sInfo.aMatchinfo[1];
108477       rc = sqlite3Fts3MatchinfoDocsizeGlobal(pCsr, &sInfo.aMatchinfo[ofst]);
108478     }
108479     pCsr->aMatchinfo = sInfo.aMatchinfo;
108480     pCsr->isMatchinfoNeeded = 1;
108481   }
108482
108483   sInfo.aMatchinfo = pCsr->aMatchinfo;
108484   if( rc==SQLITE_OK && pCsr->isMatchinfoNeeded ){
108485     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprLocalMatchinfoCb, (void*)&sInfo);
108486     if( pTab->bHasDocsize ){
108487       int ofst = 2 + 3*sInfo.aMatchinfo[0]*sInfo.aMatchinfo[1];
108488       rc = sqlite3Fts3MatchinfoDocsizeLocal(pCsr, &sInfo.aMatchinfo[ofst]);
108489     }
108490     pCsr->isMatchinfoNeeded = 0;
108491   }
108492
108493   return SQLITE_OK;
108494 }
108495
108496 /*
108497 ** Implementation of snippet() function.
108498 */
108499 SQLITE_PRIVATE void sqlite3Fts3Snippet(
108500   sqlite3_context *pCtx,          /* SQLite function call context */
108501   Fts3Cursor *pCsr,               /* Cursor object */
108502   const char *zStart,             /* Snippet start text - "<b>" */
108503   const char *zEnd,               /* Snippet end text - "</b>" */
108504   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
108505   int iCol,                       /* Extract snippet from this column */
108506   int nToken                      /* Approximate number of tokens in snippet */
108507 ){
108508   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
108509   int rc = SQLITE_OK;
108510   int i;
108511   StrBuffer res = {0, 0, 0};
108512
108513   /* The returned text includes up to four fragments of text extracted from
108514   ** the data in the current row. The first iteration of the for(...) loop
108515   ** below attempts to locate a single fragment of text nToken tokens in 
108516   ** size that contains at least one instance of all phrases in the query
108517   ** expression that appear in the current row. If such a fragment of text
108518   ** cannot be found, the second iteration of the loop attempts to locate
108519   ** a pair of fragments, and so on.
108520   */
108521   int nSnippet = 0;               /* Number of fragments in this snippet */
108522   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
108523   int nFToken = -1;               /* Number of tokens in each fragment */
108524
108525   if( !pCsr->pExpr ){
108526     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
108527     return;
108528   }
108529
108530   for(nSnippet=1; 1; nSnippet++){
108531
108532     int iSnip;                    /* Loop counter 0..nSnippet-1 */
108533     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
108534     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
108535
108536     if( nToken>=0 ){
108537       nFToken = (nToken+nSnippet-1) / nSnippet;
108538     }else{
108539       nFToken = -1 * nToken;
108540     }
108541
108542     for(iSnip=0; iSnip<nSnippet; iSnip++){
108543       int iBestScore = -1;        /* Best score of columns checked so far */
108544       int iRead;                  /* Used to iterate through columns */
108545       SnippetFragment *pFragment = &aSnippet[iSnip];
108546
108547       memset(pFragment, 0, sizeof(*pFragment));
108548
108549       /* Loop through all columns of the table being considered for snippets.
108550       ** If the iCol argument to this function was negative, this means all
108551       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
108552       */
108553       for(iRead=0; iRead<pTab->nColumn; iRead++){
108554         SnippetFragment sF;
108555         int iS;
108556         if( iCol>=0 && iRead!=iCol ) continue;
108557
108558         /* Find the best snippet of nFToken tokens in column iRead. */
108559         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
108560         if( rc!=SQLITE_OK ){
108561           goto snippet_out;
108562         }
108563         if( iS>iBestScore ){
108564           *pFragment = sF;
108565           iBestScore = iS;
108566         }
108567       }
108568
108569       mCovered |= pFragment->covered;
108570     }
108571
108572     /* If all query phrases seen by fts3BestSnippet() are present in at least
108573     ** one of the nSnippet snippet fragments, break out of the loop.
108574     */
108575     assert( (mCovered&mSeen)==mCovered );
108576     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
108577   }
108578
108579   assert( nFToken>0 );
108580
108581   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
108582     rc = fts3SnippetText(pCsr, &aSnippet[i], 
108583         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
108584     );
108585   }
108586
108587  snippet_out:
108588   if( rc!=SQLITE_OK ){
108589     sqlite3_result_error_code(pCtx, rc);
108590     sqlite3_free(res.z);
108591   }else{
108592     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
108593   }
108594 }
108595
108596
108597 typedef struct TermOffset TermOffset;
108598 typedef struct TermOffsetCtx TermOffsetCtx;
108599
108600 struct TermOffset {
108601   char *pList;                    /* Position-list */
108602   int iPos;                       /* Position just read from pList */
108603   int iOff;                       /* Offset of this term from read positions */
108604 };
108605
108606 struct TermOffsetCtx {
108607   int iCol;                       /* Column of table to populate aTerm for */
108608   int iTerm;
108609   sqlite3_int64 iDocid;
108610   TermOffset *aTerm;
108611 };
108612
108613 /*
108614 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
108615 */
108616 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
108617   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
108618   int nTerm;                      /* Number of tokens in phrase */
108619   int iTerm;                      /* For looping through nTerm phrase terms */
108620   char *pList;                    /* Pointer to position list for phrase */
108621   int iPos = 0;                   /* First position in position-list */
108622
108623   UNUSED_PARAMETER(iPhrase);
108624   pList = sqlite3Fts3FindPositions(pExpr, p->iDocid, p->iCol);
108625   nTerm = pExpr->pPhrase->nToken;
108626   if( pList ){
108627     fts3GetDeltaPosition(&pList, &iPos);
108628     assert( iPos>=0 );
108629   }
108630
108631   for(iTerm=0; iTerm<nTerm; iTerm++){
108632     TermOffset *pT = &p->aTerm[p->iTerm++];
108633     pT->iOff = nTerm-iTerm-1;
108634     pT->pList = pList;
108635     pT->iPos = iPos;
108636   }
108637
108638   return SQLITE_OK;
108639 }
108640
108641 /*
108642 ** Implementation of offsets() function.
108643 */
108644 SQLITE_PRIVATE void sqlite3Fts3Offsets(
108645   sqlite3_context *pCtx,          /* SQLite function call context */
108646   Fts3Cursor *pCsr                /* Cursor object */
108647 ){
108648   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
108649   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
108650   const char *ZDUMMY;             /* Dummy argument used with xNext() */
108651   int NDUMMY;                     /* Dummy argument used with xNext() */
108652   int rc;                         /* Return Code */
108653   int nToken;                     /* Number of tokens in query */
108654   int iCol;                       /* Column currently being processed */
108655   StrBuffer res = {0, 0, 0};      /* Result string */
108656   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
108657
108658   if( !pCsr->pExpr ){
108659     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
108660     return;
108661   }
108662
108663   memset(&sCtx, 0, sizeof(sCtx));
108664   assert( pCsr->isRequireSeek==0 );
108665
108666   /* Count the number of terms in the query */
108667   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
108668   if( rc!=SQLITE_OK ) goto offsets_out;
108669
108670   /* Allocate the array of TermOffset iterators. */
108671   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
108672   if( 0==sCtx.aTerm ){
108673     rc = SQLITE_NOMEM;
108674     goto offsets_out;
108675   }
108676   sCtx.iDocid = pCsr->iPrevId;
108677
108678   /* Loop through the table columns, appending offset information to 
108679   ** string-buffer res for each column.
108680   */
108681   for(iCol=0; iCol<pTab->nColumn; iCol++){
108682     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
108683     int iStart;
108684     int iEnd;
108685     int iCurrent;
108686     const char *zDoc;
108687     int nDoc;
108688
108689     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is 
108690     ** no way that this operation can fail, so the return code from
108691     ** fts3ExprIterate() can be discarded.
108692     */
108693     sCtx.iCol = iCol;
108694     sCtx.iTerm = 0;
108695     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
108696
108697     /* Retreive the text stored in column iCol. If an SQL NULL is stored 
108698     ** in column iCol, jump immediately to the next iteration of the loop.
108699     ** If an OOM occurs while retrieving the data (this can happen if SQLite
108700     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM 
108701     ** to the caller. 
108702     */
108703     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
108704     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
108705     if( zDoc==0 ){
108706       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
108707         continue;
108708       }
108709       rc = SQLITE_NOMEM;
108710       goto offsets_out;
108711     }
108712
108713     /* Initialize a tokenizer iterator to iterate through column iCol. */
108714     rc = pMod->xOpen(pTab->pTokenizer, zDoc, nDoc, &pC);
108715     if( rc!=SQLITE_OK ) goto offsets_out;
108716     pC->pTokenizer = pTab->pTokenizer;
108717
108718     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
108719     while( rc==SQLITE_OK ){
108720       int i;                      /* Used to loop through terms */
108721       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
108722       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
108723
108724       for(i=0; i<nToken; i++){
108725         TermOffset *pT = &sCtx.aTerm[i];
108726         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
108727           iMinPos = pT->iPos-pT->iOff;
108728           pTerm = pT;
108729         }
108730       }
108731
108732       if( !pTerm ){
108733         /* All offsets for this column have been gathered. */
108734         break;
108735       }else{
108736         assert( iCurrent<=iMinPos );
108737         if( 0==(0xFE&*pTerm->pList) ){
108738           pTerm->pList = 0;
108739         }else{
108740           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
108741         }
108742         while( rc==SQLITE_OK && iCurrent<iMinPos ){
108743           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
108744         }
108745         if( rc==SQLITE_OK ){
108746           char aBuffer[64];
108747           sqlite3_snprintf(sizeof(aBuffer), aBuffer, 
108748               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
108749           );
108750           rc = fts3StringAppend(&res, aBuffer, -1);
108751         }else if( rc==SQLITE_DONE ){
108752           rc = SQLITE_CORRUPT;
108753         }
108754       }
108755     }
108756     if( rc==SQLITE_DONE ){
108757       rc = SQLITE_OK;
108758     }
108759
108760     pMod->xClose(pC);
108761     if( rc!=SQLITE_OK ) goto offsets_out;
108762   }
108763
108764  offsets_out:
108765   sqlite3_free(sCtx.aTerm);
108766   assert( rc!=SQLITE_DONE );
108767   if( rc!=SQLITE_OK ){
108768     sqlite3_result_error_code(pCtx,  rc);
108769     sqlite3_free(res.z);
108770   }else{
108771     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
108772   }
108773   return;
108774 }
108775
108776 /*
108777 ** Implementation of matchinfo() function.
108778 */
108779 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *pContext, Fts3Cursor *pCsr){
108780   int rc;
108781   if( !pCsr->pExpr ){
108782     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
108783     return;
108784   }
108785   rc = fts3GetMatchinfo(pCsr);
108786   if( rc!=SQLITE_OK ){
108787     sqlite3_result_error_code(pContext, rc);
108788   }else{
108789     Fts3Table *pTab = (Fts3Table*)pCsr->base.pVtab;
108790     int n = sizeof(u32)*(2+pCsr->aMatchinfo[0]*pCsr->aMatchinfo[1]*3);
108791     if( pTab->bHasDocsize ){
108792       n += sizeof(u32)*(1 + 2*pTab->nColumn);
108793     }
108794     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
108795   }
108796 }
108797
108798 #endif
108799
108800 /************** End of fts3_snippet.c ****************************************/
108801 /************** Begin file rtree.c *******************************************/
108802 /*
108803 ** 2001 September 15
108804 **
108805 ** The author disclaims copyright to this source code.  In place of
108806 ** a legal notice, here is a blessing:
108807 **
108808 **    May you do good and not evil.
108809 **    May you find forgiveness for yourself and forgive others.
108810 **    May you share freely, never taking more than you give.
108811 **
108812 *************************************************************************
108813 ** This file contains code for implementations of the r-tree and r*-tree
108814 ** algorithms packaged as an SQLite virtual table module.
108815 */
108816
108817 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
108818
108819 /*
108820 ** This file contains an implementation of a couple of different variants
108821 ** of the r-tree algorithm. See the README file for further details. The 
108822 ** same data-structure is used for all, but the algorithms for insert and
108823 ** delete operations vary. The variants used are selected at compile time 
108824 ** by defining the following symbols:
108825 */
108826
108827 /* Either, both or none of the following may be set to activate 
108828 ** r*tree variant algorithms.
108829 */
108830 #define VARIANT_RSTARTREE_CHOOSESUBTREE 0
108831 #define VARIANT_RSTARTREE_REINSERT      1
108832
108833 /* 
108834 ** Exactly one of the following must be set to 1.
108835 */
108836 #define VARIANT_GUTTMAN_QUADRATIC_SPLIT 0
108837 #define VARIANT_GUTTMAN_LINEAR_SPLIT    0
108838 #define VARIANT_RSTARTREE_SPLIT         1
108839
108840 #define VARIANT_GUTTMAN_SPLIT \
108841         (VARIANT_GUTTMAN_LINEAR_SPLIT||VARIANT_GUTTMAN_QUADRATIC_SPLIT)
108842
108843 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
108844   #define PickNext QuadraticPickNext
108845   #define PickSeeds QuadraticPickSeeds
108846   #define AssignCells splitNodeGuttman
108847 #endif
108848 #if VARIANT_GUTTMAN_LINEAR_SPLIT
108849   #define PickNext LinearPickNext
108850   #define PickSeeds LinearPickSeeds
108851   #define AssignCells splitNodeGuttman
108852 #endif
108853 #if VARIANT_RSTARTREE_SPLIT
108854   #define AssignCells splitNodeStartree
108855 #endif
108856
108857
108858 #ifndef SQLITE_CORE
108859   SQLITE_EXTENSION_INIT1
108860 #else
108861 #endif
108862
108863
108864 #ifndef SQLITE_AMALGAMATION
108865 typedef sqlite3_int64 i64;
108866 typedef unsigned char u8;
108867 typedef unsigned int u32;
108868 #endif
108869
108870 typedef struct Rtree Rtree;
108871 typedef struct RtreeCursor RtreeCursor;
108872 typedef struct RtreeNode RtreeNode;
108873 typedef struct RtreeCell RtreeCell;
108874 typedef struct RtreeConstraint RtreeConstraint;
108875 typedef union RtreeCoord RtreeCoord;
108876
108877 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
108878 #define RTREE_MAX_DIMENSIONS 5
108879
108880 /* Size of hash table Rtree.aHash. This hash table is not expected to
108881 ** ever contain very many entries, so a fixed number of buckets is 
108882 ** used.
108883 */
108884 #define HASHSIZE 128
108885
108886 /* 
108887 ** An rtree virtual-table object.
108888 */
108889 struct Rtree {
108890   sqlite3_vtab base;
108891   sqlite3 *db;                /* Host database connection */
108892   int iNodeSize;              /* Size in bytes of each node in the node table */
108893   int nDim;                   /* Number of dimensions */
108894   int nBytesPerCell;          /* Bytes consumed per cell */
108895   int iDepth;                 /* Current depth of the r-tree structure */
108896   char *zDb;                  /* Name of database containing r-tree table */
108897   char *zName;                /* Name of r-tree table */ 
108898   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
108899   int nBusy;                  /* Current number of users of this structure */
108900
108901   /* List of nodes removed during a CondenseTree operation. List is
108902   ** linked together via the pointer normally used for hash chains -
108903   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
108904   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
108905   */
108906   RtreeNode *pDeleted;
108907   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
108908
108909   /* Statements to read/write/delete a record from xxx_node */
108910   sqlite3_stmt *pReadNode;
108911   sqlite3_stmt *pWriteNode;
108912   sqlite3_stmt *pDeleteNode;
108913
108914   /* Statements to read/write/delete a record from xxx_rowid */
108915   sqlite3_stmt *pReadRowid;
108916   sqlite3_stmt *pWriteRowid;
108917   sqlite3_stmt *pDeleteRowid;
108918
108919   /* Statements to read/write/delete a record from xxx_parent */
108920   sqlite3_stmt *pReadParent;
108921   sqlite3_stmt *pWriteParent;
108922   sqlite3_stmt *pDeleteParent;
108923
108924   int eCoordType;
108925 };
108926
108927 /* Possible values for eCoordType: */
108928 #define RTREE_COORD_REAL32 0
108929 #define RTREE_COORD_INT32  1
108930
108931 /*
108932 ** The minimum number of cells allowed for a node is a third of the 
108933 ** maximum. In Gutman's notation:
108934 **
108935 **     m = M/3
108936 **
108937 ** If an R*-tree "Reinsert" operation is required, the same number of
108938 ** cells are removed from the overfull node and reinserted into the tree.
108939 */
108940 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
108941 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
108942 #define RTREE_MAXCELLS 51
108943
108944 /* 
108945 ** An rtree cursor object.
108946 */
108947 struct RtreeCursor {
108948   sqlite3_vtab_cursor base;
108949   RtreeNode *pNode;                 /* Node cursor is currently pointing at */
108950   int iCell;                        /* Index of current cell in pNode */
108951   int iStrategy;                    /* Copy of idxNum search parameter */
108952   int nConstraint;                  /* Number of entries in aConstraint */
108953   RtreeConstraint *aConstraint;     /* Search constraints. */
108954 };
108955
108956 union RtreeCoord {
108957   float f;
108958   int i;
108959 };
108960
108961 /*
108962 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
108963 ** formatted as a double. This macro assumes that local variable pRtree points
108964 ** to the Rtree structure associated with the RtreeCoord.
108965 */
108966 #define DCOORD(coord) (                           \
108967   (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
108968     ((double)coord.f) :                           \
108969     ((double)coord.i)                             \
108970 )
108971
108972 /*
108973 ** A search constraint.
108974 */
108975 struct RtreeConstraint {
108976   int iCoord;                       /* Index of constrained coordinate */
108977   int op;                           /* Constraining operation */
108978   double rValue;                    /* Constraint value. */
108979 };
108980
108981 /* Possible values for RtreeConstraint.op */
108982 #define RTREE_EQ 0x41
108983 #define RTREE_LE 0x42
108984 #define RTREE_LT 0x43
108985 #define RTREE_GE 0x44
108986 #define RTREE_GT 0x45
108987
108988 /* 
108989 ** An rtree structure node.
108990 **
108991 ** Data format (RtreeNode.zData):
108992 **
108993 **   1. If the node is the root node (node 1), then the first 2 bytes
108994 **      of the node contain the tree depth as a big-endian integer.
108995 **      For non-root nodes, the first 2 bytes are left unused.
108996 **
108997 **   2. The next 2 bytes contain the number of entries currently 
108998 **      stored in the node.
108999 **
109000 **   3. The remainder of the node contains the node entries. Each entry
109001 **      consists of a single 8-byte integer followed by an even number
109002 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
109003 **      of a record. For internal nodes it is the node number of a
109004 **      child page.
109005 */
109006 struct RtreeNode {
109007   RtreeNode *pParent;               /* Parent node */
109008   i64 iNode;
109009   int nRef;
109010   int isDirty;
109011   u8 *zData;
109012   RtreeNode *pNext;                 /* Next node in this hash chain */
109013 };
109014 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
109015
109016 /* 
109017 ** Structure to store a deserialized rtree record.
109018 */
109019 struct RtreeCell {
109020   i64 iRowid;
109021   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];
109022 };
109023
109024 #ifndef MAX
109025 # define MAX(x,y) ((x) < (y) ? (y) : (x))
109026 #endif
109027 #ifndef MIN
109028 # define MIN(x,y) ((x) > (y) ? (y) : (x))
109029 #endif
109030
109031 /*
109032 ** Functions to deserialize a 16 bit integer, 32 bit real number and
109033 ** 64 bit integer. The deserialized value is returned.
109034 */
109035 static int readInt16(u8 *p){
109036   return (p[0]<<8) + p[1];
109037 }
109038 static void readCoord(u8 *p, RtreeCoord *pCoord){
109039   u32 i = (
109040     (((u32)p[0]) << 24) + 
109041     (((u32)p[1]) << 16) + 
109042     (((u32)p[2]) <<  8) + 
109043     (((u32)p[3]) <<  0)
109044   );
109045   *(u32 *)pCoord = i;
109046 }
109047 static i64 readInt64(u8 *p){
109048   return (
109049     (((i64)p[0]) << 56) + 
109050     (((i64)p[1]) << 48) + 
109051     (((i64)p[2]) << 40) + 
109052     (((i64)p[3]) << 32) + 
109053     (((i64)p[4]) << 24) + 
109054     (((i64)p[5]) << 16) + 
109055     (((i64)p[6]) <<  8) + 
109056     (((i64)p[7]) <<  0)
109057   );
109058 }
109059
109060 /*
109061 ** Functions to serialize a 16 bit integer, 32 bit real number and
109062 ** 64 bit integer. The value returned is the number of bytes written
109063 ** to the argument buffer (always 2, 4 and 8 respectively).
109064 */
109065 static int writeInt16(u8 *p, int i){
109066   p[0] = (i>> 8)&0xFF;
109067   p[1] = (i>> 0)&0xFF;
109068   return 2;
109069 }
109070 static int writeCoord(u8 *p, RtreeCoord *pCoord){
109071   u32 i;
109072   assert( sizeof(RtreeCoord)==4 );
109073   assert( sizeof(u32)==4 );
109074   i = *(u32 *)pCoord;
109075   p[0] = (i>>24)&0xFF;
109076   p[1] = (i>>16)&0xFF;
109077   p[2] = (i>> 8)&0xFF;
109078   p[3] = (i>> 0)&0xFF;
109079   return 4;
109080 }
109081 static int writeInt64(u8 *p, i64 i){
109082   p[0] = (i>>56)&0xFF;
109083   p[1] = (i>>48)&0xFF;
109084   p[2] = (i>>40)&0xFF;
109085   p[3] = (i>>32)&0xFF;
109086   p[4] = (i>>24)&0xFF;
109087   p[5] = (i>>16)&0xFF;
109088   p[6] = (i>> 8)&0xFF;
109089   p[7] = (i>> 0)&0xFF;
109090   return 8;
109091 }
109092
109093 /*
109094 ** Increment the reference count of node p.
109095 */
109096 static void nodeReference(RtreeNode *p){
109097   if( p ){
109098     p->nRef++;
109099   }
109100 }
109101
109102 /*
109103 ** Clear the content of node p (set all bytes to 0x00).
109104 */
109105 static void nodeZero(Rtree *pRtree, RtreeNode *p){
109106   if( p ){
109107     memset(&p->zData[2], 0, pRtree->iNodeSize-2);
109108     p->isDirty = 1;
109109   }
109110 }
109111
109112 /*
109113 ** Given a node number iNode, return the corresponding key to use
109114 ** in the Rtree.aHash table.
109115 */
109116 static int nodeHash(i64 iNode){
109117   return (
109118     (iNode>>56) ^ (iNode>>48) ^ (iNode>>40) ^ (iNode>>32) ^ 
109119     (iNode>>24) ^ (iNode>>16) ^ (iNode>> 8) ^ (iNode>> 0)
109120   ) % HASHSIZE;
109121 }
109122
109123 /*
109124 ** Search the node hash table for node iNode. If found, return a pointer
109125 ** to it. Otherwise, return 0.
109126 */
109127 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
109128   RtreeNode *p;
109129   assert( iNode!=0 );
109130   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
109131   return p;
109132 }
109133
109134 /*
109135 ** Add node pNode to the node hash table.
109136 */
109137 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
109138   if( pNode ){
109139     int iHash;
109140     assert( pNode->pNext==0 );
109141     iHash = nodeHash(pNode->iNode);
109142     pNode->pNext = pRtree->aHash[iHash];
109143     pRtree->aHash[iHash] = pNode;
109144   }
109145 }
109146
109147 /*
109148 ** Remove node pNode from the node hash table.
109149 */
109150 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
109151   RtreeNode **pp;
109152   if( pNode->iNode!=0 ){
109153     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
109154     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
109155     *pp = pNode->pNext;
109156     pNode->pNext = 0;
109157   }
109158 }
109159
109160 /*
109161 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
109162 ** indicating that node has not yet been assigned a node number. It is
109163 ** assigned a node number when nodeWrite() is called to write the
109164 ** node contents out to the database.
109165 */
109166 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent, int zero){
109167   RtreeNode *pNode;
109168   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
109169   if( pNode ){
109170     memset(pNode, 0, sizeof(RtreeNode) + (zero?pRtree->iNodeSize:0));
109171     pNode->zData = (u8 *)&pNode[1];
109172     pNode->nRef = 1;
109173     pNode->pParent = pParent;
109174     pNode->isDirty = 1;
109175     nodeReference(pParent);
109176   }
109177   return pNode;
109178 }
109179
109180 /*
109181 ** Obtain a reference to an r-tree node.
109182 */
109183 static int
109184 nodeAcquire(
109185   Rtree *pRtree,             /* R-tree structure */
109186   i64 iNode,                 /* Node number to load */
109187   RtreeNode *pParent,        /* Either the parent node or NULL */
109188   RtreeNode **ppNode         /* OUT: Acquired node */
109189 ){
109190   int rc;
109191   RtreeNode *pNode;
109192
109193   /* Check if the requested node is already in the hash table. If so,
109194   ** increase its reference count and return it.
109195   */
109196   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
109197     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
109198     if( pParent && !pNode->pParent ){
109199       nodeReference(pParent);
109200       pNode->pParent = pParent;
109201     }
109202     pNode->nRef++;
109203     *ppNode = pNode;
109204     return SQLITE_OK;
109205   }
109206
109207   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
109208   if( !pNode ){
109209     *ppNode = 0;
109210     return SQLITE_NOMEM;
109211   }
109212   pNode->pParent = pParent;
109213   pNode->zData = (u8 *)&pNode[1];
109214   pNode->nRef = 1;
109215   pNode->iNode = iNode;
109216   pNode->isDirty = 0;
109217   pNode->pNext = 0;
109218
109219   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
109220   rc = sqlite3_step(pRtree->pReadNode);
109221   if( rc==SQLITE_ROW ){
109222     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
109223     assert( sqlite3_column_bytes(pRtree->pReadNode, 0)==pRtree->iNodeSize );
109224     memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
109225     nodeReference(pParent);
109226   }else{
109227     sqlite3_free(pNode);
109228     pNode = 0;
109229   }
109230
109231   *ppNode = pNode;
109232   rc = sqlite3_reset(pRtree->pReadNode);
109233
109234   if( rc==SQLITE_OK && iNode==1 ){
109235     pRtree->iDepth = readInt16(pNode->zData);
109236   }
109237
109238   assert( (rc==SQLITE_OK && pNode) || (pNode==0 && rc!=SQLITE_OK) );
109239   nodeHashInsert(pRtree, pNode);
109240
109241   return rc;
109242 }
109243
109244 /*
109245 ** Overwrite cell iCell of node pNode with the contents of pCell.
109246 */
109247 static void nodeOverwriteCell(
109248   Rtree *pRtree, 
109249   RtreeNode *pNode,  
109250   RtreeCell *pCell, 
109251   int iCell
109252 ){
109253   int ii;
109254   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
109255   p += writeInt64(p, pCell->iRowid);
109256   for(ii=0; ii<(pRtree->nDim*2); ii++){
109257     p += writeCoord(p, &pCell->aCoord[ii]);
109258   }
109259   pNode->isDirty = 1;
109260 }
109261
109262 /*
109263 ** Remove cell the cell with index iCell from node pNode.
109264 */
109265 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
109266   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
109267   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
109268   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
109269   memmove(pDst, pSrc, nByte);
109270   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
109271   pNode->isDirty = 1;
109272 }
109273
109274 /*
109275 ** Insert the contents of cell pCell into node pNode. If the insert
109276 ** is successful, return SQLITE_OK.
109277 **
109278 ** If there is not enough free space in pNode, return SQLITE_FULL.
109279 */
109280 static int
109281 nodeInsertCell(
109282   Rtree *pRtree, 
109283   RtreeNode *pNode, 
109284   RtreeCell *pCell 
109285 ){
109286   int nCell;                    /* Current number of cells in pNode */
109287   int nMaxCell;                 /* Maximum number of cells for pNode */
109288
109289   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
109290   nCell = NCELL(pNode);
109291
109292   assert(nCell<=nMaxCell);
109293
109294   if( nCell<nMaxCell ){
109295     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
109296     writeInt16(&pNode->zData[2], nCell+1);
109297     pNode->isDirty = 1;
109298   }
109299
109300   return (nCell==nMaxCell);
109301 }
109302
109303 /*
109304 ** If the node is dirty, write it out to the database.
109305 */
109306 static int
109307 nodeWrite(Rtree *pRtree, RtreeNode *pNode){
109308   int rc = SQLITE_OK;
109309   if( pNode->isDirty ){
109310     sqlite3_stmt *p = pRtree->pWriteNode;
109311     if( pNode->iNode ){
109312       sqlite3_bind_int64(p, 1, pNode->iNode);
109313     }else{
109314       sqlite3_bind_null(p, 1);
109315     }
109316     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
109317     sqlite3_step(p);
109318     pNode->isDirty = 0;
109319     rc = sqlite3_reset(p);
109320     if( pNode->iNode==0 && rc==SQLITE_OK ){
109321       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
109322       nodeHashInsert(pRtree, pNode);
109323     }
109324   }
109325   return rc;
109326 }
109327
109328 /*
109329 ** Release a reference to a node. If the node is dirty and the reference
109330 ** count drops to zero, the node data is written to the database.
109331 */
109332 static int
109333 nodeRelease(Rtree *pRtree, RtreeNode *pNode){
109334   int rc = SQLITE_OK;
109335   if( pNode ){
109336     assert( pNode->nRef>0 );
109337     pNode->nRef--;
109338     if( pNode->nRef==0 ){
109339       if( pNode->iNode==1 ){
109340         pRtree->iDepth = -1;
109341       }
109342       if( pNode->pParent ){
109343         rc = nodeRelease(pRtree, pNode->pParent);
109344       }
109345       if( rc==SQLITE_OK ){
109346         rc = nodeWrite(pRtree, pNode);
109347       }
109348       nodeHashDelete(pRtree, pNode);
109349       sqlite3_free(pNode);
109350     }
109351   }
109352   return rc;
109353 }
109354
109355 /*
109356 ** Return the 64-bit integer value associated with cell iCell of
109357 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
109358 ** an internal node, then the 64-bit integer is a child page number.
109359 */
109360 static i64 nodeGetRowid(
109361   Rtree *pRtree, 
109362   RtreeNode *pNode, 
109363   int iCell
109364 ){
109365   assert( iCell<NCELL(pNode) );
109366   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
109367 }
109368
109369 /*
109370 ** Return coordinate iCoord from cell iCell in node pNode.
109371 */
109372 static void nodeGetCoord(
109373   Rtree *pRtree, 
109374   RtreeNode *pNode, 
109375   int iCell,
109376   int iCoord,
109377   RtreeCoord *pCoord           /* Space to write result to */
109378 ){
109379   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
109380 }
109381
109382 /*
109383 ** Deserialize cell iCell of node pNode. Populate the structure pointed
109384 ** to by pCell with the results.
109385 */
109386 static void nodeGetCell(
109387   Rtree *pRtree, 
109388   RtreeNode *pNode, 
109389   int iCell,
109390   RtreeCell *pCell
109391 ){
109392   int ii;
109393   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
109394   for(ii=0; ii<pRtree->nDim*2; ii++){
109395     nodeGetCoord(pRtree, pNode, iCell, ii, &pCell->aCoord[ii]);
109396   }
109397 }
109398
109399
109400 /* Forward declaration for the function that does the work of
109401 ** the virtual table module xCreate() and xConnect() methods.
109402 */
109403 static int rtreeInit(
109404   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
109405 );
109406
109407 /* 
109408 ** Rtree virtual table module xCreate method.
109409 */
109410 static int rtreeCreate(
109411   sqlite3 *db,
109412   void *pAux,
109413   int argc, const char *const*argv,
109414   sqlite3_vtab **ppVtab,
109415   char **pzErr
109416 ){
109417   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
109418 }
109419
109420 /* 
109421 ** Rtree virtual table module xConnect method.
109422 */
109423 static int rtreeConnect(
109424   sqlite3 *db,
109425   void *pAux,
109426   int argc, const char *const*argv,
109427   sqlite3_vtab **ppVtab,
109428   char **pzErr
109429 ){
109430   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
109431 }
109432
109433 /*
109434 ** Increment the r-tree reference count.
109435 */
109436 static void rtreeReference(Rtree *pRtree){
109437   pRtree->nBusy++;
109438 }
109439
109440 /*
109441 ** Decrement the r-tree reference count. When the reference count reaches
109442 ** zero the structure is deleted.
109443 */
109444 static void rtreeRelease(Rtree *pRtree){
109445   pRtree->nBusy--;
109446   if( pRtree->nBusy==0 ){
109447     sqlite3_finalize(pRtree->pReadNode);
109448     sqlite3_finalize(pRtree->pWriteNode);
109449     sqlite3_finalize(pRtree->pDeleteNode);
109450     sqlite3_finalize(pRtree->pReadRowid);
109451     sqlite3_finalize(pRtree->pWriteRowid);
109452     sqlite3_finalize(pRtree->pDeleteRowid);
109453     sqlite3_finalize(pRtree->pReadParent);
109454     sqlite3_finalize(pRtree->pWriteParent);
109455     sqlite3_finalize(pRtree->pDeleteParent);
109456     sqlite3_free(pRtree);
109457   }
109458 }
109459
109460 /* 
109461 ** Rtree virtual table module xDisconnect method.
109462 */
109463 static int rtreeDisconnect(sqlite3_vtab *pVtab){
109464   rtreeRelease((Rtree *)pVtab);
109465   return SQLITE_OK;
109466 }
109467
109468 /* 
109469 ** Rtree virtual table module xDestroy method.
109470 */
109471 static int rtreeDestroy(sqlite3_vtab *pVtab){
109472   Rtree *pRtree = (Rtree *)pVtab;
109473   int rc;
109474   char *zCreate = sqlite3_mprintf(
109475     "DROP TABLE '%q'.'%q_node';"
109476     "DROP TABLE '%q'.'%q_rowid';"
109477     "DROP TABLE '%q'.'%q_parent';",
109478     pRtree->zDb, pRtree->zName, 
109479     pRtree->zDb, pRtree->zName,
109480     pRtree->zDb, pRtree->zName
109481   );
109482   if( !zCreate ){
109483     rc = SQLITE_NOMEM;
109484   }else{
109485     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
109486     sqlite3_free(zCreate);
109487   }
109488   if( rc==SQLITE_OK ){
109489     rtreeRelease(pRtree);
109490   }
109491
109492   return rc;
109493 }
109494
109495 /* 
109496 ** Rtree virtual table module xOpen method.
109497 */
109498 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
109499   int rc = SQLITE_NOMEM;
109500   RtreeCursor *pCsr;
109501
109502   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
109503   if( pCsr ){
109504     memset(pCsr, 0, sizeof(RtreeCursor));
109505     pCsr->base.pVtab = pVTab;
109506     rc = SQLITE_OK;
109507   }
109508   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
109509
109510   return rc;
109511 }
109512
109513 /* 
109514 ** Rtree virtual table module xClose method.
109515 */
109516 static int rtreeClose(sqlite3_vtab_cursor *cur){
109517   Rtree *pRtree = (Rtree *)(cur->pVtab);
109518   int rc;
109519   RtreeCursor *pCsr = (RtreeCursor *)cur;
109520   sqlite3_free(pCsr->aConstraint);
109521   rc = nodeRelease(pRtree, pCsr->pNode);
109522   sqlite3_free(pCsr);
109523   return rc;
109524 }
109525
109526 /*
109527 ** Rtree virtual table module xEof method.
109528 **
109529 ** Return non-zero if the cursor does not currently point to a valid 
109530 ** record (i.e if the scan has finished), or zero otherwise.
109531 */
109532 static int rtreeEof(sqlite3_vtab_cursor *cur){
109533   RtreeCursor *pCsr = (RtreeCursor *)cur;
109534   return (pCsr->pNode==0);
109535 }
109536
109537 /* 
109538 ** Cursor pCursor currently points to a cell in a non-leaf page.
109539 ** Return true if the sub-tree headed by the cell is filtered
109540 ** (excluded) by the constraints in the pCursor->aConstraint[] 
109541 ** array, or false otherwise.
109542 */
109543 static int testRtreeCell(Rtree *pRtree, RtreeCursor *pCursor){
109544   RtreeCell cell;
109545   int ii;
109546   int bRes = 0;
109547
109548   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
109549   for(ii=0; bRes==0 && ii<pCursor->nConstraint; ii++){
109550     RtreeConstraint *p = &pCursor->aConstraint[ii];
109551     double cell_min = DCOORD(cell.aCoord[(p->iCoord>>1)*2]);
109552     double cell_max = DCOORD(cell.aCoord[(p->iCoord>>1)*2+1]);
109553
109554     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
109555         || p->op==RTREE_GT || p->op==RTREE_EQ
109556     );
109557
109558     switch( p->op ){
109559       case RTREE_LE: case RTREE_LT: bRes = p->rValue<cell_min; break;
109560       case RTREE_GE: case RTREE_GT: bRes = p->rValue>cell_max; break;
109561       case RTREE_EQ: 
109562         bRes = (p->rValue>cell_max || p->rValue<cell_min);
109563         break;
109564     }
109565   }
109566
109567   return bRes;
109568 }
109569
109570 /* 
109571 ** Return true if the cell that cursor pCursor currently points to
109572 ** would be filtered (excluded) by the constraints in the 
109573 ** pCursor->aConstraint[] array, or false otherwise.
109574 **
109575 ** This function assumes that the cell is part of a leaf node.
109576 */
109577 static int testRtreeEntry(Rtree *pRtree, RtreeCursor *pCursor){
109578   RtreeCell cell;
109579   int ii;
109580
109581   nodeGetCell(pRtree, pCursor->pNode, pCursor->iCell, &cell);
109582   for(ii=0; ii<pCursor->nConstraint; ii++){
109583     RtreeConstraint *p = &pCursor->aConstraint[ii];
109584     double coord = DCOORD(cell.aCoord[p->iCoord]);
109585     int res;
109586     assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
109587         || p->op==RTREE_GT || p->op==RTREE_EQ
109588     );
109589     switch( p->op ){
109590       case RTREE_LE: res = (coord<=p->rValue); break;
109591       case RTREE_LT: res = (coord<p->rValue);  break;
109592       case RTREE_GE: res = (coord>=p->rValue); break;
109593       case RTREE_GT: res = (coord>p->rValue);  break;
109594       case RTREE_EQ: res = (coord==p->rValue); break;
109595     }
109596
109597     if( !res ) return 1;
109598   }
109599
109600   return 0;
109601 }
109602
109603 /*
109604 ** Cursor pCursor currently points at a node that heads a sub-tree of
109605 ** height iHeight (if iHeight==0, then the node is a leaf). Descend
109606 ** to point to the left-most cell of the sub-tree that matches the 
109607 ** configured constraints.
109608 */
109609 static int descendToCell(
109610   Rtree *pRtree, 
109611   RtreeCursor *pCursor, 
109612   int iHeight,
109613   int *pEof                 /* OUT: Set to true if cannot descend */
109614 ){
109615   int isEof;
109616   int rc;
109617   int ii;
109618   RtreeNode *pChild;
109619   sqlite3_int64 iRowid;
109620
109621   RtreeNode *pSavedNode = pCursor->pNode;
109622   int iSavedCell = pCursor->iCell;
109623
109624   assert( iHeight>=0 );
109625
109626   if( iHeight==0 ){
109627     isEof = testRtreeEntry(pRtree, pCursor);
109628   }else{
109629     isEof = testRtreeCell(pRtree, pCursor);
109630   }
109631   if( isEof || iHeight==0 ){
109632     *pEof = isEof;
109633     return SQLITE_OK;
109634   }
109635
109636   iRowid = nodeGetRowid(pRtree, pCursor->pNode, pCursor->iCell);
109637   rc = nodeAcquire(pRtree, iRowid, pCursor->pNode, &pChild);
109638   if( rc!=SQLITE_OK ){
109639     return rc;
109640   }
109641
109642   nodeRelease(pRtree, pCursor->pNode);
109643   pCursor->pNode = pChild;
109644   isEof = 1;
109645   for(ii=0; isEof && ii<NCELL(pChild); ii++){
109646     pCursor->iCell = ii;
109647     rc = descendToCell(pRtree, pCursor, iHeight-1, &isEof);
109648     if( rc!=SQLITE_OK ){
109649       return rc;
109650     }
109651   }
109652
109653   if( isEof ){
109654     assert( pCursor->pNode==pChild );
109655     nodeReference(pSavedNode);
109656     nodeRelease(pRtree, pChild);
109657     pCursor->pNode = pSavedNode;
109658     pCursor->iCell = iSavedCell;
109659   }
109660
109661   *pEof = isEof;
109662   return SQLITE_OK;
109663 }
109664
109665 /*
109666 ** One of the cells in node pNode is guaranteed to have a 64-bit 
109667 ** integer value equal to iRowid. Return the index of this cell.
109668 */
109669 static int nodeRowidIndex(Rtree *pRtree, RtreeNode *pNode, i64 iRowid){
109670   int ii;
109671   for(ii=0; nodeGetRowid(pRtree, pNode, ii)!=iRowid; ii++){
109672     assert( ii<(NCELL(pNode)-1) );
109673   }
109674   return ii;
109675 }
109676
109677 /*
109678 ** Return the index of the cell containing a pointer to node pNode
109679 ** in its parent. If pNode is the root node, return -1.
109680 */
109681 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode){
109682   RtreeNode *pParent = pNode->pParent;
109683   if( pParent ){
109684     return nodeRowidIndex(pRtree, pParent, pNode->iNode);
109685   }
109686   return -1;
109687 }
109688
109689 /* 
109690 ** Rtree virtual table module xNext method.
109691 */
109692 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
109693   Rtree *pRtree = (Rtree *)(pVtabCursor->pVtab);
109694   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
109695   int rc = SQLITE_OK;
109696
109697   if( pCsr->iStrategy==1 ){
109698     /* This "scan" is a direct lookup by rowid. There is no next entry. */
109699     nodeRelease(pRtree, pCsr->pNode);
109700     pCsr->pNode = 0;
109701   }
109702
109703   else if( pCsr->pNode ){
109704     /* Move to the next entry that matches the configured constraints. */
109705     int iHeight = 0;
109706     while( pCsr->pNode ){
109707       RtreeNode *pNode = pCsr->pNode;
109708       int nCell = NCELL(pNode);
109709       for(pCsr->iCell++; pCsr->iCell<nCell; pCsr->iCell++){
109710         int isEof;
109711         rc = descendToCell(pRtree, pCsr, iHeight, &isEof);
109712         if( rc!=SQLITE_OK || !isEof ){
109713           return rc;
109714         }
109715       }
109716       pCsr->pNode = pNode->pParent;
109717       pCsr->iCell = nodeParentIndex(pRtree, pNode);
109718       nodeReference(pCsr->pNode);
109719       nodeRelease(pRtree, pNode);
109720       iHeight++;
109721     }
109722   }
109723
109724   return rc;
109725 }
109726
109727 /* 
109728 ** Rtree virtual table module xRowid method.
109729 */
109730 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
109731   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
109732   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
109733
109734   assert(pCsr->pNode);
109735   *pRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
109736
109737   return SQLITE_OK;
109738 }
109739
109740 /* 
109741 ** Rtree virtual table module xColumn method.
109742 */
109743 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
109744   Rtree *pRtree = (Rtree *)cur->pVtab;
109745   RtreeCursor *pCsr = (RtreeCursor *)cur;
109746
109747   if( i==0 ){
109748     i64 iRowid = nodeGetRowid(pRtree, pCsr->pNode, pCsr->iCell);
109749     sqlite3_result_int64(ctx, iRowid);
109750   }else{
109751     RtreeCoord c;
109752     nodeGetCoord(pRtree, pCsr->pNode, pCsr->iCell, i-1, &c);
109753     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
109754       sqlite3_result_double(ctx, c.f);
109755     }else{
109756       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
109757       sqlite3_result_int(ctx, c.i);
109758     }
109759   }
109760
109761   return SQLITE_OK;
109762 }
109763
109764 /* 
109765 ** Use nodeAcquire() to obtain the leaf node containing the record with 
109766 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
109767 ** return SQLITE_OK. If there is no such record in the table, set
109768 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
109769 ** to zero and return an SQLite error code.
109770 */
109771 static int findLeafNode(Rtree *pRtree, i64 iRowid, RtreeNode **ppLeaf){
109772   int rc;
109773   *ppLeaf = 0;
109774   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
109775   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
109776     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
109777     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
109778     sqlite3_reset(pRtree->pReadRowid);
109779   }else{
109780     rc = sqlite3_reset(pRtree->pReadRowid);
109781   }
109782   return rc;
109783 }
109784
109785
109786 /* 
109787 ** Rtree virtual table module xFilter method.
109788 */
109789 static int rtreeFilter(
109790   sqlite3_vtab_cursor *pVtabCursor, 
109791   int idxNum, const char *idxStr,
109792   int argc, sqlite3_value **argv
109793 ){
109794   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
109795   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
109796
109797   RtreeNode *pRoot = 0;
109798   int ii;
109799   int rc = SQLITE_OK;
109800
109801   rtreeReference(pRtree);
109802
109803   sqlite3_free(pCsr->aConstraint);
109804   pCsr->aConstraint = 0;
109805   pCsr->iStrategy = idxNum;
109806
109807   if( idxNum==1 ){
109808     /* Special case - lookup by rowid. */
109809     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
109810     i64 iRowid = sqlite3_value_int64(argv[0]);
109811     rc = findLeafNode(pRtree, iRowid, &pLeaf);
109812     pCsr->pNode = pLeaf; 
109813     if( pLeaf && rc==SQLITE_OK ){
109814       pCsr->iCell = nodeRowidIndex(pRtree, pLeaf, iRowid);
109815     }
109816   }else{
109817     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
109818     ** with the configured constraints. 
109819     */
109820     if( argc>0 ){
109821       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
109822       pCsr->nConstraint = argc;
109823       if( !pCsr->aConstraint ){
109824         rc = SQLITE_NOMEM;
109825       }else{
109826         assert( (idxStr==0 && argc==0) || strlen(idxStr)==argc*2 );
109827         for(ii=0; ii<argc; ii++){
109828           RtreeConstraint *p = &pCsr->aConstraint[ii];
109829           p->op = idxStr[ii*2];
109830           p->iCoord = idxStr[ii*2+1]-'a';
109831           p->rValue = sqlite3_value_double(argv[ii]);
109832         }
109833       }
109834     }
109835   
109836     if( rc==SQLITE_OK ){
109837       pCsr->pNode = 0;
109838       rc = nodeAcquire(pRtree, 1, 0, &pRoot);
109839     }
109840     if( rc==SQLITE_OK ){
109841       int isEof = 1;
109842       int nCell = NCELL(pRoot);
109843       pCsr->pNode = pRoot;
109844       for(pCsr->iCell=0; rc==SQLITE_OK && pCsr->iCell<nCell; pCsr->iCell++){
109845         assert( pCsr->pNode==pRoot );
109846         rc = descendToCell(pRtree, pCsr, pRtree->iDepth, &isEof);
109847         if( !isEof ){
109848           break;
109849         }
109850       }
109851       if( rc==SQLITE_OK && isEof ){
109852         assert( pCsr->pNode==pRoot );
109853         nodeRelease(pRtree, pRoot);
109854         pCsr->pNode = 0;
109855       }
109856       assert( rc!=SQLITE_OK || !pCsr->pNode || pCsr->iCell<NCELL(pCsr->pNode) );
109857     }
109858   }
109859
109860   rtreeRelease(pRtree);
109861   return rc;
109862 }
109863
109864 /*
109865 ** Rtree virtual table module xBestIndex method. There are three
109866 ** table scan strategies to choose from (in order from most to 
109867 ** least desirable):
109868 **
109869 **   idxNum     idxStr        Strategy
109870 **   ------------------------------------------------
109871 **     1        Unused        Direct lookup by rowid.
109872 **     2        See below     R-tree query.
109873 **     3        Unused        Full table scan.
109874 **   ------------------------------------------------
109875 **
109876 ** If strategy 1 or 3 is used, then idxStr is not meaningful. If strategy
109877 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
109878 ** constraint used. The first two bytes of idxStr correspond to 
109879 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
109880 ** (argvIndex==1) etc.
109881 **
109882 ** The first of each pair of bytes in idxStr identifies the constraint
109883 ** operator as follows:
109884 **
109885 **   Operator    Byte Value
109886 **   ----------------------
109887 **      =        0x41 ('A')
109888 **     <=        0x42 ('B')
109889 **      <        0x43 ('C')
109890 **     >=        0x44 ('D')
109891 **      >        0x45 ('E')
109892 **   ----------------------
109893 **
109894 ** The second of each pair of bytes identifies the coordinate column
109895 ** to which the constraint applies. The leftmost coordinate column
109896 ** is 'a', the second from the left 'b' etc.
109897 */
109898 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
109899   int rc = SQLITE_OK;
109900   int ii, cCol;
109901
109902   int iIdx = 0;
109903   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
109904   memset(zIdxStr, 0, sizeof(zIdxStr));
109905
109906   assert( pIdxInfo->idxStr==0 );
109907   for(ii=0; ii<pIdxInfo->nConstraint; ii++){
109908     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
109909
109910     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
109911       /* We have an equality constraint on the rowid. Use strategy 1. */
109912       int jj;
109913       for(jj=0; jj<ii; jj++){
109914         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
109915         pIdxInfo->aConstraintUsage[jj].omit = 0;
109916       }
109917       pIdxInfo->idxNum = 1;
109918       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
109919       pIdxInfo->aConstraintUsage[jj].omit = 1;
109920
109921       /* This strategy involves a two rowid lookups on an B-Tree structures
109922       ** and then a linear search of an R-Tree node. This should be 
109923       ** considered almost as quick as a direct rowid lookup (for which 
109924       ** sqlite uses an internal cost of 0.0).
109925       */ 
109926       pIdxInfo->estimatedCost = 10.0;
109927       return SQLITE_OK;
109928     }
109929
109930     if( p->usable && p->iColumn>0 ){
109931       u8 op = 0;
109932       switch( p->op ){
109933         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
109934         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
109935         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
109936         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
109937         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
109938       }
109939       if( op ){
109940         /* Make sure this particular constraint has not been used before.
109941         ** If it has been used before, ignore it.
109942         **
109943         ** A <= or < can be used if there is a prior >= or >.
109944         ** A >= or > can be used if there is a prior < or <=.
109945         ** A <= or < is disqualified if there is a prior <=, <, or ==.
109946         ** A >= or > is disqualified if there is a prior >=, >, or ==.
109947         ** A == is disqualifed if there is any prior constraint.
109948         */
109949         int j, opmsk;
109950         static const unsigned char compatible[] = { 0, 0, 1, 1, 2, 2 };
109951         assert( compatible[RTREE_EQ & 7]==0 );
109952         assert( compatible[RTREE_LT & 7]==1 );
109953         assert( compatible[RTREE_LE & 7]==1 );
109954         assert( compatible[RTREE_GT & 7]==2 );
109955         assert( compatible[RTREE_GE & 7]==2 );
109956         cCol = p->iColumn - 1 + 'a';
109957         opmsk = compatible[op & 7];
109958         for(j=0; j<iIdx; j+=2){
109959           if( zIdxStr[j+1]==cCol && (compatible[zIdxStr[j] & 7] & opmsk)!=0 ){
109960             op = 0;
109961             break;
109962           }
109963         }
109964       }
109965       if( op ){
109966         assert( iIdx<sizeof(zIdxStr)-1 );
109967         zIdxStr[iIdx++] = op;
109968         zIdxStr[iIdx++] = cCol;
109969         pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
109970         pIdxInfo->aConstraintUsage[ii].omit = 1;
109971       }
109972     }
109973   }
109974
109975   pIdxInfo->idxNum = 2;
109976   pIdxInfo->needToFreeIdxStr = 1;
109977   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
109978     return SQLITE_NOMEM;
109979   }
109980   assert( iIdx>=0 );
109981   pIdxInfo->estimatedCost = (2000000.0 / (double)(iIdx + 1));
109982   return rc;
109983 }
109984
109985 /*
109986 ** Return the N-dimensional volumn of the cell stored in *p.
109987 */
109988 static float cellArea(Rtree *pRtree, RtreeCell *p){
109989   float area = 1.0;
109990   int ii;
109991   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
109992     area = area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
109993   }
109994   return area;
109995 }
109996
109997 /*
109998 ** Return the margin length of cell p. The margin length is the sum
109999 ** of the objects size in each dimension.
110000 */
110001 static float cellMargin(Rtree *pRtree, RtreeCell *p){
110002   float margin = 0.0;
110003   int ii;
110004   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
110005     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
110006   }
110007   return margin;
110008 }
110009
110010 /*
110011 ** Store the union of cells p1 and p2 in p1.
110012 */
110013 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
110014   int ii;
110015   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
110016     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
110017       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
110018       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
110019     }
110020   }else{
110021     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
110022       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
110023       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
110024     }
110025   }
110026 }
110027
110028 /*
110029 ** Return true if the area covered by p2 is a subset of the area covered
110030 ** by p1. False otherwise.
110031 */
110032 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
110033   int ii;
110034   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
110035   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
110036     RtreeCoord *a1 = &p1->aCoord[ii];
110037     RtreeCoord *a2 = &p2->aCoord[ii];
110038     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
110039      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
110040     ){
110041       return 0;
110042     }
110043   }
110044   return 1;
110045 }
110046
110047 /*
110048 ** Return the amount cell p would grow by if it were unioned with pCell.
110049 */
110050 static float cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
110051   float area;
110052   RtreeCell cell;
110053   memcpy(&cell, p, sizeof(RtreeCell));
110054   area = cellArea(pRtree, &cell);
110055   cellUnion(pRtree, &cell, pCell);
110056   return (cellArea(pRtree, &cell)-area);
110057 }
110058
110059 #if VARIANT_RSTARTREE_CHOOSESUBTREE || VARIANT_RSTARTREE_SPLIT
110060 static float cellOverlap(
110061   Rtree *pRtree, 
110062   RtreeCell *p, 
110063   RtreeCell *aCell, 
110064   int nCell, 
110065   int iExclude
110066 ){
110067   int ii;
110068   float overlap = 0.0;
110069   for(ii=0; ii<nCell; ii++){
110070     if( ii!=iExclude ){
110071       int jj;
110072       float o = 1.0;
110073       for(jj=0; jj<(pRtree->nDim*2); jj+=2){
110074         double x1;
110075         double x2;
110076
110077         x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
110078         x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
110079
110080         if( x2<x1 ){
110081           o = 0.0;
110082           break;
110083         }else{
110084           o = o * (x2-x1);
110085         }
110086       }
110087       overlap += o;
110088     }
110089   }
110090   return overlap;
110091 }
110092 #endif
110093
110094 #if VARIANT_RSTARTREE_CHOOSESUBTREE
110095 static float cellOverlapEnlargement(
110096   Rtree *pRtree, 
110097   RtreeCell *p, 
110098   RtreeCell *pInsert, 
110099   RtreeCell *aCell, 
110100   int nCell, 
110101   int iExclude
110102 ){
110103   float before;
110104   float after;
110105   before = cellOverlap(pRtree, p, aCell, nCell, iExclude);
110106   cellUnion(pRtree, p, pInsert);
110107   after = cellOverlap(pRtree, p, aCell, nCell, iExclude);
110108   return after-before;
110109 }
110110 #endif
110111
110112
110113 /*
110114 ** This function implements the ChooseLeaf algorithm from Gutman[84].
110115 ** ChooseSubTree in r*tree terminology.
110116 */
110117 static int ChooseLeaf(
110118   Rtree *pRtree,               /* Rtree table */
110119   RtreeCell *pCell,            /* Cell to insert into rtree */
110120   int iHeight,                 /* Height of sub-tree rooted at pCell */
110121   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
110122 ){
110123   int rc;
110124   int ii;
110125   RtreeNode *pNode;
110126   rc = nodeAcquire(pRtree, 1, 0, &pNode);
110127
110128   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
110129     int iCell;
110130     sqlite3_int64 iBest;
110131
110132     float fMinGrowth;
110133     float fMinArea;
110134     float fMinOverlap;
110135
110136     int nCell = NCELL(pNode);
110137     RtreeCell cell;
110138     RtreeNode *pChild;
110139
110140     RtreeCell *aCell = 0;
110141
110142 #if VARIANT_RSTARTREE_CHOOSESUBTREE
110143     if( ii==(pRtree->iDepth-1) ){
110144       int jj;
110145       aCell = sqlite3_malloc(sizeof(RtreeCell)*nCell);
110146       if( !aCell ){
110147         rc = SQLITE_NOMEM;
110148         nodeRelease(pRtree, pNode);
110149         pNode = 0;
110150         continue;
110151       }
110152       for(jj=0; jj<nCell; jj++){
110153         nodeGetCell(pRtree, pNode, jj, &aCell[jj]);
110154       }
110155     }
110156 #endif
110157
110158     /* Select the child node which will be enlarged the least if pCell
110159     ** is inserted into it. Resolve ties by choosing the entry with
110160     ** the smallest area.
110161     */
110162     for(iCell=0; iCell<nCell; iCell++){
110163       float growth;
110164       float area;
110165       float overlap = 0.0;
110166       nodeGetCell(pRtree, pNode, iCell, &cell);
110167       growth = cellGrowth(pRtree, &cell, pCell);
110168       area = cellArea(pRtree, &cell);
110169 #if VARIANT_RSTARTREE_CHOOSESUBTREE
110170       if( ii==(pRtree->iDepth-1) ){
110171         overlap = cellOverlapEnlargement(pRtree,&cell,pCell,aCell,nCell,iCell);
110172       }
110173 #endif
110174       if( (iCell==0) 
110175        || (overlap<fMinOverlap) 
110176        || (overlap==fMinOverlap && growth<fMinGrowth)
110177        || (overlap==fMinOverlap && growth==fMinGrowth && area<fMinArea)
110178       ){
110179         fMinOverlap = overlap;
110180         fMinGrowth = growth;
110181         fMinArea = area;
110182         iBest = cell.iRowid;
110183       }
110184     }
110185
110186     sqlite3_free(aCell);
110187     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
110188     nodeRelease(pRtree, pNode);
110189     pNode = pChild;
110190   }
110191
110192   *ppLeaf = pNode;
110193   return rc;
110194 }
110195
110196 /*
110197 ** A cell with the same content as pCell has just been inserted into
110198 ** the node pNode. This function updates the bounding box cells in
110199 ** all ancestor elements.
110200 */
110201 static void AdjustTree(
110202   Rtree *pRtree,                    /* Rtree table */
110203   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
110204   RtreeCell *pCell                  /* This cell was just inserted */
110205 ){
110206   RtreeNode *p = pNode;
110207   while( p->pParent ){
110208     RtreeCell cell;
110209     RtreeNode *pParent = p->pParent;
110210     int iCell = nodeParentIndex(pRtree, p);
110211
110212     nodeGetCell(pRtree, pParent, iCell, &cell);
110213     if( !cellContains(pRtree, &cell, pCell) ){
110214       cellUnion(pRtree, &cell, pCell);
110215       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
110216     }
110217  
110218     p = pParent;
110219   }
110220 }
110221
110222 /*
110223 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
110224 */
110225 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
110226   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
110227   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
110228   sqlite3_step(pRtree->pWriteRowid);
110229   return sqlite3_reset(pRtree->pWriteRowid);
110230 }
110231
110232 /*
110233 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
110234 */
110235 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
110236   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
110237   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
110238   sqlite3_step(pRtree->pWriteParent);
110239   return sqlite3_reset(pRtree->pWriteParent);
110240 }
110241
110242 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
110243
110244 #if VARIANT_GUTTMAN_LINEAR_SPLIT
110245 /*
110246 ** Implementation of the linear variant of the PickNext() function from
110247 ** Guttman[84].
110248 */
110249 static RtreeCell *LinearPickNext(
110250   Rtree *pRtree,
110251   RtreeCell *aCell, 
110252   int nCell, 
110253   RtreeCell *pLeftBox, 
110254   RtreeCell *pRightBox,
110255   int *aiUsed
110256 ){
110257   int ii;
110258   for(ii=0; aiUsed[ii]; ii++);
110259   aiUsed[ii] = 1;
110260   return &aCell[ii];
110261 }
110262
110263 /*
110264 ** Implementation of the linear variant of the PickSeeds() function from
110265 ** Guttman[84].
110266 */
110267 static void LinearPickSeeds(
110268   Rtree *pRtree,
110269   RtreeCell *aCell, 
110270   int nCell, 
110271   int *piLeftSeed, 
110272   int *piRightSeed
110273 ){
110274   int i;
110275   int iLeftSeed = 0;
110276   int iRightSeed = 1;
110277   float maxNormalInnerWidth = 0.0;
110278
110279   /* Pick two "seed" cells from the array of cells. The algorithm used
110280   ** here is the LinearPickSeeds algorithm from Gutman[1984]. The 
110281   ** indices of the two seed cells in the array are stored in local
110282   ** variables iLeftSeek and iRightSeed.
110283   */
110284   for(i=0; i<pRtree->nDim; i++){
110285     float x1 = DCOORD(aCell[0].aCoord[i*2]);
110286     float x2 = DCOORD(aCell[0].aCoord[i*2+1]);
110287     float x3 = x1;
110288     float x4 = x2;
110289     int jj;
110290
110291     int iCellLeft = 0;
110292     int iCellRight = 0;
110293
110294     for(jj=1; jj<nCell; jj++){
110295       float left = DCOORD(aCell[jj].aCoord[i*2]);
110296       float right = DCOORD(aCell[jj].aCoord[i*2+1]);
110297
110298       if( left<x1 ) x1 = left;
110299       if( right>x4 ) x4 = right;
110300       if( left>x3 ){
110301         x3 = left;
110302         iCellRight = jj;
110303       }
110304       if( right<x2 ){
110305         x2 = right;
110306         iCellLeft = jj;
110307       }
110308     }
110309
110310     if( x4!=x1 ){
110311       float normalwidth = (x3 - x2) / (x4 - x1);
110312       if( normalwidth>maxNormalInnerWidth ){
110313         iLeftSeed = iCellLeft;
110314         iRightSeed = iCellRight;
110315       }
110316     }
110317   }
110318
110319   *piLeftSeed = iLeftSeed;
110320   *piRightSeed = iRightSeed;
110321 }
110322 #endif /* VARIANT_GUTTMAN_LINEAR_SPLIT */
110323
110324 #if VARIANT_GUTTMAN_QUADRATIC_SPLIT
110325 /*
110326 ** Implementation of the quadratic variant of the PickNext() function from
110327 ** Guttman[84].
110328 */
110329 static RtreeCell *QuadraticPickNext(
110330   Rtree *pRtree,
110331   RtreeCell *aCell, 
110332   int nCell, 
110333   RtreeCell *pLeftBox, 
110334   RtreeCell *pRightBox,
110335   int *aiUsed
110336 ){
110337   #define FABS(a) ((a)<0.0?-1.0*(a):(a))
110338
110339   int iSelect = -1;
110340   float fDiff;
110341   int ii;
110342   for(ii=0; ii<nCell; ii++){
110343     if( aiUsed[ii]==0 ){
110344       float left = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
110345       float right = cellGrowth(pRtree, pLeftBox, &aCell[ii]);
110346       float diff = FABS(right-left);
110347       if( iSelect<0 || diff>fDiff ){
110348         fDiff = diff;
110349         iSelect = ii;
110350       }
110351     }
110352   }
110353   aiUsed[iSelect] = 1;
110354   return &aCell[iSelect];
110355 }
110356
110357 /*
110358 ** Implementation of the quadratic variant of the PickSeeds() function from
110359 ** Guttman[84].
110360 */
110361 static void QuadraticPickSeeds(
110362   Rtree *pRtree,
110363   RtreeCell *aCell, 
110364   int nCell, 
110365   int *piLeftSeed, 
110366   int *piRightSeed
110367 ){
110368   int ii;
110369   int jj;
110370
110371   int iLeftSeed = 0;
110372   int iRightSeed = 1;
110373   float fWaste = 0.0;
110374
110375   for(ii=0; ii<nCell; ii++){
110376     for(jj=ii+1; jj<nCell; jj++){
110377       float right = cellArea(pRtree, &aCell[jj]);
110378       float growth = cellGrowth(pRtree, &aCell[ii], &aCell[jj]);
110379       float waste = growth - right;
110380
110381       if( waste>fWaste ){
110382         iLeftSeed = ii;
110383         iRightSeed = jj;
110384         fWaste = waste;
110385       }
110386     }
110387   }
110388
110389   *piLeftSeed = iLeftSeed;
110390   *piRightSeed = iRightSeed;
110391 }
110392 #endif /* VARIANT_GUTTMAN_QUADRATIC_SPLIT */
110393
110394 /*
110395 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
110396 ** nIdx. The aIdx array contains the set of integers from 0 to 
110397 ** (nIdx-1) in no particular order. This function sorts the values
110398 ** in aIdx according to the indexed values in aDistance. For
110399 ** example, assuming the inputs:
110400 **
110401 **   aIdx      = { 0,   1,   2,   3 }
110402 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
110403 **
110404 ** this function sets the aIdx array to contain:
110405 **
110406 **   aIdx      = { 0,   1,   2,   3 }
110407 **
110408 ** The aSpare array is used as temporary working space by the
110409 ** sorting algorithm.
110410 */
110411 static void SortByDistance(
110412   int *aIdx, 
110413   int nIdx, 
110414   float *aDistance, 
110415   int *aSpare
110416 ){
110417   if( nIdx>1 ){
110418     int iLeft = 0;
110419     int iRight = 0;
110420
110421     int nLeft = nIdx/2;
110422     int nRight = nIdx-nLeft;
110423     int *aLeft = aIdx;
110424     int *aRight = &aIdx[nLeft];
110425
110426     SortByDistance(aLeft, nLeft, aDistance, aSpare);
110427     SortByDistance(aRight, nRight, aDistance, aSpare);
110428
110429     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
110430     aLeft = aSpare;
110431
110432     while( iLeft<nLeft || iRight<nRight ){
110433       if( iLeft==nLeft ){
110434         aIdx[iLeft+iRight] = aRight[iRight];
110435         iRight++;
110436       }else if( iRight==nRight ){
110437         aIdx[iLeft+iRight] = aLeft[iLeft];
110438         iLeft++;
110439       }else{
110440         float fLeft = aDistance[aLeft[iLeft]];
110441         float fRight = aDistance[aRight[iRight]];
110442         if( fLeft<fRight ){
110443           aIdx[iLeft+iRight] = aLeft[iLeft];
110444           iLeft++;
110445         }else{
110446           aIdx[iLeft+iRight] = aRight[iRight];
110447           iRight++;
110448         }
110449       }
110450     }
110451
110452 #if 0
110453     /* Check that the sort worked */
110454     {
110455       int jj;
110456       for(jj=1; jj<nIdx; jj++){
110457         float left = aDistance[aIdx[jj-1]];
110458         float right = aDistance[aIdx[jj]];
110459         assert( left<=right );
110460       }
110461     }
110462 #endif
110463   }
110464 }
110465
110466 /*
110467 ** Arguments aIdx, aCell and aSpare all point to arrays of size
110468 ** nIdx. The aIdx array contains the set of integers from 0 to 
110469 ** (nIdx-1) in no particular order. This function sorts the values
110470 ** in aIdx according to dimension iDim of the cells in aCell. The
110471 ** minimum value of dimension iDim is considered first, the
110472 ** maximum used to break ties.
110473 **
110474 ** The aSpare array is used as temporary working space by the
110475 ** sorting algorithm.
110476 */
110477 static void SortByDimension(
110478   Rtree *pRtree,
110479   int *aIdx, 
110480   int nIdx, 
110481   int iDim, 
110482   RtreeCell *aCell, 
110483   int *aSpare
110484 ){
110485   if( nIdx>1 ){
110486
110487     int iLeft = 0;
110488     int iRight = 0;
110489
110490     int nLeft = nIdx/2;
110491     int nRight = nIdx-nLeft;
110492     int *aLeft = aIdx;
110493     int *aRight = &aIdx[nLeft];
110494
110495     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
110496     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
110497
110498     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
110499     aLeft = aSpare;
110500     while( iLeft<nLeft || iRight<nRight ){
110501       double xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
110502       double xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
110503       double xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
110504       double xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
110505       if( (iLeft!=nLeft) && ((iRight==nRight)
110506        || (xleft1<xright1)
110507        || (xleft1==xright1 && xleft2<xright2)
110508       )){
110509         aIdx[iLeft+iRight] = aLeft[iLeft];
110510         iLeft++;
110511       }else{
110512         aIdx[iLeft+iRight] = aRight[iRight];
110513         iRight++;
110514       }
110515     }
110516
110517 #if 0
110518     /* Check that the sort worked */
110519     {
110520       int jj;
110521       for(jj=1; jj<nIdx; jj++){
110522         float xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
110523         float xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
110524         float xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
110525         float xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
110526         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
110527       }
110528     }
110529 #endif
110530   }
110531 }
110532
110533 #if VARIANT_RSTARTREE_SPLIT
110534 /*
110535 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
110536 */
110537 static int splitNodeStartree(
110538   Rtree *pRtree,
110539   RtreeCell *aCell,
110540   int nCell,
110541   RtreeNode *pLeft,
110542   RtreeNode *pRight,
110543   RtreeCell *pBboxLeft,
110544   RtreeCell *pBboxRight
110545 ){
110546   int **aaSorted;
110547   int *aSpare;
110548   int ii;
110549
110550   int iBestDim;
110551   int iBestSplit;
110552   float fBestMargin;
110553
110554   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
110555
110556   aaSorted = (int **)sqlite3_malloc(nByte);
110557   if( !aaSorted ){
110558     return SQLITE_NOMEM;
110559   }
110560
110561   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
110562   memset(aaSorted, 0, nByte);
110563   for(ii=0; ii<pRtree->nDim; ii++){
110564     int jj;
110565     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
110566     for(jj=0; jj<nCell; jj++){
110567       aaSorted[ii][jj] = jj;
110568     }
110569     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
110570   }
110571
110572   for(ii=0; ii<pRtree->nDim; ii++){
110573     float margin = 0.0;
110574     float fBestOverlap;
110575     float fBestArea;
110576     int iBestLeft;
110577     int nLeft;
110578
110579     for(
110580       nLeft=RTREE_MINCELLS(pRtree); 
110581       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
110582       nLeft++
110583     ){
110584       RtreeCell left;
110585       RtreeCell right;
110586       int kk;
110587       float overlap;
110588       float area;
110589
110590       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
110591       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
110592       for(kk=1; kk<(nCell-1); kk++){
110593         if( kk<nLeft ){
110594           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
110595         }else{
110596           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
110597         }
110598       }
110599       margin += cellMargin(pRtree, &left);
110600       margin += cellMargin(pRtree, &right);
110601       overlap = cellOverlap(pRtree, &left, &right, 1, -1);
110602       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
110603       if( (nLeft==RTREE_MINCELLS(pRtree))
110604        || (overlap<fBestOverlap)
110605        || (overlap==fBestOverlap && area<fBestArea)
110606       ){
110607         iBestLeft = nLeft;
110608         fBestOverlap = overlap;
110609         fBestArea = area;
110610       }
110611     }
110612
110613     if( ii==0 || margin<fBestMargin ){
110614       iBestDim = ii;
110615       fBestMargin = margin;
110616       iBestSplit = iBestLeft;
110617     }
110618   }
110619
110620   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
110621   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
110622   for(ii=0; ii<nCell; ii++){
110623     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
110624     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
110625     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
110626     nodeInsertCell(pRtree, pTarget, pCell);
110627     cellUnion(pRtree, pBbox, pCell);
110628   }
110629
110630   sqlite3_free(aaSorted);
110631   return SQLITE_OK;
110632 }
110633 #endif
110634
110635 #if VARIANT_GUTTMAN_SPLIT
110636 /*
110637 ** Implementation of the regular R-tree SplitNode from Guttman[1984].
110638 */
110639 static int splitNodeGuttman(
110640   Rtree *pRtree,
110641   RtreeCell *aCell,
110642   int nCell,
110643   RtreeNode *pLeft,
110644   RtreeNode *pRight,
110645   RtreeCell *pBboxLeft,
110646   RtreeCell *pBboxRight
110647 ){
110648   int iLeftSeed = 0;
110649   int iRightSeed = 1;
110650   int *aiUsed;
110651   int i;
110652
110653   aiUsed = sqlite3_malloc(sizeof(int)*nCell);
110654   if( !aiUsed ){
110655     return SQLITE_NOMEM;
110656   }
110657   memset(aiUsed, 0, sizeof(int)*nCell);
110658
110659   PickSeeds(pRtree, aCell, nCell, &iLeftSeed, &iRightSeed);
110660
110661   memcpy(pBboxLeft, &aCell[iLeftSeed], sizeof(RtreeCell));
110662   memcpy(pBboxRight, &aCell[iRightSeed], sizeof(RtreeCell));
110663   nodeInsertCell(pRtree, pLeft, &aCell[iLeftSeed]);
110664   nodeInsertCell(pRtree, pRight, &aCell[iRightSeed]);
110665   aiUsed[iLeftSeed] = 1;
110666   aiUsed[iRightSeed] = 1;
110667
110668   for(i=nCell-2; i>0; i--){
110669     RtreeCell *pNext;
110670     pNext = PickNext(pRtree, aCell, nCell, pBboxLeft, pBboxRight, aiUsed);
110671     float diff =  
110672       cellGrowth(pRtree, pBboxLeft, pNext) - 
110673       cellGrowth(pRtree, pBboxRight, pNext)
110674     ;
110675     if( (RTREE_MINCELLS(pRtree)-NCELL(pRight)==i)
110676      || (diff>0.0 && (RTREE_MINCELLS(pRtree)-NCELL(pLeft)!=i))
110677     ){
110678       nodeInsertCell(pRtree, pRight, pNext);
110679       cellUnion(pRtree, pBboxRight, pNext);
110680     }else{
110681       nodeInsertCell(pRtree, pLeft, pNext);
110682       cellUnion(pRtree, pBboxLeft, pNext);
110683     }
110684   }
110685
110686   sqlite3_free(aiUsed);
110687   return SQLITE_OK;
110688 }
110689 #endif
110690
110691 static int updateMapping(
110692   Rtree *pRtree, 
110693   i64 iRowid, 
110694   RtreeNode *pNode, 
110695   int iHeight
110696 ){
110697   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
110698   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
110699   if( iHeight>0 ){
110700     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
110701     if( pChild ){
110702       nodeRelease(pRtree, pChild->pParent);
110703       nodeReference(pNode);
110704       pChild->pParent = pNode;
110705     }
110706   }
110707   return xSetMapping(pRtree, iRowid, pNode->iNode);
110708 }
110709
110710 static int SplitNode(
110711   Rtree *pRtree,
110712   RtreeNode *pNode,
110713   RtreeCell *pCell,
110714   int iHeight
110715 ){
110716   int i;
110717   int newCellIsRight = 0;
110718
110719   int rc = SQLITE_OK;
110720   int nCell = NCELL(pNode);
110721   RtreeCell *aCell;
110722   int *aiUsed;
110723
110724   RtreeNode *pLeft = 0;
110725   RtreeNode *pRight = 0;
110726
110727   RtreeCell leftbbox;
110728   RtreeCell rightbbox;
110729
110730   /* Allocate an array and populate it with a copy of pCell and 
110731   ** all cells from node pLeft. Then zero the original node.
110732   */
110733   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
110734   if( !aCell ){
110735     rc = SQLITE_NOMEM;
110736     goto splitnode_out;
110737   }
110738   aiUsed = (int *)&aCell[nCell+1];
110739   memset(aiUsed, 0, sizeof(int)*(nCell+1));
110740   for(i=0; i<nCell; i++){
110741     nodeGetCell(pRtree, pNode, i, &aCell[i]);
110742   }
110743   nodeZero(pRtree, pNode);
110744   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
110745   nCell++;
110746
110747   if( pNode->iNode==1 ){
110748     pRight = nodeNew(pRtree, pNode, 1);
110749     pLeft = nodeNew(pRtree, pNode, 1);
110750     pRtree->iDepth++;
110751     pNode->isDirty = 1;
110752     writeInt16(pNode->zData, pRtree->iDepth);
110753   }else{
110754     pLeft = pNode;
110755     pRight = nodeNew(pRtree, pLeft->pParent, 1);
110756     nodeReference(pLeft);
110757   }
110758
110759   if( !pLeft || !pRight ){
110760     rc = SQLITE_NOMEM;
110761     goto splitnode_out;
110762   }
110763
110764   memset(pLeft->zData, 0, pRtree->iNodeSize);
110765   memset(pRight->zData, 0, pRtree->iNodeSize);
110766
110767   rc = AssignCells(pRtree, aCell, nCell, pLeft, pRight, &leftbbox, &rightbbox);
110768   if( rc!=SQLITE_OK ){
110769     goto splitnode_out;
110770   }
110771
110772   /* Ensure both child nodes have node numbers assigned to them. */
110773   if( (0==pRight->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pRight)))
110774    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
110775   ){
110776     goto splitnode_out;
110777   }
110778
110779   rightbbox.iRowid = pRight->iNode;
110780   leftbbox.iRowid = pLeft->iNode;
110781
110782   if( pNode->iNode==1 ){
110783     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
110784     if( rc!=SQLITE_OK ){
110785       goto splitnode_out;
110786     }
110787   }else{
110788     RtreeNode *pParent = pLeft->pParent;
110789     int iCell = nodeParentIndex(pRtree, pLeft);
110790     nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
110791     AdjustTree(pRtree, pParent, &leftbbox);
110792   }
110793   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
110794     goto splitnode_out;
110795   }
110796
110797   for(i=0; i<NCELL(pRight); i++){
110798     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
110799     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
110800     if( iRowid==pCell->iRowid ){
110801       newCellIsRight = 1;
110802     }
110803     if( rc!=SQLITE_OK ){
110804       goto splitnode_out;
110805     }
110806   }
110807   if( pNode->iNode==1 ){
110808     for(i=0; i<NCELL(pLeft); i++){
110809       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
110810       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
110811       if( rc!=SQLITE_OK ){
110812         goto splitnode_out;
110813       }
110814     }
110815   }else if( newCellIsRight==0 ){
110816     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
110817   }
110818
110819   if( rc==SQLITE_OK ){
110820     rc = nodeRelease(pRtree, pRight);
110821     pRight = 0;
110822   }
110823   if( rc==SQLITE_OK ){
110824     rc = nodeRelease(pRtree, pLeft);
110825     pLeft = 0;
110826   }
110827
110828 splitnode_out:
110829   nodeRelease(pRtree, pRight);
110830   nodeRelease(pRtree, pLeft);
110831   sqlite3_free(aCell);
110832   return rc;
110833 }
110834
110835 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
110836   int rc = SQLITE_OK;
110837   if( pLeaf->iNode!=1 && pLeaf->pParent==0 ){
110838     sqlite3_bind_int64(pRtree->pReadParent, 1, pLeaf->iNode);
110839     if( sqlite3_step(pRtree->pReadParent)==SQLITE_ROW ){
110840       i64 iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
110841       rc = nodeAcquire(pRtree, iNode, 0, &pLeaf->pParent);
110842     }else{
110843       rc = SQLITE_ERROR;
110844     }
110845     sqlite3_reset(pRtree->pReadParent);
110846     if( rc==SQLITE_OK ){
110847       rc = fixLeafParent(pRtree, pLeaf->pParent);
110848     }
110849   }
110850   return rc;
110851 }
110852
110853 static int deleteCell(Rtree *, RtreeNode *, int, int);
110854
110855 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
110856   int rc;
110857   RtreeNode *pParent;
110858   int iCell;
110859
110860   assert( pNode->nRef==1 );
110861
110862   /* Remove the entry in the parent cell. */
110863   iCell = nodeParentIndex(pRtree, pNode);
110864   pParent = pNode->pParent;
110865   pNode->pParent = 0;
110866   if( SQLITE_OK!=(rc = deleteCell(pRtree, pParent, iCell, iHeight+1)) 
110867    || SQLITE_OK!=(rc = nodeRelease(pRtree, pParent))
110868   ){
110869     return rc;
110870   }
110871
110872   /* Remove the xxx_node entry. */
110873   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
110874   sqlite3_step(pRtree->pDeleteNode);
110875   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
110876     return rc;
110877   }
110878
110879   /* Remove the xxx_parent entry. */
110880   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
110881   sqlite3_step(pRtree->pDeleteParent);
110882   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
110883     return rc;
110884   }
110885   
110886   /* Remove the node from the in-memory hash table and link it into
110887   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
110888   */
110889   nodeHashDelete(pRtree, pNode);
110890   pNode->iNode = iHeight;
110891   pNode->pNext = pRtree->pDeleted;
110892   pNode->nRef++;
110893   pRtree->pDeleted = pNode;
110894
110895   return SQLITE_OK;
110896 }
110897
110898 static void fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
110899   RtreeNode *pParent = pNode->pParent;
110900   if( pParent ){
110901     int ii; 
110902     int nCell = NCELL(pNode);
110903     RtreeCell box;                            /* Bounding box for pNode */
110904     nodeGetCell(pRtree, pNode, 0, &box);
110905     for(ii=1; ii<nCell; ii++){
110906       RtreeCell cell;
110907       nodeGetCell(pRtree, pNode, ii, &cell);
110908       cellUnion(pRtree, &box, &cell);
110909     }
110910     box.iRowid = pNode->iNode;
110911     ii = nodeParentIndex(pRtree, pNode);
110912     nodeOverwriteCell(pRtree, pParent, &box, ii);
110913     fixBoundingBox(pRtree, pParent);
110914   }
110915 }
110916
110917 /*
110918 ** Delete the cell at index iCell of node pNode. After removing the
110919 ** cell, adjust the r-tree data structure if required.
110920 */
110921 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
110922   int rc;
110923
110924   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
110925     return rc;
110926   }
110927
110928   /* Remove the cell from the node. This call just moves bytes around
110929   ** the in-memory node image, so it cannot fail.
110930   */
110931   nodeDeleteCell(pRtree, pNode, iCell);
110932
110933   /* If the node is not the tree root and now has less than the minimum
110934   ** number of cells, remove it from the tree. Otherwise, update the
110935   ** cell in the parent node so that it tightly contains the updated
110936   ** node.
110937   */
110938   if( pNode->iNode!=1 ){
110939     RtreeNode *pParent = pNode->pParent;
110940     if( (pParent->iNode!=1 || NCELL(pParent)!=1) 
110941      && (NCELL(pNode)<RTREE_MINCELLS(pRtree))
110942     ){
110943       rc = removeNode(pRtree, pNode, iHeight);
110944     }else{
110945       fixBoundingBox(pRtree, pNode);
110946     }
110947   }
110948
110949   return rc;
110950 }
110951
110952 static int Reinsert(
110953   Rtree *pRtree, 
110954   RtreeNode *pNode, 
110955   RtreeCell *pCell, 
110956   int iHeight
110957 ){
110958   int *aOrder;
110959   int *aSpare;
110960   RtreeCell *aCell;
110961   float *aDistance;
110962   int nCell;
110963   float aCenterCoord[RTREE_MAX_DIMENSIONS];
110964   int iDim;
110965   int ii;
110966   int rc = SQLITE_OK;
110967
110968   memset(aCenterCoord, 0, sizeof(float)*RTREE_MAX_DIMENSIONS);
110969
110970   nCell = NCELL(pNode)+1;
110971
110972   /* Allocate the buffers used by this operation. The allocation is
110973   ** relinquished before this function returns.
110974   */
110975   aCell = (RtreeCell *)sqlite3_malloc(nCell * (
110976     sizeof(RtreeCell) +         /* aCell array */
110977     sizeof(int)       +         /* aOrder array */
110978     sizeof(int)       +         /* aSpare array */
110979     sizeof(float)               /* aDistance array */
110980   ));
110981   if( !aCell ){
110982     return SQLITE_NOMEM;
110983   }
110984   aOrder    = (int *)&aCell[nCell];
110985   aSpare    = (int *)&aOrder[nCell];
110986   aDistance = (float *)&aSpare[nCell];
110987
110988   for(ii=0; ii<nCell; ii++){
110989     if( ii==(nCell-1) ){
110990       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
110991     }else{
110992       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
110993     }
110994     aOrder[ii] = ii;
110995     for(iDim=0; iDim<pRtree->nDim; iDim++){
110996       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
110997       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
110998     }
110999   }
111000   for(iDim=0; iDim<pRtree->nDim; iDim++){
111001     aCenterCoord[iDim] = aCenterCoord[iDim]/((float)nCell*2.0);
111002   }
111003
111004   for(ii=0; ii<nCell; ii++){
111005     aDistance[ii] = 0.0;
111006     for(iDim=0; iDim<pRtree->nDim; iDim++){
111007       float coord = DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
111008           DCOORD(aCell[ii].aCoord[iDim*2]);
111009       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
111010     }
111011   }
111012
111013   SortByDistance(aOrder, nCell, aDistance, aSpare);
111014   nodeZero(pRtree, pNode);
111015
111016   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
111017     RtreeCell *p = &aCell[aOrder[ii]];
111018     nodeInsertCell(pRtree, pNode, p);
111019     if( p->iRowid==pCell->iRowid ){
111020       if( iHeight==0 ){
111021         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
111022       }else{
111023         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
111024       }
111025     }
111026   }
111027   if( rc==SQLITE_OK ){
111028     fixBoundingBox(pRtree, pNode);
111029   }
111030   for(; rc==SQLITE_OK && ii<nCell; ii++){
111031     /* Find a node to store this cell in. pNode->iNode currently contains
111032     ** the height of the sub-tree headed by the cell.
111033     */
111034     RtreeNode *pInsert;
111035     RtreeCell *p = &aCell[aOrder[ii]];
111036     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
111037     if( rc==SQLITE_OK ){
111038       int rc2;
111039       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
111040       rc2 = nodeRelease(pRtree, pInsert);
111041       if( rc==SQLITE_OK ){
111042         rc = rc2;
111043       }
111044     }
111045   }
111046
111047   sqlite3_free(aCell);
111048   return rc;
111049 }
111050
111051 /*
111052 ** Insert cell pCell into node pNode. Node pNode is the head of a 
111053 ** subtree iHeight high (leaf nodes have iHeight==0).
111054 */
111055 static int rtreeInsertCell(
111056   Rtree *pRtree,
111057   RtreeNode *pNode,
111058   RtreeCell *pCell,
111059   int iHeight
111060 ){
111061   int rc = SQLITE_OK;
111062   if( iHeight>0 ){
111063     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
111064     if( pChild ){
111065       nodeRelease(pRtree, pChild->pParent);
111066       nodeReference(pNode);
111067       pChild->pParent = pNode;
111068     }
111069   }
111070   if( nodeInsertCell(pRtree, pNode, pCell) ){
111071 #if VARIANT_RSTARTREE_REINSERT
111072     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
111073       rc = SplitNode(pRtree, pNode, pCell, iHeight);
111074     }else{
111075       pRtree->iReinsertHeight = iHeight;
111076       rc = Reinsert(pRtree, pNode, pCell, iHeight);
111077     }
111078 #else
111079     rc = SplitNode(pRtree, pNode, pCell, iHeight);
111080 #endif
111081   }else{
111082     AdjustTree(pRtree, pNode, pCell);
111083     if( iHeight==0 ){
111084       rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
111085     }else{
111086       rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
111087     }
111088   }
111089   return rc;
111090 }
111091
111092 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
111093   int ii;
111094   int rc = SQLITE_OK;
111095   int nCell = NCELL(pNode);
111096
111097   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
111098     RtreeNode *pInsert;
111099     RtreeCell cell;
111100     nodeGetCell(pRtree, pNode, ii, &cell);
111101
111102     /* Find a node to store this cell in. pNode->iNode currently contains
111103     ** the height of the sub-tree headed by the cell.
111104     */
111105     rc = ChooseLeaf(pRtree, &cell, pNode->iNode, &pInsert);
111106     if( rc==SQLITE_OK ){
111107       int rc2;
111108       rc = rtreeInsertCell(pRtree, pInsert, &cell, pNode->iNode);
111109       rc2 = nodeRelease(pRtree, pInsert);
111110       if( rc==SQLITE_OK ){
111111         rc = rc2;
111112       }
111113     }
111114   }
111115   return rc;
111116 }
111117
111118 /*
111119 ** Select a currently unused rowid for a new r-tree record.
111120 */
111121 static int newRowid(Rtree *pRtree, i64 *piRowid){
111122   int rc;
111123   sqlite3_bind_null(pRtree->pWriteRowid, 1);
111124   sqlite3_bind_null(pRtree->pWriteRowid, 2);
111125   sqlite3_step(pRtree->pWriteRowid);
111126   rc = sqlite3_reset(pRtree->pWriteRowid);
111127   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
111128   return rc;
111129 }
111130
111131 #ifndef NDEBUG
111132 static int hashIsEmpty(Rtree *pRtree){
111133   int ii;
111134   for(ii=0; ii<HASHSIZE; ii++){
111135     assert( !pRtree->aHash[ii] );
111136   }
111137   return 1;
111138 }
111139 #endif
111140
111141 /*
111142 ** The xUpdate method for rtree module virtual tables.
111143 */
111144 static int rtreeUpdate(
111145   sqlite3_vtab *pVtab, 
111146   int nData, 
111147   sqlite3_value **azData, 
111148   sqlite_int64 *pRowid
111149 ){
111150   Rtree *pRtree = (Rtree *)pVtab;
111151   int rc = SQLITE_OK;
111152
111153   rtreeReference(pRtree);
111154
111155   assert(nData>=1);
111156   assert(hashIsEmpty(pRtree));
111157
111158   /* If azData[0] is not an SQL NULL value, it is the rowid of a
111159   ** record to delete from the r-tree table. The following block does
111160   ** just that.
111161   */
111162   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
111163     i64 iDelete;                /* The rowid to delete */
111164     RtreeNode *pLeaf;           /* Leaf node containing record iDelete */
111165     int iCell;                  /* Index of iDelete cell in pLeaf */
111166     RtreeNode *pRoot;
111167
111168     /* Obtain a reference to the root node to initialise Rtree.iDepth */
111169     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
111170
111171     /* Obtain a reference to the leaf node that contains the entry 
111172     ** about to be deleted. 
111173     */
111174     if( rc==SQLITE_OK ){
111175       iDelete = sqlite3_value_int64(azData[0]);
111176       rc = findLeafNode(pRtree, iDelete, &pLeaf);
111177     }
111178
111179     /* Delete the cell in question from the leaf node. */
111180     if( rc==SQLITE_OK ){
111181       int rc2;
111182       iCell = nodeRowidIndex(pRtree, pLeaf, iDelete);
111183       rc = deleteCell(pRtree, pLeaf, iCell, 0);
111184       rc2 = nodeRelease(pRtree, pLeaf);
111185       if( rc==SQLITE_OK ){
111186         rc = rc2;
111187       }
111188     }
111189
111190     /* Delete the corresponding entry in the <rtree>_rowid table. */
111191     if( rc==SQLITE_OK ){
111192       sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
111193       sqlite3_step(pRtree->pDeleteRowid);
111194       rc = sqlite3_reset(pRtree->pDeleteRowid);
111195     }
111196
111197     /* Check if the root node now has exactly one child. If so, remove
111198     ** it, schedule the contents of the child for reinsertion and 
111199     ** reduce the tree height by one.
111200     **
111201     ** This is equivalent to copying the contents of the child into
111202     ** the root node (the operation that Gutman's paper says to perform 
111203     ** in this scenario).
111204     */
111205     if( rc==SQLITE_OK && pRtree->iDepth>0 ){
111206       if( rc==SQLITE_OK && NCELL(pRoot)==1 ){
111207         RtreeNode *pChild;
111208         i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
111209         rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
111210         if( rc==SQLITE_OK ){
111211           rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
111212         }
111213         if( rc==SQLITE_OK ){
111214           pRtree->iDepth--;
111215           writeInt16(pRoot->zData, pRtree->iDepth);
111216           pRoot->isDirty = 1;
111217         }
111218       }
111219     }
111220
111221     /* Re-insert the contents of any underfull nodes removed from the tree. */
111222     for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
111223       if( rc==SQLITE_OK ){
111224         rc = reinsertNodeContent(pRtree, pLeaf);
111225       }
111226       pRtree->pDeleted = pLeaf->pNext;
111227       sqlite3_free(pLeaf);
111228     }
111229
111230     /* Release the reference to the root node. */
111231     if( rc==SQLITE_OK ){
111232       rc = nodeRelease(pRtree, pRoot);
111233     }else{
111234       nodeRelease(pRtree, pRoot);
111235     }
111236   }
111237
111238   /* If the azData[] array contains more than one element, elements
111239   ** (azData[2]..azData[argc-1]) contain a new record to insert into
111240   ** the r-tree structure.
111241   */
111242   if( rc==SQLITE_OK && nData>1 ){
111243     /* Insert a new record into the r-tree */
111244     RtreeCell cell;
111245     int ii;
111246     RtreeNode *pLeaf;
111247
111248     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
111249     assert( nData==(pRtree->nDim*2 + 3) );
111250     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
111251       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
111252         cell.aCoord[ii].f = (float)sqlite3_value_double(azData[ii+3]);
111253         cell.aCoord[ii+1].f = (float)sqlite3_value_double(azData[ii+4]);
111254         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
111255           rc = SQLITE_CONSTRAINT;
111256           goto constraint;
111257         }
111258       }
111259     }else{
111260       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
111261         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
111262         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
111263         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
111264           rc = SQLITE_CONSTRAINT;
111265           goto constraint;
111266         }
111267       }
111268     }
111269
111270     /* Figure out the rowid of the new row. */
111271     if( sqlite3_value_type(azData[2])==SQLITE_NULL ){
111272       rc = newRowid(pRtree, &cell.iRowid);
111273     }else{
111274       cell.iRowid = sqlite3_value_int64(azData[2]);
111275       sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
111276       if( SQLITE_ROW==sqlite3_step(pRtree->pReadRowid) ){
111277         sqlite3_reset(pRtree->pReadRowid);
111278         rc = SQLITE_CONSTRAINT;
111279         goto constraint;
111280       }
111281       rc = sqlite3_reset(pRtree->pReadRowid);
111282     }
111283
111284     if( rc==SQLITE_OK ){
111285       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
111286     }
111287     if( rc==SQLITE_OK ){
111288       int rc2;
111289       pRtree->iReinsertHeight = -1;
111290       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
111291       rc2 = nodeRelease(pRtree, pLeaf);
111292       if( rc==SQLITE_OK ){
111293         rc = rc2;
111294       }
111295     }
111296   }
111297
111298 constraint:
111299   rtreeRelease(pRtree);
111300   return rc;
111301 }
111302
111303 /*
111304 ** The xRename method for rtree module virtual tables.
111305 */
111306 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
111307   Rtree *pRtree = (Rtree *)pVtab;
111308   int rc = SQLITE_NOMEM;
111309   char *zSql = sqlite3_mprintf(
111310     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
111311     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
111312     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
111313     , pRtree->zDb, pRtree->zName, zNewName 
111314     , pRtree->zDb, pRtree->zName, zNewName 
111315     , pRtree->zDb, pRtree->zName, zNewName
111316   );
111317   if( zSql ){
111318     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
111319     sqlite3_free(zSql);
111320   }
111321   return rc;
111322 }
111323
111324 static sqlite3_module rtreeModule = {
111325   0,                         /* iVersion */
111326   rtreeCreate,                /* xCreate - create a table */
111327   rtreeConnect,               /* xConnect - connect to an existing table */
111328   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
111329   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
111330   rtreeDestroy,               /* xDestroy - Drop a table */
111331   rtreeOpen,                  /* xOpen - open a cursor */
111332   rtreeClose,                 /* xClose - close a cursor */
111333   rtreeFilter,                /* xFilter - configure scan constraints */
111334   rtreeNext,                  /* xNext - advance a cursor */
111335   rtreeEof,                   /* xEof */
111336   rtreeColumn,                /* xColumn - read data */
111337   rtreeRowid,                 /* xRowid - read data */
111338   rtreeUpdate,                /* xUpdate - write data */
111339   0,                          /* xBegin - begin transaction */
111340   0,                          /* xSync - sync transaction */
111341   0,                          /* xCommit - commit transaction */
111342   0,                          /* xRollback - rollback transaction */
111343   0,                          /* xFindFunction - function overloading */
111344   rtreeRename                 /* xRename - rename the table */
111345 };
111346
111347 static int rtreeSqlInit(
111348   Rtree *pRtree, 
111349   sqlite3 *db, 
111350   const char *zDb, 
111351   const char *zPrefix, 
111352   int isCreate
111353 ){
111354   int rc = SQLITE_OK;
111355
111356   #define N_STATEMENT 9
111357   static const char *azSql[N_STATEMENT] = {
111358     /* Read and write the xxx_node table */
111359     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
111360     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
111361     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
111362
111363     /* Read and write the xxx_rowid table */
111364     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
111365     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
111366     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
111367
111368     /* Read and write the xxx_parent table */
111369     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
111370     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
111371     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
111372   };
111373   sqlite3_stmt **appStmt[N_STATEMENT];
111374   int i;
111375
111376   pRtree->db = db;
111377
111378   if( isCreate ){
111379     char *zCreate = sqlite3_mprintf(
111380 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
111381 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
111382 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY, parentnode INTEGER);"
111383 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
111384       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
111385     );
111386     if( !zCreate ){
111387       return SQLITE_NOMEM;
111388     }
111389     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
111390     sqlite3_free(zCreate);
111391     if( rc!=SQLITE_OK ){
111392       return rc;
111393     }
111394   }
111395
111396   appStmt[0] = &pRtree->pReadNode;
111397   appStmt[1] = &pRtree->pWriteNode;
111398   appStmt[2] = &pRtree->pDeleteNode;
111399   appStmt[3] = &pRtree->pReadRowid;
111400   appStmt[4] = &pRtree->pWriteRowid;
111401   appStmt[5] = &pRtree->pDeleteRowid;
111402   appStmt[6] = &pRtree->pReadParent;
111403   appStmt[7] = &pRtree->pWriteParent;
111404   appStmt[8] = &pRtree->pDeleteParent;
111405
111406   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
111407     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
111408     if( zSql ){
111409       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
111410     }else{
111411       rc = SQLITE_NOMEM;
111412     }
111413     sqlite3_free(zSql);
111414   }
111415
111416   return rc;
111417 }
111418
111419 /*
111420 ** The second argument to this function contains the text of an SQL statement
111421 ** that returns a single integer value. The statement is compiled and executed
111422 ** using database connection db. If successful, the integer value returned
111423 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
111424 ** code is returned and the value of *piVal after returning is not defined.
111425 */
111426 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
111427   int rc = SQLITE_NOMEM;
111428   if( zSql ){
111429     sqlite3_stmt *pStmt = 0;
111430     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
111431     if( rc==SQLITE_OK ){
111432       if( SQLITE_ROW==sqlite3_step(pStmt) ){
111433         *piVal = sqlite3_column_int(pStmt, 0);
111434       }
111435       rc = sqlite3_finalize(pStmt);
111436     }
111437   }
111438   return rc;
111439 }
111440
111441 /*
111442 ** This function is called from within the xConnect() or xCreate() method to
111443 ** determine the node-size used by the rtree table being created or connected
111444 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
111445 ** Otherwise, an SQLite error code is returned.
111446 **
111447 ** If this function is being called as part of an xConnect(), then the rtree
111448 ** table already exists. In this case the node-size is determined by inspecting
111449 ** the root node of the tree.
111450 **
111451 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 
111452 ** This ensures that each node is stored on a single database page. If the 
111453 ** database page-size is so large that more than RTREE_MAXCELLS entries 
111454 ** would fit in a single node, use a smaller node-size.
111455 */
111456 static int getNodeSize(
111457   sqlite3 *db,                    /* Database handle */
111458   Rtree *pRtree,                  /* Rtree handle */
111459   int isCreate                    /* True for xCreate, false for xConnect */
111460 ){
111461   int rc;
111462   char *zSql;
111463   if( isCreate ){
111464     int iPageSize;
111465     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
111466     rc = getIntFromStmt(db, zSql, &iPageSize);
111467     if( rc==SQLITE_OK ){
111468       pRtree->iNodeSize = iPageSize-64;
111469       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
111470         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
111471       }
111472     }
111473   }else{
111474     zSql = sqlite3_mprintf(
111475         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
111476         pRtree->zDb, pRtree->zName
111477     );
111478     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
111479   }
111480
111481   sqlite3_free(zSql);
111482   return rc;
111483 }
111484
111485 /* 
111486 ** This function is the implementation of both the xConnect and xCreate
111487 ** methods of the r-tree virtual table.
111488 **
111489 **   argv[0]   -> module name
111490 **   argv[1]   -> database name
111491 **   argv[2]   -> table name
111492 **   argv[...] -> column names...
111493 */
111494 static int rtreeInit(
111495   sqlite3 *db,                        /* Database connection */
111496   void *pAux,                         /* One of the RTREE_COORD_* constants */
111497   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
111498   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
111499   char **pzErr,                       /* OUT: Error message, if any */
111500   int isCreate                        /* True for xCreate, false for xConnect */
111501 ){
111502   int rc = SQLITE_OK;
111503   Rtree *pRtree;
111504   int nDb;              /* Length of string argv[1] */
111505   int nName;            /* Length of string argv[2] */
111506   int eCoordType = (int)pAux;
111507
111508   const char *aErrMsg[] = {
111509     0,                                                    /* 0 */
111510     "Wrong number of columns for an rtree table",         /* 1 */
111511     "Too few columns for an rtree table",                 /* 2 */
111512     "Too many columns for an rtree table"                 /* 3 */
111513   };
111514
111515   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
111516   if( aErrMsg[iErr] ){
111517     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
111518     return SQLITE_ERROR;
111519   }
111520
111521   /* Allocate the sqlite3_vtab structure */
111522   nDb = strlen(argv[1]);
111523   nName = strlen(argv[2]);
111524   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
111525   if( !pRtree ){
111526     return SQLITE_NOMEM;
111527   }
111528   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
111529   pRtree->nBusy = 1;
111530   pRtree->base.pModule = &rtreeModule;
111531   pRtree->zDb = (char *)&pRtree[1];
111532   pRtree->zName = &pRtree->zDb[nDb+1];
111533   pRtree->nDim = (argc-4)/2;
111534   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
111535   pRtree->eCoordType = eCoordType;
111536   memcpy(pRtree->zDb, argv[1], nDb);
111537   memcpy(pRtree->zName, argv[2], nName);
111538
111539   /* Figure out the node size to use. */
111540   rc = getNodeSize(db, pRtree, isCreate);
111541
111542   /* Create/Connect to the underlying relational database schema. If
111543   ** that is successful, call sqlite3_declare_vtab() to configure
111544   ** the r-tree table schema.
111545   */
111546   if( rc==SQLITE_OK ){
111547     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
111548       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
111549     }else{
111550       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
111551       char *zTmp;
111552       int ii;
111553       for(ii=4; zSql && ii<argc; ii++){
111554         zTmp = zSql;
111555         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
111556         sqlite3_free(zTmp);
111557       }
111558       if( zSql ){
111559         zTmp = zSql;
111560         zSql = sqlite3_mprintf("%s);", zTmp);
111561         sqlite3_free(zTmp);
111562       }
111563       if( !zSql ){
111564         rc = SQLITE_NOMEM;
111565       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
111566         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
111567       }
111568       sqlite3_free(zSql);
111569     }
111570   }
111571
111572   if( rc==SQLITE_OK ){
111573     *ppVtab = (sqlite3_vtab *)pRtree;
111574   }else{
111575     rtreeRelease(pRtree);
111576   }
111577   return rc;
111578 }
111579
111580
111581 /*
111582 ** Implementation of a scalar function that decodes r-tree nodes to
111583 ** human readable strings. This can be used for debugging and analysis.
111584 **
111585 ** The scalar function takes two arguments, a blob of data containing
111586 ** an r-tree node, and the number of dimensions the r-tree indexes.
111587 ** For a two-dimensional r-tree structure called "rt", to deserialize
111588 ** all nodes, a statement like:
111589 **
111590 **   SELECT rtreenode(2, data) FROM rt_node;
111591 **
111592 ** The human readable string takes the form of a Tcl list with one
111593 ** entry for each cell in the r-tree node. Each entry is itself a
111594 ** list, containing the 8-byte rowid/pageno followed by the 
111595 ** <num-dimension>*2 coordinates.
111596 */
111597 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
111598   char *zText = 0;
111599   RtreeNode node;
111600   Rtree tree;
111601   int ii;
111602
111603   memset(&node, 0, sizeof(RtreeNode));
111604   memset(&tree, 0, sizeof(Rtree));
111605   tree.nDim = sqlite3_value_int(apArg[0]);
111606   tree.nBytesPerCell = 8 + 8 * tree.nDim;
111607   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
111608
111609   for(ii=0; ii<NCELL(&node); ii++){
111610     char zCell[512];
111611     int nCell = 0;
111612     RtreeCell cell;
111613     int jj;
111614
111615     nodeGetCell(&tree, &node, ii, &cell);
111616     sqlite3_snprintf(512-nCell,&zCell[nCell],"%d", cell.iRowid);
111617     nCell = strlen(zCell);
111618     for(jj=0; jj<tree.nDim*2; jj++){
111619       sqlite3_snprintf(512-nCell,&zCell[nCell]," %f",(double)cell.aCoord[jj].f);
111620       nCell = strlen(zCell);
111621     }
111622
111623     if( zText ){
111624       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
111625       sqlite3_free(zText);
111626       zText = zTextNew;
111627     }else{
111628       zText = sqlite3_mprintf("{%s}", zCell);
111629     }
111630   }
111631   
111632   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
111633 }
111634
111635 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
111636   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
111637    || sqlite3_value_bytes(apArg[0])<2
111638   ){
111639     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
111640   }else{
111641     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
111642     sqlite3_result_int(ctx, readInt16(zBlob));
111643   }
111644 }
111645
111646 /*
111647 ** Register the r-tree module with database handle db. This creates the
111648 ** virtual table module "rtree" and the debugging/analysis scalar 
111649 ** function "rtreenode".
111650 */
111651 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
111652   int rc = SQLITE_OK;
111653
111654   if( rc==SQLITE_OK ){
111655     int utf8 = SQLITE_UTF8;
111656     rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
111657   }
111658   if( rc==SQLITE_OK ){
111659     int utf8 = SQLITE_UTF8;
111660     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
111661   }
111662   if( rc==SQLITE_OK ){
111663     void *c = (void *)RTREE_COORD_REAL32;
111664     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
111665   }
111666   if( rc==SQLITE_OK ){
111667     void *c = (void *)RTREE_COORD_INT32;
111668     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
111669   }
111670
111671   return rc;
111672 }
111673
111674 #if !SQLITE_CORE
111675 SQLITE_API int sqlite3_extension_init(
111676   sqlite3 *db,
111677   char **pzErrMsg,
111678   const sqlite3_api_routines *pApi
111679 ){
111680   SQLITE_EXTENSION_INIT2(pApi)
111681   return sqlite3RtreeInit(db);
111682 }
111683 #endif
111684
111685 #endif
111686
111687 /************** End of rtree.c ***********************************************/
111688 /************** Begin file icu.c *********************************************/
111689 /*
111690 ** 2007 May 6
111691 **
111692 ** The author disclaims copyright to this source code.  In place of
111693 ** a legal notice, here is a blessing:
111694 **
111695 **    May you do good and not evil.
111696 **    May you find forgiveness for yourself and forgive others.
111697 **    May you share freely, never taking more than you give.
111698 **
111699 *************************************************************************
111700 ** $Id: sqlite3.c,v 1.1 2010/06/07 15:40:31 cervenansky Exp $
111701 **
111702 ** This file implements an integration between the ICU library 
111703 ** ("International Components for Unicode", an open-source library 
111704 ** for handling unicode data) and SQLite. The integration uses 
111705 ** ICU to provide the following to SQLite:
111706 **
111707 **   * An implementation of the SQL regexp() function (and hence REGEXP
111708 **     operator) using the ICU uregex_XX() APIs.
111709 **
111710 **   * Implementations of the SQL scalar upper() and lower() functions
111711 **     for case mapping.
111712 **
111713 **   * Integration of ICU and SQLite collation seqences.
111714 **
111715 **   * An implementation of the LIKE operator that uses ICU to 
111716 **     provide case-independent matching.
111717 */
111718
111719 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
111720
111721 /* Include ICU headers */
111722 #include <unicode/utypes.h>
111723 #include <unicode/uregex.h>
111724 #include <unicode/ustring.h>
111725 #include <unicode/ucol.h>
111726
111727
111728 #ifndef SQLITE_CORE
111729   SQLITE_EXTENSION_INIT1
111730 #else
111731 #endif
111732
111733 /*
111734 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
111735 ** operator.
111736 */
111737 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
111738 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
111739 #endif
111740
111741 /*
111742 ** Version of sqlite3_free() that is always a function, never a macro.
111743 */
111744 static void xFree(void *p){
111745   sqlite3_free(p);
111746 }
111747
111748 /*
111749 ** Compare two UTF-8 strings for equality where the first string is
111750 ** a "LIKE" expression. Return true (1) if they are the same and 
111751 ** false (0) if they are different.
111752 */
111753 static int icuLikeCompare(
111754   const uint8_t *zPattern,   /* LIKE pattern */
111755   const uint8_t *zString,    /* The UTF-8 string to compare against */
111756   const UChar32 uEsc         /* The escape character */
111757 ){
111758   static const int MATCH_ONE = (UChar32)'_';
111759   static const int MATCH_ALL = (UChar32)'%';
111760
111761   int iPattern = 0;       /* Current byte index in zPattern */
111762   int iString = 0;        /* Current byte index in zString */
111763
111764   int prevEscape = 0;     /* True if the previous character was uEsc */
111765
111766   while( zPattern[iPattern]!=0 ){
111767
111768     /* Read (and consume) the next character from the input pattern. */
111769     UChar32 uPattern;
111770     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
111771     assert(uPattern!=0);
111772
111773     /* There are now 4 possibilities:
111774     **
111775     **     1. uPattern is an unescaped match-all character "%",
111776     **     2. uPattern is an unescaped match-one character "_",
111777     **     3. uPattern is an unescaped escape character, or
111778     **     4. uPattern is to be handled as an ordinary character
111779     */
111780     if( !prevEscape && uPattern==MATCH_ALL ){
111781       /* Case 1. */
111782       uint8_t c;
111783
111784       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
111785       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
111786       ** test string.
111787       */
111788       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
111789         if( c==MATCH_ONE ){
111790           if( zString[iString]==0 ) return 0;
111791           U8_FWD_1_UNSAFE(zString, iString);
111792         }
111793         iPattern++;
111794       }
111795
111796       if( zPattern[iPattern]==0 ) return 1;
111797
111798       while( zString[iString] ){
111799         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
111800           return 1;
111801         }
111802         U8_FWD_1_UNSAFE(zString, iString);
111803       }
111804       return 0;
111805
111806     }else if( !prevEscape && uPattern==MATCH_ONE ){
111807       /* Case 2. */
111808       if( zString[iString]==0 ) return 0;
111809       U8_FWD_1_UNSAFE(zString, iString);
111810
111811     }else if( !prevEscape && uPattern==uEsc){
111812       /* Case 3. */
111813       prevEscape = 1;
111814
111815     }else{
111816       /* Case 4. */
111817       UChar32 uString;
111818       U8_NEXT_UNSAFE(zString, iString, uString);
111819       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
111820       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
111821       if( uString!=uPattern ){
111822         return 0;
111823       }
111824       prevEscape = 0;
111825     }
111826   }
111827
111828   return zString[iString]==0;
111829 }
111830
111831 /*
111832 ** Implementation of the like() SQL function.  This function implements
111833 ** the build-in LIKE operator.  The first argument to the function is the
111834 ** pattern and the second argument is the string.  So, the SQL statements:
111835 **
111836 **       A LIKE B
111837 **
111838 ** is implemented as like(B, A). If there is an escape character E, 
111839 **
111840 **       A LIKE B ESCAPE E
111841 **
111842 ** is mapped to like(B, A, E).
111843 */
111844 static void icuLikeFunc(
111845   sqlite3_context *context, 
111846   int argc, 
111847   sqlite3_value **argv
111848 ){
111849   const unsigned char *zA = sqlite3_value_text(argv[0]);
111850   const unsigned char *zB = sqlite3_value_text(argv[1]);
111851   UChar32 uEsc = 0;
111852
111853   /* Limit the length of the LIKE or GLOB pattern to avoid problems
111854   ** of deep recursion and N*N behavior in patternCompare().
111855   */
111856   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
111857     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
111858     return;
111859   }
111860
111861
111862   if( argc==3 ){
111863     /* The escape character string must consist of a single UTF-8 character.
111864     ** Otherwise, return an error.
111865     */
111866     int nE= sqlite3_value_bytes(argv[2]);
111867     const unsigned char *zE = sqlite3_value_text(argv[2]);
111868     int i = 0;
111869     if( zE==0 ) return;
111870     U8_NEXT(zE, i, nE, uEsc);
111871     if( i!=nE){
111872       sqlite3_result_error(context, 
111873           "ESCAPE expression must be a single character", -1);
111874       return;
111875     }
111876   }
111877
111878   if( zA && zB ){
111879     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
111880   }
111881 }
111882
111883 /*
111884 ** This function is called when an ICU function called from within
111885 ** the implementation of an SQL scalar function returns an error.
111886 **
111887 ** The scalar function context passed as the first argument is 
111888 ** loaded with an error message based on the following two args.
111889 */
111890 static void icuFunctionError(
111891   sqlite3_context *pCtx,       /* SQLite scalar function context */
111892   const char *zName,           /* Name of ICU function that failed */
111893   UErrorCode e                 /* Error code returned by ICU function */
111894 ){
111895   char zBuf[128];
111896   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
111897   zBuf[127] = '\0';
111898   sqlite3_result_error(pCtx, zBuf, -1);
111899 }
111900
111901 /*
111902 ** Function to delete compiled regexp objects. Registered as
111903 ** a destructor function with sqlite3_set_auxdata().
111904 */
111905 static void icuRegexpDelete(void *p){
111906   URegularExpression *pExpr = (URegularExpression *)p;
111907   uregex_close(pExpr);
111908 }
111909
111910 /*
111911 ** Implementation of SQLite REGEXP operator. This scalar function takes
111912 ** two arguments. The first is a regular expression pattern to compile
111913 ** the second is a string to match against that pattern. If either 
111914 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
111915 ** is 1 if the string matches the pattern, or 0 otherwise.
111916 **
111917 ** SQLite maps the regexp() function to the regexp() operator such
111918 ** that the following two are equivalent:
111919 **
111920 **     zString REGEXP zPattern
111921 **     regexp(zPattern, zString)
111922 **
111923 ** Uses the following ICU regexp APIs:
111924 **
111925 **     uregex_open()
111926 **     uregex_matches()
111927 **     uregex_close()
111928 */
111929 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
111930   UErrorCode status = U_ZERO_ERROR;
111931   URegularExpression *pExpr;
111932   UBool res;
111933   const UChar *zString = sqlite3_value_text16(apArg[1]);
111934
111935   /* If the left hand side of the regexp operator is NULL, 
111936   ** then the result is also NULL. 
111937   */
111938   if( !zString ){
111939     return;
111940   }
111941
111942   pExpr = sqlite3_get_auxdata(p, 0);
111943   if( !pExpr ){
111944     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
111945     if( !zPattern ){
111946       return;
111947     }
111948     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
111949
111950     if( U_SUCCESS(status) ){
111951       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
111952     }else{
111953       assert(!pExpr);
111954       icuFunctionError(p, "uregex_open", status);
111955       return;
111956     }
111957   }
111958
111959   /* Configure the text that the regular expression operates on. */
111960   uregex_setText(pExpr, zString, -1, &status);
111961   if( !U_SUCCESS(status) ){
111962     icuFunctionError(p, "uregex_setText", status);
111963     return;
111964   }
111965
111966   /* Attempt the match */
111967   res = uregex_matches(pExpr, 0, &status);
111968   if( !U_SUCCESS(status) ){
111969     icuFunctionError(p, "uregex_matches", status);
111970     return;
111971   }
111972
111973   /* Set the text that the regular expression operates on to a NULL
111974   ** pointer. This is not really necessary, but it is tidier than 
111975   ** leaving the regular expression object configured with an invalid
111976   ** pointer after this function returns.
111977   */
111978   uregex_setText(pExpr, 0, 0, &status);
111979
111980   /* Return 1 or 0. */
111981   sqlite3_result_int(p, res ? 1 : 0);
111982 }
111983
111984 /*
111985 ** Implementations of scalar functions for case mapping - upper() and 
111986 ** lower(). Function upper() converts its input to upper-case (ABC).
111987 ** Function lower() converts to lower-case (abc).
111988 **
111989 ** ICU provides two types of case mapping, "general" case mapping and
111990 ** "language specific". Refer to ICU documentation for the differences
111991 ** between the two.
111992 **
111993 ** To utilise "general" case mapping, the upper() or lower() scalar 
111994 ** functions are invoked with one argument:
111995 **
111996 **     upper('ABC') -> 'abc'
111997 **     lower('abc') -> 'ABC'
111998 **
111999 ** To access ICU "language specific" case mapping, upper() or lower()
112000 ** should be invoked with two arguments. The second argument is the name
112001 ** of the locale to use. Passing an empty string ("") or SQL NULL value
112002 ** as the second argument is the same as invoking the 1 argument version
112003 ** of upper() or lower().
112004 **
112005 **     lower('I', 'en_us') -> 'i'
112006 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
112007 **
112008 ** http://www.icu-project.org/userguide/posix.html#case_mappings
112009 */
112010 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
112011   const UChar *zInput;
112012   UChar *zOutput;
112013   int nInput;
112014   int nOutput;
112015
112016   UErrorCode status = U_ZERO_ERROR;
112017   const char *zLocale = 0;
112018
112019   assert(nArg==1 || nArg==2);
112020   if( nArg==2 ){
112021     zLocale = (const char *)sqlite3_value_text(apArg[1]);
112022   }
112023
112024   zInput = sqlite3_value_text16(apArg[0]);
112025   if( !zInput ){
112026     return;
112027   }
112028   nInput = sqlite3_value_bytes16(apArg[0]);
112029
112030   nOutput = nInput * 2 + 2;
112031   zOutput = sqlite3_malloc(nOutput);
112032   if( !zOutput ){
112033     return;
112034   }
112035
112036   if( sqlite3_user_data(p) ){
112037     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
112038   }else{
112039     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
112040   }
112041
112042   if( !U_SUCCESS(status) ){
112043     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
112044     return;
112045   }
112046
112047   sqlite3_result_text16(p, zOutput, -1, xFree);
112048 }
112049
112050 /*
112051 ** Collation sequence destructor function. The pCtx argument points to
112052 ** a UCollator structure previously allocated using ucol_open().
112053 */
112054 static void icuCollationDel(void *pCtx){
112055   UCollator *p = (UCollator *)pCtx;
112056   ucol_close(p);
112057 }
112058
112059 /*
112060 ** Collation sequence comparison function. The pCtx argument points to
112061 ** a UCollator structure previously allocated using ucol_open().
112062 */
112063 static int icuCollationColl(
112064   void *pCtx,
112065   int nLeft,
112066   const void *zLeft,
112067   int nRight,
112068   const void *zRight
112069 ){
112070   UCollationResult res;
112071   UCollator *p = (UCollator *)pCtx;
112072   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
112073   switch( res ){
112074     case UCOL_LESS:    return -1;
112075     case UCOL_GREATER: return +1;
112076     case UCOL_EQUAL:   return 0;
112077   }
112078   assert(!"Unexpected return value from ucol_strcoll()");
112079   return 0;
112080 }
112081
112082 /*
112083 ** Implementation of the scalar function icu_load_collation().
112084 **
112085 ** This scalar function is used to add ICU collation based collation 
112086 ** types to an SQLite database connection. It is intended to be called
112087 ** as follows:
112088 **
112089 **     SELECT icu_load_collation(<locale>, <collation-name>);
112090 **
112091 ** Where <locale> is a string containing an ICU locale identifier (i.e.
112092 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
112093 ** collation sequence to create.
112094 */
112095 static void icuLoadCollation(
112096   sqlite3_context *p, 
112097   int nArg, 
112098   sqlite3_value **apArg
112099 ){
112100   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
112101   UErrorCode status = U_ZERO_ERROR;
112102   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
112103   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
112104   UCollator *pUCollator;    /* ICU library collation object */
112105   int rc;                   /* Return code from sqlite3_create_collation_x() */
112106
112107   assert(nArg==2);
112108   zLocale = (const char *)sqlite3_value_text(apArg[0]);
112109   zName = (const char *)sqlite3_value_text(apArg[1]);
112110
112111   if( !zLocale || !zName ){
112112     return;
112113   }
112114
112115   pUCollator = ucol_open(zLocale, &status);
112116   if( !U_SUCCESS(status) ){
112117     icuFunctionError(p, "ucol_open", status);
112118     return;
112119   }
112120   assert(p);
112121
112122   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
112123       icuCollationColl, icuCollationDel
112124   );
112125   if( rc!=SQLITE_OK ){
112126     ucol_close(pUCollator);
112127     sqlite3_result_error(p, "Error registering collation function", -1);
112128   }
112129 }
112130
112131 /*
112132 ** Register the ICU extension functions with database db.
112133 */
112134 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
112135   struct IcuScalar {
112136     const char *zName;                        /* Function name */
112137     int nArg;                                 /* Number of arguments */
112138     int enc;                                  /* Optimal text encoding */
112139     void *pContext;                           /* sqlite3_user_data() context */
112140     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
112141   } scalars[] = {
112142     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
112143
112144     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
112145     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
112146     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
112147     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
112148
112149     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
112150     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
112151     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
112152     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
112153
112154     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
112155     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
112156
112157     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
112158   };
112159
112160   int rc = SQLITE_OK;
112161   int i;
112162
112163   for(i=0; rc==SQLITE_OK && i<(sizeof(scalars)/sizeof(struct IcuScalar)); i++){
112164     struct IcuScalar *p = &scalars[i];
112165     rc = sqlite3_create_function(
112166         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
112167     );
112168   }
112169
112170   return rc;
112171 }
112172
112173 #if !SQLITE_CORE
112174 SQLITE_API int sqlite3_extension_init(
112175   sqlite3 *db, 
112176   char **pzErrMsg,
112177   const sqlite3_api_routines *pApi
112178 ){
112179   SQLITE_EXTENSION_INIT2(pApi)
112180   return sqlite3IcuInit(db);
112181 }
112182 #endif
112183
112184 #endif
112185
112186 /************** End of icu.c *************************************************/
112187 /************** Begin file fts3_icu.c ****************************************/
112188 /*
112189 ** 2007 June 22
112190 **
112191 ** The author disclaims copyright to this source code.  In place of
112192 ** a legal notice, here is a blessing:
112193 **
112194 **    May you do good and not evil.
112195 **    May you find forgiveness for yourself and forgive others.
112196 **    May you share freely, never taking more than you give.
112197 **
112198 *************************************************************************
112199 ** This file implements a tokenizer for fts3 based on the ICU library.
112200 ** 
112201 ** $Id: sqlite3.c,v 1.1 2010/06/07 15:40:31 cervenansky Exp $
112202 */
112203
112204 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
112205 #ifdef SQLITE_ENABLE_ICU
112206
112207
112208 #include <unicode/ubrk.h>
112209 #include <unicode/utf16.h>
112210
112211 typedef struct IcuTokenizer IcuTokenizer;
112212 typedef struct IcuCursor IcuCursor;
112213
112214 struct IcuTokenizer {
112215   sqlite3_tokenizer base;
112216   char *zLocale;
112217 };
112218
112219 struct IcuCursor {
112220   sqlite3_tokenizer_cursor base;
112221
112222   UBreakIterator *pIter;      /* ICU break-iterator object */
112223   int nChar;                  /* Number of UChar elements in pInput */
112224   UChar *aChar;               /* Copy of input using utf-16 encoding */
112225   int *aOffset;               /* Offsets of each character in utf-8 input */
112226
112227   int nBuffer;
112228   char *zBuffer;
112229
112230   int iToken;
112231 };
112232
112233 /*
112234 ** Create a new tokenizer instance.
112235 */
112236 static int icuCreate(
112237   int argc,                            /* Number of entries in argv[] */
112238   const char * const *argv,            /* Tokenizer creation arguments */
112239   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
112240 ){
112241   IcuTokenizer *p;
112242   int n = 0;
112243
112244   if( argc>0 ){
112245     n = strlen(argv[0])+1;
112246   }
112247   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
112248   if( !p ){
112249     return SQLITE_NOMEM;
112250   }
112251   memset(p, 0, sizeof(IcuTokenizer));
112252
112253   if( n ){
112254     p->zLocale = (char *)&p[1];
112255     memcpy(p->zLocale, argv[0], n);
112256   }
112257
112258   *ppTokenizer = (sqlite3_tokenizer *)p;
112259
112260   return SQLITE_OK;
112261 }
112262
112263 /*
112264 ** Destroy a tokenizer
112265 */
112266 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
112267   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
112268   sqlite3_free(p);
112269   return SQLITE_OK;
112270 }
112271
112272 /*
112273 ** Prepare to begin tokenizing a particular string.  The input
112274 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
112275 ** used to incrementally tokenize this string is returned in 
112276 ** *ppCursor.
112277 */
112278 static int icuOpen(
112279   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
112280   const char *zInput,                    /* Input string */
112281   int nInput,                            /* Length of zInput in bytes */
112282   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
112283 ){
112284   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
112285   IcuCursor *pCsr;
112286
112287   const int32_t opt = U_FOLD_CASE_DEFAULT;
112288   UErrorCode status = U_ZERO_ERROR;
112289   int nChar;
112290
112291   UChar32 c;
112292   int iInput = 0;
112293   int iOut = 0;
112294
112295   *ppCursor = 0;
112296
112297   if( nInput<0 ){
112298     nInput = strlen(zInput);
112299   }
112300   nChar = nInput+1;
112301   pCsr = (IcuCursor *)sqlite3_malloc(
112302       sizeof(IcuCursor) +                /* IcuCursor */
112303       nChar * sizeof(UChar) +            /* IcuCursor.aChar[] */
112304       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
112305   );
112306   if( !pCsr ){
112307     return SQLITE_NOMEM;
112308   }
112309   memset(pCsr, 0, sizeof(IcuCursor));
112310   pCsr->aChar = (UChar *)&pCsr[1];
112311   pCsr->aOffset = (int *)&pCsr->aChar[nChar];
112312
112313   pCsr->aOffset[iOut] = iInput;
112314   U8_NEXT(zInput, iInput, nInput, c); 
112315   while( c>0 ){
112316     int isError = 0;
112317     c = u_foldCase(c, opt);
112318     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
112319     if( isError ){
112320       sqlite3_free(pCsr);
112321       return SQLITE_ERROR;
112322     }
112323     pCsr->aOffset[iOut] = iInput;
112324
112325     if( iInput<nInput ){
112326       U8_NEXT(zInput, iInput, nInput, c);
112327     }else{
112328       c = 0;
112329     }
112330   }
112331
112332   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
112333   if( !U_SUCCESS(status) ){
112334     sqlite3_free(pCsr);
112335     return SQLITE_ERROR;
112336   }
112337   pCsr->nChar = iOut;
112338
112339   ubrk_first(pCsr->pIter);
112340   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
112341   return SQLITE_OK;
112342 }
112343
112344 /*
112345 ** Close a tokenization cursor previously opened by a call to icuOpen().
112346 */
112347 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
112348   IcuCursor *pCsr = (IcuCursor *)pCursor;
112349   ubrk_close(pCsr->pIter);
112350   sqlite3_free(pCsr->zBuffer);
112351   sqlite3_free(pCsr);
112352   return SQLITE_OK;
112353 }
112354
112355 /*
112356 ** Extract the next token from a tokenization cursor.
112357 */
112358 static int icuNext(
112359   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
112360   const char **ppToken,               /* OUT: *ppToken is the token text */
112361   int *pnBytes,                       /* OUT: Number of bytes in token */
112362   int *piStartOffset,                 /* OUT: Starting offset of token */
112363   int *piEndOffset,                   /* OUT: Ending offset of token */
112364   int *piPosition                     /* OUT: Position integer of token */
112365 ){
112366   IcuCursor *pCsr = (IcuCursor *)pCursor;
112367
112368   int iStart = 0;
112369   int iEnd = 0;
112370   int nByte = 0;
112371
112372   while( iStart==iEnd ){
112373     UChar32 c;
112374
112375     iStart = ubrk_current(pCsr->pIter);
112376     iEnd = ubrk_next(pCsr->pIter);
112377     if( iEnd==UBRK_DONE ){
112378       return SQLITE_DONE;
112379     }
112380
112381     while( iStart<iEnd ){
112382       int iWhite = iStart;
112383       U8_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
112384       if( u_isspace(c) ){
112385         iStart = iWhite;
112386       }else{
112387         break;
112388       }
112389     }
112390     assert(iStart<=iEnd);
112391   }
112392
112393   do {
112394     UErrorCode status = U_ZERO_ERROR;
112395     if( nByte ){
112396       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
112397       if( !zNew ){
112398         return SQLITE_NOMEM;
112399       }
112400       pCsr->zBuffer = zNew;
112401       pCsr->nBuffer = nByte;
112402     }
112403
112404     u_strToUTF8(
112405         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
112406         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
112407         &status                                  /* Output success/failure */
112408     );
112409   } while( nByte>pCsr->nBuffer );
112410
112411   *ppToken = pCsr->zBuffer;
112412   *pnBytes = nByte;
112413   *piStartOffset = pCsr->aOffset[iStart];
112414   *piEndOffset = pCsr->aOffset[iEnd];
112415   *piPosition = pCsr->iToken++;
112416
112417   return SQLITE_OK;
112418 }
112419
112420 /*
112421 ** The set of routines that implement the simple tokenizer
112422 */
112423 static const sqlite3_tokenizer_module icuTokenizerModule = {
112424   0,                           /* iVersion */
112425   icuCreate,                   /* xCreate  */
112426   icuDestroy,                  /* xCreate  */
112427   icuOpen,                     /* xOpen    */
112428   icuClose,                    /* xClose   */
112429   icuNext,                     /* xNext    */
112430 };
112431
112432 /*
112433 ** Set *ppModule to point at the implementation of the ICU tokenizer.
112434 */
112435 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
112436   sqlite3_tokenizer_module const**ppModule
112437 ){
112438   *ppModule = &icuTokenizerModule;
112439 }
112440
112441 #endif /* defined(SQLITE_ENABLE_ICU) */
112442 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
112443
112444 /************** End of fts3_icu.c ********************************************/